lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
apache-2.0
e6df8d5904dc763611eb4ae3eeed83d57dd8d301
0
Esri/cordova-plugin-advanced-geolocation,Esri/cordova-plugin-advanced-geolocation,andygup/cordova-plugin-advanced-geolocation,geostarters/cordova-plugin-advanced-geolocation,geostarters/cordova-plugin-advanced-geolocation,Esri/cordova-plugin-advanced-geolocation,andygup/cordova-plugin-advanced-geolocation,geostarters/cordova-plugin-advanced-geolocation,andygup/cordova-plugin-advanced-geolocation
/** * @author Andy Gup * * Copyright 2016 Esri * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License.​ */ package com.esri.cordova.geolocation.controllers; /** * IMPORTANT: This Class is only compatible with API Level 17 or greater * Reference: https://developer.android.com/reference/android/telephony/CellInfo.html */ import android.content.Context; import android.os.Build; import android.os.Looper; import android.telephony.CellInfo; import android.telephony.CellInfoCdma; import android.telephony.CellInfoGsm; import android.telephony.CellInfoLte; import android.telephony.CellInfoWcdma; import android.telephony.CellLocation; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.telephony.cdma.CdmaCellLocation; import android.telephony.gsm.GsmCellLocation; import android.util.Log; import com.esri.cordova.geolocation.utils.ErrorMessages; import com.esri.cordova.geolocation.utils.JSONHelper; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.PluginResult; import java.util.List; public final class CellLocationController implements Runnable{ public static final String CELLINFO_PROVIDER = "cell"; private static final String TAG = "GeolocationPlugin"; private static CallbackContext _callbackContext; // Threadsafe private static TelephonyManager _telephonyManager = null; private static PhoneStateListener _phoneStateListener = null; private static CordovaInterface _cordova; private static boolean _isConnected = false; public CellLocationController( boolean isConnected, CordovaInterface cordova, CallbackContext callbackContext ){ _isConnected = isConnected; _cordova = cordova; _callbackContext = callbackContext; } public void run(){ // There are minimum OS version requirements if(versionCheck()){ // Reference: http://developer.android.com/reference/android/os/Process.html#THREAD_PRIORITY_BACKGROUND android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); // We are running a Looper to allow the Cordova CallbackContext to be passed within the Thread as a message. if(Looper.myLooper() == null){ _telephonyManager = (TelephonyManager) _cordova.getActivity().getSystemService(Context.TELEPHONY_SERVICE); Looper.prepare(); startLocation(); Looper.loop(); } } else { Log.e(TAG, ErrorMessages.CELL_DATA_MIN_VERSION().message); sendCallback(PluginResult.Status.ERROR, JSONHelper.errorJSON(CELLINFO_PROVIDER, ErrorMessages.CELL_DATA_MIN_VERSION())); } } public void startLocation(){ if(!Thread.currentThread().isInterrupted()){ Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable throwable) { Log.d(TAG, "Failing gracefully after detecting an uncaught exception on CellLocationController thread. " + throwable.getMessage()); sendCallback(PluginResult.Status.ERROR, JSONHelper.errorJSON(CELLINFO_PROVIDER, ErrorMessages.UNCAUGHT_THREAD_EXCEPTION())); stopLocation(); } }); if(_isConnected){ // Set up a change listener setPhoneStateListener(); // Return a snapshot of all cell info getAllCellInfos(); Log.d(TAG, "Starting CellLocationController"); } else { Log.e(TAG, "Unable to start CellLocationController: no internet connection."); sendCallback(PluginResult.Status.ERROR, JSONHelper.errorJSON(CELLINFO_PROVIDER, ErrorMessages.CELL_DATA_NOT_AVAILABLE())); } } } /** * Full stop using brute force. Works with many Android versions. */ public void stopLocation(){ if(_phoneStateListener != null && _telephonyManager != null){ _telephonyManager.listen(_phoneStateListener, PhoneStateListener.LISTEN_NONE); _phoneStateListener = null; _telephonyManager = null; Thread.currentThread().interrupt(); Log.d(TAG, "Stopping PhoneStateListener"); } } /** * Returns all observed cell information from all radios on the device including the primary and * neighboring cells. Calling this method does not trigger a call to onCellInfoChanged(), or change * the rate at which onCellInfoChanged() is called. */ private void getAllCellInfos(){ if(_telephonyManager != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { final List<CellInfo> cellInfos = _telephonyManager.getAllCellInfo(); processCellInfos(cellInfos); } else { Log.w(TAG, "Unable to provide cell info due to version restriction"); } } private void setPhoneStateListener(){ _phoneStateListener = new PhoneStateListener(){ @Override public void onCellLocationChanged(CellLocation location){ if(location instanceof CdmaCellLocation){ final CdmaCellLocation cellLocationCdma = (CdmaCellLocation) location; sendCallback(PluginResult.Status.OK, JSONHelper.cdmaCellLocationJSON(cellLocationCdma)); } if(location instanceof GsmCellLocation){ final GsmCellLocation cellLocationGsm = (GsmCellLocation) location; sendCallback(PluginResult.Status.OK, JSONHelper.gsmCellLocationJSON(cellLocationGsm)); } } }; _telephonyManager.listen(_phoneStateListener, PhoneStateListener.LISTEN_CELL_LOCATION); } private static void processCellInfos(List<CellInfo> cellInfos){ if(cellInfos != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ for(CellInfo cellInfo : cellInfos){ if(cellInfo instanceof CellInfoWcdma){ final CellInfoWcdma cellInfoWcdma = (CellInfoWcdma) cellInfo; sendCallback(PluginResult.Status.OK, JSONHelper.cellInfoWCDMAJSON(cellInfoWcdma)); } if(cellInfo instanceof CellInfoGsm){ final CellInfoGsm cellInfoGsm = (CellInfoGsm) cellInfo; sendCallback(PluginResult.Status.OK, JSONHelper.cellInfoGSMJSON(cellInfoGsm)); } if(cellInfo instanceof CellInfoCdma){ final CellInfoCdma cellIdentityCdma = (CellInfoCdma) cellInfo; sendCallback(PluginResult.Status.OK, JSONHelper.cellInfoCDMAJSON(cellIdentityCdma)); } if(cellInfo instanceof CellInfoLte){ final CellInfoLte cellInfoLte = (CellInfoLte) cellInfo; sendCallback(PluginResult.Status.OK, JSONHelper.cellInfoLTEJSON(cellInfoLte)); } Log.d(TAG,cellInfo.toString()); } } else { Log.e(TAG, "CellInfoLocation returning null. Is it supported on this phone?"); // There are several reasons as to why cell location data would be null. // * could be an older device running an unsupported version of the Android OS // * could be a device that doesn't support this capability. // * could be incorrect permissions: ACCESS_COARSE_LOCATION sendCallback(PluginResult.Status.ERROR, JSONHelper.errorJSON(CELLINFO_PROVIDER, ErrorMessages.CELL_DATA_IS_NULL())); } } /** * This Class will not work correctly on older versions of the Android SDK * Reference: http://developer.android.com/reference/android/telephony/TelephonyManager.html#getAllCellInfo() */ private static boolean versionCheck(){ boolean verified = true; final int version = Build.VERSION.SDK_INT; if(version < Build.VERSION_CODES.LOLLIPOP){ verified = false; } return verified; } private static void sendCallback(PluginResult.Status status, String message){ if(!Thread.interrupted()){ final PluginResult result = new PluginResult(status, message); result.setKeepCallback(true); _callbackContext.sendPluginResult(result); } } }
src/com/esri/cordova/geolocation/controllers/CellLocationController.java
/** * @author Andy Gup * * Copyright 2016 Esri * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License.​ */ package com.esri.cordova.geolocation.controllers; /** * IMPORTANT: This Class is only compatible with API Level 17 or greater * Reference: https://developer.android.com/reference/android/telephony/CellInfo.html */ import android.content.Context; import android.os.Build; import android.os.Looper; import android.telephony.CellInfo; import android.telephony.CellInfoCdma; import android.telephony.CellInfoGsm; import android.telephony.CellInfoLte; import android.telephony.CellInfoWcdma; import android.telephony.CellLocation; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.telephony.cdma.CdmaCellLocation; import android.telephony.gsm.GsmCellLocation; import android.util.Log; import com.esri.cordova.geolocation.utils.JSONHelper; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.PluginResult; import java.util.List; public final class CellLocationController implements Runnable{ public static final String CELLINFO_PROVIDER = "cell"; private static final String TAG = "GeolocationPlugin"; private static final int MIN_BUILD_VER = 21; private static CallbackContext _callbackContext; // Threadsafe private static TelephonyManager _telephonyManager = null; private static PhoneStateListener _phoneStateListener = null; private static CordovaInterface _cordova; private static boolean _isConnected = false; public CellLocationController( boolean isConnected, CordovaInterface cordova, CallbackContext callbackContext ){ _isConnected = isConnected; _cordova = cordova; _callbackContext = callbackContext; } public void run(){ // There are minimum OS version requirements if(versionCheck()){ // Reference: http://developer.android.com/reference/android/os/Process.html#THREAD_PRIORITY_BACKGROUND android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); // We are running a Looper to allow the Cordova CallbackContext to be passed within the Thread as a message. if(Looper.myLooper() == null){ _telephonyManager = (TelephonyManager) _cordova.getActivity().getSystemService(Context.TELEPHONY_SERVICE); Looper.prepare(); startLocation(); Looper.loop(); } } } public void startLocation(){ if(!Thread.currentThread().isInterrupted()){ Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable throwable) { Log.d(TAG, "Failing gracefully after detecting an uncaught exception on CellLocationController thread. " + throwable.getMessage()); stopLocation(); } }); if(_isConnected){ // Set up a change listener setPhoneStateListener(); // Return a snapshot of all cell info getAllCellInfos(); Log.d(TAG, "Starting CellLocationController"); } else { Log.e(TAG, "Unable to start CellLocationController: no internet connection."); } } } /** * Full stop using brute force. Works with many Android versions. */ public void stopLocation(){ if(_phoneStateListener != null && _telephonyManager != null){ _telephonyManager.listen(_phoneStateListener, PhoneStateListener.LISTEN_NONE); _phoneStateListener = null; _telephonyManager = null; Thread.currentThread().interrupt(); Log.d(TAG, "Stopping PhoneStateListener"); } } /** * Returns all observed cell information from all radios on the device including the primary and * neighboring cells. Calling this method does not trigger a call to onCellInfoChanged(), or change * the rate at which onCellInfoChanged() is called. */ private void getAllCellInfos(){ if(_telephonyManager != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { final List<CellInfo> cellInfos = _telephonyManager.getAllCellInfo(); processCellInfos(cellInfos); } else { Log.w(TAG, "Unable to provide cell info due to version restriction"); } } private void setPhoneStateListener(){ _phoneStateListener = new PhoneStateListener(){ @Override public void onCellLocationChanged(CellLocation location){ if(location instanceof CdmaCellLocation){ final CdmaCellLocation cellLocationCdma = (CdmaCellLocation) location; sendCallback(PluginResult.Status.OK, JSONHelper.cdmaCellLocationJSON(cellLocationCdma)); } if(location instanceof GsmCellLocation){ final GsmCellLocation cellLocationGsm = (GsmCellLocation) location; sendCallback(PluginResult.Status.OK, JSONHelper.gsmCellLocationJSON(cellLocationGsm)); } } }; _telephonyManager.listen(_phoneStateListener, PhoneStateListener.LISTEN_CELL_LOCATION); } private static void processCellInfos(List<CellInfo> cellInfos){ if(cellInfos != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ for(CellInfo cellInfo : cellInfos){ if(cellInfo instanceof CellInfoWcdma){ final CellInfoWcdma cellInfoWcdma = (CellInfoWcdma) cellInfo; sendCallback(PluginResult.Status.OK, JSONHelper.cellInfoWCDMAJSON(cellInfoWcdma)); } if(cellInfo instanceof CellInfoGsm){ final CellInfoGsm cellInfoGsm = (CellInfoGsm) cellInfo; sendCallback(PluginResult.Status.OK, JSONHelper.cellInfoGSMJSON(cellInfoGsm)); } if(cellInfo instanceof CellInfoCdma){ final CellInfoCdma cellIdentityCdma = (CellInfoCdma) cellInfo; sendCallback(PluginResult.Status.OK, JSONHelper.cellInfoCDMAJSON(cellIdentityCdma)); } if(cellInfo instanceof CellInfoLte){ final CellInfoLte cellInfoLte = (CellInfoLte) cellInfo; sendCallback(PluginResult.Status.OK, JSONHelper.cellInfoLTEJSON(cellInfoLte)); } Log.d(TAG,cellInfo.toString()); } } else { Log.e(TAG, "CellInfoLocation returning null. Is it supported on this phone?"); // There are several reasons as to why cell location data would be null. // * could be an older device running an unsupported version of the Android OS // * could be a device that doesn't support this capability. // * could be incorrect permissions: ACCESS_COARSE_LOCATION sendCallback(PluginResult.Status.ERROR, JSONHelper.errorJSON(CELLINFO_PROVIDER, "Cell location data is returning as null")); } } /** * This Class will not work correctly on older versions of the Android SDK * Reference: http://developer.android.com/reference/android/telephony/TelephonyManager.html#getAllCellInfo() */ private static boolean versionCheck(){ boolean verified = true; final int version = Build.VERSION.SDK_INT; if(version < MIN_BUILD_VER){ Log.e(TAG, "WARNING: A minimum SDK v17 is required for CellLocation to work, and minimum SDK v21 is REQUIRED for this library."); verified = false; } return verified; } private static void sendCallback(PluginResult.Status status, String message){ if(!Thread.interrupted()){ final PluginResult result = new PluginResult(status, message); result.setKeepCallback(true); _callbackContext.sendPluginResult(result); } } }
Updated error messages in CellLocationController
src/com/esri/cordova/geolocation/controllers/CellLocationController.java
Updated error messages in CellLocationController
<ide><path>rc/com/esri/cordova/geolocation/controllers/CellLocationController.java <ide> import android.telephony.gsm.GsmCellLocation; <ide> import android.util.Log; <ide> <add>import com.esri.cordova.geolocation.utils.ErrorMessages; <ide> import com.esri.cordova.geolocation.utils.JSONHelper; <ide> <ide> import org.apache.cordova.CallbackContext; <ide> <ide> public static final String CELLINFO_PROVIDER = "cell"; <ide> private static final String TAG = "GeolocationPlugin"; <del> private static final int MIN_BUILD_VER = 21; <ide> private static CallbackContext _callbackContext; // Threadsafe <ide> private static TelephonyManager _telephonyManager = null; <ide> private static PhoneStateListener _phoneStateListener = null; <ide> Looper.loop(); <ide> } <ide> } <add> else { <add> Log.e(TAG, ErrorMessages.CELL_DATA_MIN_VERSION().message); <add> sendCallback(PluginResult.Status.ERROR, <add> JSONHelper.errorJSON(CELLINFO_PROVIDER, ErrorMessages.CELL_DATA_MIN_VERSION())); <add> } <ide> } <ide> <ide> public void startLocation(){ <ide> public void uncaughtException(Thread thread, Throwable throwable) { <ide> Log.d(TAG, "Failing gracefully after detecting an uncaught exception on CellLocationController thread. " <ide> + throwable.getMessage()); <add> sendCallback(PluginResult.Status.ERROR, <add> JSONHelper.errorJSON(CELLINFO_PROVIDER, ErrorMessages.UNCAUGHT_THREAD_EXCEPTION())); <ide> stopLocation(); <ide> } <ide> }); <ide> } <ide> else { <ide> Log.e(TAG, "Unable to start CellLocationController: no internet connection."); <add> sendCallback(PluginResult.Status.ERROR, <add> JSONHelper.errorJSON(CELLINFO_PROVIDER, ErrorMessages.CELL_DATA_NOT_AVAILABLE())); <ide> } <ide> } <ide> } <ide> // * could be a device that doesn't support this capability. <ide> // * could be incorrect permissions: ACCESS_COARSE_LOCATION <ide> sendCallback(PluginResult.Status.ERROR, <del> JSONHelper.errorJSON(CELLINFO_PROVIDER, "Cell location data is returning as null")); <add> JSONHelper.errorJSON(CELLINFO_PROVIDER, ErrorMessages.CELL_DATA_IS_NULL())); <ide> } <ide> } <ide> <ide> private static boolean versionCheck(){ <ide> boolean verified = true; <ide> final int version = Build.VERSION.SDK_INT; <del> if(version < MIN_BUILD_VER){ <del> Log.e(TAG, "WARNING: A minimum SDK v17 is required for CellLocation to work, and minimum SDK v21 is REQUIRED for this library."); <add> if(version < Build.VERSION_CODES.LOLLIPOP){ <ide> verified = false; <ide> } <ide>
Java
mit
7d4450ed35865b9405bdc26d400d7e75e520a22b
0
BenjaminMalley/graphql-java,graphql-java/graphql-java,graphql-java/graphql-java,ChiralBehaviors/graphql-java,blevandowski-lv/graphql-java,kroepke/graphql-java,blevandowski-lv/graphql-java,dminkovsky/graphql-java,fderose/graphql-java,fderose/graphql-java,erikogenvik/graphql-java,dminkovsky/graphql-java
package graphql.parser; import graphql.ShouldNotHappenException; import graphql.language.*; import graphql.parser.antlr.GraphqlBaseVisitor; import graphql.parser.antlr.GraphqlParser; import org.antlr.v4.runtime.ParserRuleContext; import java.math.BigDecimal; import java.util.ArrayDeque; import java.util.Deque; public class GraphqlAntlrToLanguage extends GraphqlBaseVisitor<Void> { Document result; private enum ContextProperty { OperationDefinition, FragmentDefinition, Field, InlineFragment, FragmentSpread, SelectionSet, VariableDefinition, ListType, NonNullType, Directive } static class ContextEntry { ContextProperty contextProperty; Object value; public ContextEntry(ContextProperty contextProperty, Object value) { this.contextProperty = contextProperty; this.value = value; } } private Deque<ContextEntry> contextStack = new ArrayDeque<>(); private void addContextProperty(ContextProperty contextProperty, Object value) { switch (contextProperty) { case SelectionSet: newSelectionSet((SelectionSet) value); break; case Field: newField((Field) value); break; } contextStack.addFirst(new ContextEntry(contextProperty, value)); } private void popContext() { contextStack.removeFirst(); } private Object getFromContextStack(ContextProperty contextProperty) { return getFromContextStack(contextProperty, false); } private Object getFromContextStack(ContextProperty contextProperty, boolean required) { for (ContextEntry contextEntry : contextStack) { if (contextEntry.contextProperty == contextProperty) { return contextEntry.value; } } if (required) throw new RuntimeException("not found" + contextProperty); return null; } private void newSelectionSet(SelectionSet selectionSet) { for (ContextEntry contextEntry : contextStack) { if (contextEntry.contextProperty == ContextProperty.Field) { ((Field) contextEntry.value).setSelectionSet(selectionSet); break; } else if (contextEntry.contextProperty == ContextProperty.OperationDefinition) { ((OperationDefinition) contextEntry.value).setSelectionSet(selectionSet); break; } else if (contextEntry.contextProperty == ContextProperty.FragmentDefinition) { ((FragmentDefinition) contextEntry.value).setSelectionSet(selectionSet); break; } else if (contextEntry.contextProperty == ContextProperty.InlineFragment) { ((InlineFragment) contextEntry.value).setSelectionSet(selectionSet); break; } } } private void newField(Field field) { ((SelectionSet) getFromContextStack(ContextProperty.SelectionSet)).getSelections().add(field); } @Override public Void visitDocument( GraphqlParser.DocumentContext ctx) { result = new Document(); newNode(result, ctx); return super.visitDocument(ctx); } @Override public Void visitOperationDefinition( GraphqlParser.OperationDefinitionContext ctx) { OperationDefinition operationDefinition; operationDefinition = new OperationDefinition(); newNode(operationDefinition, ctx); newNode(operationDefinition, ctx); if (ctx.operationType() == null) { operationDefinition.setOperation(OperationDefinition.Operation.QUERY); } else { operationDefinition.setOperation(parseOperation(ctx.operationType())); } if (ctx.NAME() != null) { operationDefinition.setName(ctx.NAME().getText()); } result.getDefinitions().add(operationDefinition); addContextProperty(ContextProperty.OperationDefinition, operationDefinition); super.visitOperationDefinition(ctx); popContext(); return null; } private OperationDefinition.Operation parseOperation(GraphqlParser.OperationTypeContext operationTypeContext) { if (operationTypeContext.getText().equals("query")) { return OperationDefinition.Operation.QUERY; } else if (operationTypeContext.getText().equals("mutation")) { return OperationDefinition.Operation.MUTATION; } else { throw new RuntimeException(); } } @Override public Void visitFragmentSpread( GraphqlParser.FragmentSpreadContext ctx) { FragmentSpread fragmentSpread = new FragmentSpread(ctx.fragmentName().getText()); newNode(fragmentSpread, ctx); ((SelectionSet) getFromContextStack(ContextProperty.SelectionSet)).getSelections().add(fragmentSpread); addContextProperty(ContextProperty.FragmentSpread, fragmentSpread); super.visitFragmentSpread(ctx); popContext(); return null; } @Override public Void visitVariableDefinition( GraphqlParser.VariableDefinitionContext ctx) { VariableDefinition variableDefinition = new VariableDefinition(); newNode(variableDefinition, ctx); variableDefinition.setName(ctx.variable().NAME().getText()); if (ctx.defaultValue() != null) { Value value = getValue(ctx.defaultValue().value()); variableDefinition.setDefaultValue(value); } OperationDefinition operationDefiniton = (OperationDefinition) getFromContextStack(ContextProperty.OperationDefinition); operationDefiniton.getVariableDefinitions().add(variableDefinition); addContextProperty(ContextProperty.VariableDefinition, variableDefinition); super.visitVariableDefinition(ctx); popContext(); return null; } @Override public Void visitFragmentDefinition( GraphqlParser.FragmentDefinitionContext ctx) { FragmentDefinition fragmentDefinition = new FragmentDefinition(); newNode(fragmentDefinition, ctx); fragmentDefinition.setName(ctx.fragmentName().getText()); fragmentDefinition.setTypeCondition(new TypeName(ctx.typeCondition().getText())); addContextProperty(ContextProperty.FragmentDefinition, fragmentDefinition); result.getDefinitions().add(fragmentDefinition); super.visitFragmentDefinition(ctx); popContext(); return null; } @Override public Void visitSelectionSet( GraphqlParser.SelectionSetContext ctx) { SelectionSet newSelectionSet = new SelectionSet(); newNode(newSelectionSet, ctx); addContextProperty(ContextProperty.SelectionSet, newSelectionSet); super.visitSelectionSet(ctx); popContext(); return null; } @Override public Void visitField( GraphqlParser.FieldContext ctx) { Field newField = new Field(); newNode(newField, ctx); newField.setName(ctx.NAME().getText()); if (ctx.alias() != null) { newField.setAlias(ctx.alias().NAME().getText()); } addContextProperty(ContextProperty.Field, newField); super.visitField(ctx); popContext(); return null; } @Override public Void visitTypeName( GraphqlParser.TypeNameContext ctx) { TypeName typeName = new TypeName(ctx.NAME().getText()); newNode(typeName, ctx); for (ContextEntry contextEntry : contextStack) { if (contextEntry.value instanceof ListType) { ((ListType) contextEntry.value).setType(typeName); break; } if (contextEntry.value instanceof NonNullType) { ((NonNullType) contextEntry.value).setType(typeName); break; } if (contextEntry.value instanceof VariableDefinition) { ((VariableDefinition) contextEntry.value).setType(typeName); break; } } return super.visitTypeName(ctx); } @Override public Void visitNonNullType( GraphqlParser.NonNullTypeContext ctx) { NonNullType nonNullType = new NonNullType(); newNode(nonNullType, ctx); for (ContextEntry contextEntry : contextStack) { if (contextEntry.value instanceof ListType) { ((ListType) contextEntry.value).setType(nonNullType); break; } if (contextEntry.value instanceof VariableDefinition) { ((VariableDefinition) contextEntry.value).setType(nonNullType); break; } } addContextProperty(ContextProperty.NonNullType, nonNullType); super.visitNonNullType(ctx); popContext(); return null; } @Override public Void visitListType( GraphqlParser.ListTypeContext ctx) { ListType listType = new ListType(); newNode(listType, ctx); for (ContextEntry contextEntry : contextStack) { if (contextEntry.value instanceof ListType) { ((ListType) contextEntry.value).setType(listType); break; } if (contextEntry.value instanceof NonNullType) { ((NonNullType) contextEntry.value).setType(listType); break; } if (contextEntry.value instanceof VariableDefinition) { ((VariableDefinition) contextEntry.value).setType(listType); break; } } addContextProperty(ContextProperty.ListType, listType); super.visitListType(ctx); popContext(); return null; } @Override public Void visitArgument( GraphqlParser.ArgumentContext ctx) { Argument argument = new Argument(ctx.NAME().getText(), getValue(ctx.valueWithVariable())); newNode(argument, ctx); if (getFromContextStack(ContextProperty.Directive, false) != null) { ((Directive) getFromContextStack(ContextProperty.Directive)).getArguments().add(argument); } else { Field field = (Field) getFromContextStack(ContextProperty.Field); field.getArguments().add(argument); } return super.visitArgument(ctx); } @Override public Void visitInlineFragment( GraphqlParser.InlineFragmentContext ctx) { InlineFragment inlineFragment = new InlineFragment(new TypeName(ctx.typeCondition().getText())); newNode(inlineFragment, ctx); ((SelectionSet) getFromContextStack(ContextProperty.SelectionSet)).getSelections().add(inlineFragment); addContextProperty(ContextProperty.InlineFragment, inlineFragment); super.visitInlineFragment(ctx); popContext(); return null; } @Override public Void visitDirective( GraphqlParser.DirectiveContext ctx) { Directive directive = new Directive(ctx.NAME().getText()); newNode(directive, ctx); for (ContextEntry contextEntry : contextStack) { if (contextEntry.contextProperty == ContextProperty.Field) { ((Field) contextEntry.value).getDirectives().add(directive); break; } else if (contextEntry.contextProperty == ContextProperty.FragmentDefinition) { ((FragmentDefinition) contextEntry.value).getDirectives().add(directive); break; } else if (contextEntry.contextProperty == ContextProperty.FragmentSpread) { ((FragmentSpread) contextEntry.value).getDirectives().add(directive); break; } else if (contextEntry.contextProperty == ContextProperty.InlineFragment) { ((InlineFragment) contextEntry.value).getDirectives().add(directive); break; } else if (contextEntry.contextProperty == ContextProperty.OperationDefinition) { ((OperationDefinition) contextEntry.value).getDirectives().add(directive); break; } } addContextProperty(ContextProperty.Directive, directive); super.visitDirective(ctx); popContext(); return null; } private Value getValue(GraphqlParser.ValueWithVariableContext ctx) { if (ctx.IntValue() != null) { IntValue intValue = new IntValue(Integer.parseInt(ctx.IntValue().getText())); newNode(intValue, ctx); return intValue; } else if (ctx.FloatValue() != null) { FloatValue floatValue = new FloatValue(new BigDecimal(ctx.FloatValue().getText())); newNode(floatValue, ctx); return floatValue; } else if (ctx.BooleanValue() != null) { BooleanValue booleanValue = new BooleanValue(Boolean.parseBoolean(ctx.BooleanValue().getText())); newNode(booleanValue, ctx); return booleanValue; } else if (ctx.StringValue() != null) { StringValue stringValue = new StringValue(trimQuotes(ctx.StringValue().getText())); newNode(stringValue, ctx); return stringValue; } else if (ctx.enumValue() != null) { EnumValue enumValue = new EnumValue(ctx.enumValue().getText()); newNode(enumValue, ctx); return enumValue; } else if (ctx.arrayValueWithVariable() != null) { ArrayValue arrayValue = new ArrayValue(); newNode(arrayValue, ctx); for (GraphqlParser.ValueWithVariableContext valueWithVariableContext : ctx.arrayValueWithVariable().valueWithVariable()) { arrayValue.getValues().add(getValue(valueWithVariableContext)); } return arrayValue; } else if (ctx.objectValueWithVariable() != null) { ObjectValue objectValue = new ObjectValue(); newNode(objectValue, ctx); for (GraphqlParser.ObjectFieldWithVariableContext objectFieldWithVariableContext : ctx.objectValueWithVariable().objectFieldWithVariable()) { ObjectField objectField = new ObjectField(objectFieldWithVariableContext.NAME().getText(), getValue(objectFieldWithVariableContext.valueWithVariable())); objectValue.getObjectFields().add(objectField); } return objectValue; } else if (ctx.variable() != null) { VariableReference variableReference = new VariableReference(ctx.variable().NAME().getText()); newNode(variableReference, ctx); return variableReference; } throw new ShouldNotHappenException(); } private Value getValue(GraphqlParser.ValueContext ctx) { if (ctx.IntValue() != null) { IntValue intValue = new IntValue(Integer.parseInt(ctx.IntValue().getText())); newNode(intValue, ctx); return intValue; } else if (ctx.FloatValue() != null) { FloatValue floatValue = new FloatValue(new BigDecimal(ctx.FloatValue().getText())); newNode(floatValue, ctx); return floatValue; } else if (ctx.BooleanValue() != null) { BooleanValue booleanValue = new BooleanValue(Boolean.parseBoolean(ctx.BooleanValue().getText())); newNode(booleanValue, ctx); return booleanValue; } else if (ctx.StringValue() != null) { StringValue stringValue = new StringValue(trimQuotes(ctx.StringValue().getText())); newNode(stringValue, ctx); return stringValue; } else if (ctx.enumValue() != null) { EnumValue enumValue = new EnumValue(ctx.enumValue().getText()); newNode(enumValue, ctx); return enumValue; } else if (ctx.arrayValue() != null) { ArrayValue arrayValue = new ArrayValue(); newNode(arrayValue, ctx); for (GraphqlParser.ValueContext valueWithVariableContext : ctx.arrayValue().value()) { arrayValue.getValues().add(getValue(valueWithVariableContext)); } return arrayValue; } else if (ctx.objectValue() != null) { ObjectValue objectValue = new ObjectValue(); newNode(objectValue,ctx); for (GraphqlParser.ObjectFieldContext objectFieldContext : ctx.objectValue().objectField()) { ObjectField objectField = new ObjectField(objectFieldContext.NAME().getText(), getValue(objectFieldContext.value())); objectValue.getObjectFields().add(objectField); } return objectValue; } throw new ShouldNotHappenException(); } private String trimQuotes(String string) { return string.substring(1, string.length() - 1); } private void newNode(AbstractNode abstractNode, ParserRuleContext parserRuleContext) { abstractNode.setSourceLocation(getSourceLocation(parserRuleContext)); } private SourceLocation getSourceLocation(ParserRuleContext parserRuleContext) { return new SourceLocation(parserRuleContext.getStart().getLine(), parserRuleContext.getStart().getCharPositionInLine()+1); } }
src/main/java/graphql/parser/GraphqlAntlrToLanguage.java
package graphql.parser; import graphql.ShouldNotHappenException; import graphql.language.*; import graphql.parser.antlr.GraphqlBaseVisitor; import graphql.parser.antlr.GraphqlParser; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.misc.NotNull; import java.math.BigDecimal; import java.util.ArrayDeque; import java.util.Deque; public class GraphqlAntlrToLanguage extends GraphqlBaseVisitor<Void> { Document result; private enum ContextProperty { OperationDefinition, FragmentDefinition, Field, InlineFragment, FragmentSpread, SelectionSet, VariableDefinition, ListType, NonNullType, Directive } static class ContextEntry { ContextProperty contextProperty; Object value; public ContextEntry(ContextProperty contextProperty, Object value) { this.contextProperty = contextProperty; this.value = value; } } private Deque<ContextEntry> contextStack = new ArrayDeque<>(); private void addContextProperty(ContextProperty contextProperty, Object value) { switch (contextProperty) { case SelectionSet: newSelectionSet((SelectionSet) value); break; case Field: newField((Field) value); break; } contextStack.addFirst(new ContextEntry(contextProperty, value)); } private void popContext() { contextStack.removeFirst(); } private Object getFromContextStack(ContextProperty contextProperty) { return getFromContextStack(contextProperty, false); } private Object getFromContextStack(ContextProperty contextProperty, boolean required) { for (ContextEntry contextEntry : contextStack) { if (contextEntry.contextProperty == contextProperty) { return contextEntry.value; } } if (required) throw new RuntimeException("not found" + contextProperty); return null; } private void newSelectionSet(SelectionSet selectionSet) { for (ContextEntry contextEntry : contextStack) { if (contextEntry.contextProperty == ContextProperty.Field) { ((Field) contextEntry.value).setSelectionSet(selectionSet); break; } else if (contextEntry.contextProperty == ContextProperty.OperationDefinition) { ((OperationDefinition) contextEntry.value).setSelectionSet(selectionSet); break; } else if (contextEntry.contextProperty == ContextProperty.FragmentDefinition) { ((FragmentDefinition) contextEntry.value).setSelectionSet(selectionSet); break; } else if (contextEntry.contextProperty == ContextProperty.InlineFragment) { ((InlineFragment) contextEntry.value).setSelectionSet(selectionSet); break; } } } private void newField(Field field) { ((SelectionSet) getFromContextStack(ContextProperty.SelectionSet)).getSelections().add(field); } @Override public Void visitDocument(@NotNull GraphqlParser.DocumentContext ctx) { result = new Document(); newNode(result, ctx); return super.visitDocument(ctx); } @Override public Void visitOperationDefinition(@NotNull GraphqlParser.OperationDefinitionContext ctx) { OperationDefinition operationDefinition; operationDefinition = new OperationDefinition(); newNode(operationDefinition, ctx); newNode(operationDefinition, ctx); if (ctx.operationType() == null) { operationDefinition.setOperation(OperationDefinition.Operation.QUERY); } else { operationDefinition.setOperation(parseOperation(ctx.operationType())); } if (ctx.NAME() != null) { operationDefinition.setName(ctx.NAME().getText()); } result.getDefinitions().add(operationDefinition); addContextProperty(ContextProperty.OperationDefinition, operationDefinition); super.visitOperationDefinition(ctx); popContext(); return null; } private OperationDefinition.Operation parseOperation(GraphqlParser.OperationTypeContext operationTypeContext) { if (operationTypeContext.getText().equals("query")) { return OperationDefinition.Operation.QUERY; } else if (operationTypeContext.getText().equals("mutation")) { return OperationDefinition.Operation.MUTATION; } else { throw new RuntimeException(); } } @Override public Void visitFragmentSpread(@NotNull GraphqlParser.FragmentSpreadContext ctx) { FragmentSpread fragmentSpread = new FragmentSpread(ctx.fragmentName().getText()); newNode(fragmentSpread, ctx); ((SelectionSet) getFromContextStack(ContextProperty.SelectionSet)).getSelections().add(fragmentSpread); addContextProperty(ContextProperty.FragmentSpread, fragmentSpread); super.visitFragmentSpread(ctx); popContext(); return null; } @Override public Void visitVariableDefinition(@NotNull GraphqlParser.VariableDefinitionContext ctx) { VariableDefinition variableDefinition = new VariableDefinition(); newNode(variableDefinition, ctx); variableDefinition.setName(ctx.variable().NAME().getText()); if (ctx.defaultValue() != null) { Value value = getValue(ctx.defaultValue().value()); variableDefinition.setDefaultValue(value); } OperationDefinition operationDefiniton = (OperationDefinition) getFromContextStack(ContextProperty.OperationDefinition); operationDefiniton.getVariableDefinitions().add(variableDefinition); addContextProperty(ContextProperty.VariableDefinition, variableDefinition); super.visitVariableDefinition(ctx); popContext(); return null; } @Override public Void visitFragmentDefinition(@NotNull GraphqlParser.FragmentDefinitionContext ctx) { FragmentDefinition fragmentDefinition = new FragmentDefinition(); newNode(fragmentDefinition, ctx); fragmentDefinition.setName(ctx.fragmentName().getText()); fragmentDefinition.setTypeCondition(new TypeName(ctx.typeCondition().getText())); addContextProperty(ContextProperty.FragmentDefinition, fragmentDefinition); result.getDefinitions().add(fragmentDefinition); super.visitFragmentDefinition(ctx); popContext(); return null; } @Override public Void visitSelectionSet(@NotNull GraphqlParser.SelectionSetContext ctx) { SelectionSet newSelectionSet = new SelectionSet(); newNode(newSelectionSet, ctx); addContextProperty(ContextProperty.SelectionSet, newSelectionSet); super.visitSelectionSet(ctx); popContext(); return null; } @Override public Void visitField(@NotNull GraphqlParser.FieldContext ctx) { Field newField = new Field(); newNode(newField, ctx); newField.setName(ctx.NAME().getText()); if (ctx.alias() != null) { newField.setAlias(ctx.alias().NAME().getText()); } addContextProperty(ContextProperty.Field, newField); super.visitField(ctx); popContext(); return null; } @Override public Void visitTypeName(@NotNull GraphqlParser.TypeNameContext ctx) { TypeName typeName = new TypeName(ctx.NAME().getText()); newNode(typeName, ctx); for (ContextEntry contextEntry : contextStack) { if (contextEntry.value instanceof ListType) { ((ListType) contextEntry.value).setType(typeName); break; } if (contextEntry.value instanceof NonNullType) { ((NonNullType) contextEntry.value).setType(typeName); break; } if (contextEntry.value instanceof VariableDefinition) { ((VariableDefinition) contextEntry.value).setType(typeName); break; } } return super.visitTypeName(ctx); } @Override public Void visitNonNullType(@NotNull GraphqlParser.NonNullTypeContext ctx) { NonNullType nonNullType = new NonNullType(); newNode(nonNullType, ctx); for (ContextEntry contextEntry : contextStack) { if (contextEntry.value instanceof ListType) { ((ListType) contextEntry.value).setType(nonNullType); break; } if (contextEntry.value instanceof VariableDefinition) { ((VariableDefinition) contextEntry.value).setType(nonNullType); break; } } addContextProperty(ContextProperty.NonNullType, nonNullType); super.visitNonNullType(ctx); popContext(); return null; } @Override public Void visitListType(@NotNull GraphqlParser.ListTypeContext ctx) { ListType listType = new ListType(); newNode(listType, ctx); for (ContextEntry contextEntry : contextStack) { if (contextEntry.value instanceof ListType) { ((ListType) contextEntry.value).setType(listType); break; } if (contextEntry.value instanceof NonNullType) { ((NonNullType) contextEntry.value).setType(listType); break; } if (contextEntry.value instanceof VariableDefinition) { ((VariableDefinition) contextEntry.value).setType(listType); break; } } addContextProperty(ContextProperty.ListType, listType); super.visitListType(ctx); popContext(); return null; } @Override public Void visitArgument(@NotNull GraphqlParser.ArgumentContext ctx) { Argument argument = new Argument(ctx.NAME().getText(), getValue(ctx.valueWithVariable())); newNode(argument, ctx); if (getFromContextStack(ContextProperty.Directive, false) != null) { ((Directive) getFromContextStack(ContextProperty.Directive)).getArguments().add(argument); } else { Field field = (Field) getFromContextStack(ContextProperty.Field); field.getArguments().add(argument); } return super.visitArgument(ctx); } @Override public Void visitInlineFragment(@NotNull GraphqlParser.InlineFragmentContext ctx) { InlineFragment inlineFragment = new InlineFragment(new TypeName(ctx.typeCondition().getText())); newNode(inlineFragment, ctx); ((SelectionSet) getFromContextStack(ContextProperty.SelectionSet)).getSelections().add(inlineFragment); addContextProperty(ContextProperty.InlineFragment, inlineFragment); super.visitInlineFragment(ctx); popContext(); return null; } @Override public Void visitDirective(@NotNull GraphqlParser.DirectiveContext ctx) { Directive directive = new Directive(ctx.NAME().getText()); newNode(directive, ctx); for (ContextEntry contextEntry : contextStack) { if (contextEntry.contextProperty == ContextProperty.Field) { ((Field) contextEntry.value).getDirectives().add(directive); break; } else if (contextEntry.contextProperty == ContextProperty.FragmentDefinition) { ((FragmentDefinition) contextEntry.value).getDirectives().add(directive); break; } else if (contextEntry.contextProperty == ContextProperty.FragmentSpread) { ((FragmentSpread) contextEntry.value).getDirectives().add(directive); break; } else if (contextEntry.contextProperty == ContextProperty.InlineFragment) { ((InlineFragment) contextEntry.value).getDirectives().add(directive); break; } else if (contextEntry.contextProperty == ContextProperty.OperationDefinition) { ((OperationDefinition) contextEntry.value).getDirectives().add(directive); break; } } addContextProperty(ContextProperty.Directive, directive); super.visitDirective(ctx); popContext(); return null; } private Value getValue(GraphqlParser.ValueWithVariableContext ctx) { if (ctx.IntValue() != null) { IntValue intValue = new IntValue(Integer.parseInt(ctx.IntValue().getText())); newNode(intValue, ctx); return intValue; } else if (ctx.FloatValue() != null) { FloatValue floatValue = new FloatValue(new BigDecimal(ctx.FloatValue().getText())); newNode(floatValue, ctx); return floatValue; } else if (ctx.BooleanValue() != null) { BooleanValue booleanValue = new BooleanValue(Boolean.parseBoolean(ctx.BooleanValue().getText())); newNode(booleanValue, ctx); return booleanValue; } else if (ctx.StringValue() != null) { StringValue stringValue = new StringValue(trimQuotes(ctx.StringValue().getText())); newNode(stringValue, ctx); return stringValue; } else if (ctx.enumValue() != null) { EnumValue enumValue = new EnumValue(ctx.enumValue().getText()); newNode(enumValue, ctx); return enumValue; } else if (ctx.arrayValueWithVariable() != null) { ArrayValue arrayValue = new ArrayValue(); newNode(arrayValue, ctx); for (GraphqlParser.ValueWithVariableContext valueWithVariableContext : ctx.arrayValueWithVariable().valueWithVariable()) { arrayValue.getValues().add(getValue(valueWithVariableContext)); } return arrayValue; } else if (ctx.objectValueWithVariable() != null) { ObjectValue objectValue = new ObjectValue(); newNode(objectValue, ctx); for (GraphqlParser.ObjectFieldWithVariableContext objectFieldWithVariableContext : ctx.objectValueWithVariable().objectFieldWithVariable()) { ObjectField objectField = new ObjectField(objectFieldWithVariableContext.NAME().getText(), getValue(objectFieldWithVariableContext.valueWithVariable())); objectValue.getObjectFields().add(objectField); } return objectValue; } else if (ctx.variable() != null) { VariableReference variableReference = new VariableReference(ctx.variable().NAME().getText()); newNode(variableReference, ctx); return variableReference; } throw new ShouldNotHappenException(); } private Value getValue(GraphqlParser.ValueContext ctx) { if (ctx.IntValue() != null) { IntValue intValue = new IntValue(Integer.parseInt(ctx.IntValue().getText())); newNode(intValue, ctx); return intValue; } else if (ctx.FloatValue() != null) { FloatValue floatValue = new FloatValue(new BigDecimal(ctx.FloatValue().getText())); newNode(floatValue, ctx); return floatValue; } else if (ctx.BooleanValue() != null) { BooleanValue booleanValue = new BooleanValue(Boolean.parseBoolean(ctx.BooleanValue().getText())); newNode(booleanValue, ctx); return booleanValue; } else if (ctx.StringValue() != null) { StringValue stringValue = new StringValue(trimQuotes(ctx.StringValue().getText())); newNode(stringValue, ctx); return stringValue; } else if (ctx.enumValue() != null) { EnumValue enumValue = new EnumValue(ctx.enumValue().getText()); newNode(enumValue, ctx); return enumValue; } else if (ctx.arrayValue() != null) { ArrayValue arrayValue = new ArrayValue(); newNode(arrayValue, ctx); for (GraphqlParser.ValueContext valueWithVariableContext : ctx.arrayValue().value()) { arrayValue.getValues().add(getValue(valueWithVariableContext)); } return arrayValue; } else if (ctx.objectValue() != null) { ObjectValue objectValue = new ObjectValue(); newNode(objectValue,ctx); for (GraphqlParser.ObjectFieldContext objectFieldContext : ctx.objectValue().objectField()) { ObjectField objectField = new ObjectField(objectFieldContext.NAME().getText(), getValue(objectFieldContext.value())); objectValue.getObjectFields().add(objectField); } return objectValue; } throw new ShouldNotHappenException(); } private String trimQuotes(String string) { return string.substring(1, string.length() - 1); } private void newNode(AbstractNode abstractNode, ParserRuleContext parserRuleContext) { abstractNode.setSourceLocation(getSourceLocation(parserRuleContext)); } private SourceLocation getSourceLocation(ParserRuleContext parserRuleContext) { return new SourceLocation(parserRuleContext.getStart().getLine(), parserRuleContext.getStart().getCharPositionInLine()+1); } }
removed deprecated nonNull annotation
src/main/java/graphql/parser/GraphqlAntlrToLanguage.java
removed deprecated nonNull annotation
<ide><path>rc/main/java/graphql/parser/GraphqlAntlrToLanguage.java <ide> import graphql.parser.antlr.GraphqlBaseVisitor; <ide> import graphql.parser.antlr.GraphqlParser; <ide> import org.antlr.v4.runtime.ParserRuleContext; <del>import org.antlr.v4.runtime.misc.NotNull; <ide> <ide> import java.math.BigDecimal; <ide> import java.util.ArrayDeque; <ide> <ide> <ide> @Override <del> public Void visitDocument(@NotNull GraphqlParser.DocumentContext ctx) { <add> public Void visitDocument( GraphqlParser.DocumentContext ctx) { <ide> result = new Document(); <ide> newNode(result, ctx); <ide> return super.visitDocument(ctx); <ide> } <ide> <ide> @Override <del> public Void visitOperationDefinition(@NotNull GraphqlParser.OperationDefinitionContext ctx) { <add> public Void visitOperationDefinition( GraphqlParser.OperationDefinitionContext ctx) { <ide> OperationDefinition operationDefinition; <ide> operationDefinition = new OperationDefinition(); <ide> newNode(operationDefinition, ctx); <ide> } <ide> <ide> @Override <del> public Void visitFragmentSpread(@NotNull GraphqlParser.FragmentSpreadContext ctx) { <add> public Void visitFragmentSpread( GraphqlParser.FragmentSpreadContext ctx) { <ide> FragmentSpread fragmentSpread = new FragmentSpread(ctx.fragmentName().getText()); <ide> newNode(fragmentSpread, ctx); <ide> ((SelectionSet) getFromContextStack(ContextProperty.SelectionSet)).getSelections().add(fragmentSpread); <ide> } <ide> <ide> @Override <del> public Void visitVariableDefinition(@NotNull GraphqlParser.VariableDefinitionContext ctx) { <add> public Void visitVariableDefinition( GraphqlParser.VariableDefinitionContext ctx) { <ide> VariableDefinition variableDefinition = new VariableDefinition(); <ide> newNode(variableDefinition, ctx); <ide> variableDefinition.setName(ctx.variable().NAME().getText()); <ide> } <ide> <ide> @Override <del> public Void visitFragmentDefinition(@NotNull GraphqlParser.FragmentDefinitionContext ctx) { <add> public Void visitFragmentDefinition( GraphqlParser.FragmentDefinitionContext ctx) { <ide> FragmentDefinition fragmentDefinition = new FragmentDefinition(); <ide> newNode(fragmentDefinition, ctx); <ide> fragmentDefinition.setName(ctx.fragmentName().getText()); <ide> <ide> <ide> @Override <del> public Void visitSelectionSet(@NotNull GraphqlParser.SelectionSetContext ctx) { <add> public Void visitSelectionSet( GraphqlParser.SelectionSetContext ctx) { <ide> SelectionSet newSelectionSet = new SelectionSet(); <ide> newNode(newSelectionSet, ctx); <ide> addContextProperty(ContextProperty.SelectionSet, newSelectionSet); <ide> <ide> <ide> @Override <del> public Void visitField(@NotNull GraphqlParser.FieldContext ctx) { <add> public Void visitField( GraphqlParser.FieldContext ctx) { <ide> Field newField = new Field(); <ide> newNode(newField, ctx); <ide> newField.setName(ctx.NAME().getText()); <ide> } <ide> <ide> @Override <del> public Void visitTypeName(@NotNull GraphqlParser.TypeNameContext ctx) { <add> public Void visitTypeName( GraphqlParser.TypeNameContext ctx) { <ide> TypeName typeName = new TypeName(ctx.NAME().getText()); <ide> newNode(typeName, ctx); <ide> for (ContextEntry contextEntry : contextStack) { <ide> } <ide> <ide> @Override <del> public Void visitNonNullType(@NotNull GraphqlParser.NonNullTypeContext ctx) { <add> public Void visitNonNullType( GraphqlParser.NonNullTypeContext ctx) { <ide> NonNullType nonNullType = new NonNullType(); <ide> newNode(nonNullType, ctx); <ide> for (ContextEntry contextEntry : contextStack) { <ide> } <ide> <ide> @Override <del> public Void visitListType(@NotNull GraphqlParser.ListTypeContext ctx) { <add> public Void visitListType( GraphqlParser.ListTypeContext ctx) { <ide> ListType listType = new ListType(); <ide> newNode(listType, ctx); <ide> for (ContextEntry contextEntry : contextStack) { <ide> } <ide> <ide> @Override <del> public Void visitArgument(@NotNull GraphqlParser.ArgumentContext ctx) { <add> public Void visitArgument( GraphqlParser.ArgumentContext ctx) { <ide> Argument argument = new Argument(ctx.NAME().getText(), getValue(ctx.valueWithVariable())); <ide> newNode(argument, ctx); <ide> if (getFromContextStack(ContextProperty.Directive, false) != null) { <ide> } <ide> <ide> @Override <del> public Void visitInlineFragment(@NotNull GraphqlParser.InlineFragmentContext ctx) { <add> public Void visitInlineFragment( GraphqlParser.InlineFragmentContext ctx) { <ide> InlineFragment inlineFragment = new InlineFragment(new TypeName(ctx.typeCondition().getText())); <ide> newNode(inlineFragment, ctx); <ide> ((SelectionSet) getFromContextStack(ContextProperty.SelectionSet)).getSelections().add(inlineFragment); <ide> } <ide> <ide> @Override <del> public Void visitDirective(@NotNull GraphqlParser.DirectiveContext ctx) { <add> public Void visitDirective( GraphqlParser.DirectiveContext ctx) { <ide> Directive directive = new Directive(ctx.NAME().getText()); <ide> newNode(directive, ctx); <ide> for (ContextEntry contextEntry : contextStack) {
Java
mit
error: pathspec 'langton/gui/LangtonGUI.java' did not match any file(s) known to git
4da4aa53c66dfc5fb68477e35a44fb2789791b3a
1
joelabr/Laborationer-Programmering-1
package langton.gui; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import javax.swing.*; public class LangtonGUI extends JFrame { private BufferedImage planeImage; public LangtonGUI() { super("Lagton's Ant"); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(800, 600); setResizable(false); planeImage = createPlane(800, 600); } private BufferedImage createPlane(int width, int height) { if (width <= 0 && height <= 0) return null; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics g = image.createGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); g.dispose(); return image; } public void paint(Graphics g) { super.paint(g); if (planeImage != null) g.drawImage(planeImage, 0, 0, null); } public static void main(String[] args) { LangtonGUI gui = new LangtonGUI(); gui.setVisible(true); } }
langton/gui/LangtonGUI.java
Begin work on GUI for Langton's Ant
langton/gui/LangtonGUI.java
Begin work on GUI for Langton's Ant
<ide><path>angton/gui/LangtonGUI.java <add>package langton.gui; <add> <add>import java.awt.Color; <add>import java.awt.Graphics; <add>import java.awt.image.BufferedImage; <add>import javax.swing.*; <add> <add>public class LangtonGUI extends JFrame <add>{ <add> private BufferedImage planeImage; <add> <add> public LangtonGUI() <add> { <add> super("Lagton's Ant"); <add> <add> setDefaultCloseOperation(EXIT_ON_CLOSE); <add> setSize(800, 600); <add> setResizable(false); <add> <add> planeImage = createPlane(800, 600); <add> } <add> <add> private BufferedImage createPlane(int width, int height) <add> { <add> if (width <= 0 && height <= 0) <add> return null; <add> <add> BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); <add> <add> Graphics g = image.createGraphics(); <add> <add> g.setColor(Color.WHITE); <add> g.fillRect(0, 0, width, height); <add> <add> g.dispose(); <add> <add> return image; <add> } <add> <add> public void paint(Graphics g) <add> { <add> super.paint(g); <add> <add> if (planeImage != null) <add> g.drawImage(planeImage, 0, 0, null); <add> } <add> <add> public static void main(String[] args) <add> { <add> LangtonGUI gui = new LangtonGUI(); <add> gui.setVisible(true); <add> } <add>}
Java
mit
5c3177238a632c17cc41d187dbad3fd3bc19bf82
0
Reaction-Framework/react-native-image2d,Reaction-Framework/react-native-image2d,Reaction-Framework/react-native-canvas,Reaction-Framework/react-native-canvas,Reaction-Framework/react-native-canvas,Reaction-Framework/react-native-image2d
package io.reactionframework.android.react.image.image2d; import android.graphics.Rect; import android.net.Uri; import android.util.Log; import com.facebook.react.bridge.*; import java.util.HashMap; import java.util.Map; public class Image2DContextModule extends ReactContextBaseJavaModule { private static final String LOG_TAG = Image2DContextModule.class.getSimpleName(); private static final String REACT_MODULE = "RCTIONImage2DContextModule"; private static Map<String, Image2DContext> mImage2DContexts; private static Map<String, Image2DContext> getImage2DContexts() { return mImage2DContexts == null ? (mImage2DContexts = new HashMap<>()) : mImage2DContexts; } private final ReactApplicationContext mContext; public Image2DContextModule(ReactApplicationContext reactContext) { super(reactContext); mContext = reactContext; } @Override public String getName() { return REACT_MODULE; } private Image2DContext createImage2DContext() { Image2DContext context = new Image2DContext(mContext); getImage2DContexts().put(context.getId(), context); return context; } private Image2DContext getImage2DContext(String id) { return getImage2DContexts().get(id); } private void releaseImage2DContext(String id) { Image2DContext context = getImage2DContext(id); context.release(); getImage2DContexts().remove(id); } private void rejectWithException(Promise promise, Throwable exception) { Log.e(LOG_TAG, exception.getMessage()); exception.printStackTrace(); promise.reject(exception.getMessage()); } @ReactMethod public void create(ReadableMap options, Promise promise) { Image2DContext context = createImage2DContext(); try { if (!options.hasKey("maxWidth") || !options.hasKey("maxHeight")) { throw new IllegalArgumentException("Image2DContext requires maxWidth and maxHeight arguments."); } int maxWidth = options.getInt("maxWidth"); int maxHeight = options.getInt("maxHeight"); if (options.hasKey("fileUrl")) { context.createFromFileUrl(options.getString("fileUrl"), maxWidth, maxHeight); promise.resolve(context.getId()); return; } if (options.hasKey("base64String")) { context.createFromBase64String(options.getString("base64String"), maxWidth, maxHeight); promise.resolve(context.getId()); return; } throw new IllegalArgumentException("Image2DContext requires fileUrl or base64String arguments."); } catch (Exception e) { releaseImage2DContext(context.getId()); rejectWithException(promise, e); } } @ReactMethod public void save(ReadableMap options, Promise promise) { try { Uri fileUrl = getImage2DContext(options.getString("id")).save(options.getMap("params").getString("fileName")); if (fileUrl == null) { throw new RuntimeException("Image2DContext could not been saved."); } promise.resolve(fileUrl.toString()); } catch (Exception e) { rejectWithException(promise, e); } } @ReactMethod public void getAsBase64String(ReadableMap options, Promise promise) { try { promise.resolve(getImage2DContext(options.getString("id")).getAsBase64String()); } catch (Exception e) { rejectWithException(promise, e); } } @ReactMethod public void getWidth(ReadableMap options, Promise promise) { try { promise.resolve(getImage2DContext(options.getString("id")).getWidth()); } catch (Exception e) { rejectWithException(promise, e); } } @ReactMethod public void getHeight(ReadableMap options, Promise promise) { try { promise.resolve(getImage2DContext(options.getString("id")).getHeight()); } catch (Exception e) { rejectWithException(promise, e); } } @ReactMethod public void crop(ReadableMap options, Promise promise) { try { Image2DContext image2DContext = getImage2DContext(options.getString("id")); ReadableMap params = options.getMap("params"); image2DContext.crop(new Rect( params.getInt("left"), params.getInt("top"), image2DContext.getWidth() - params.getInt("right"), image2DContext.getHeight() - params.getInt("bottom") )); promise.resolve(null); } catch (Exception e) { rejectWithException(promise, e); } } @ReactMethod public void drawBorder(ReadableMap options, Promise promise) { try { Image2DContext image2DContext = getImage2DContext(options.getString("id")); ReadableMap params = options.getMap("params"); String borderColor = params.getString("color"); image2DContext.drawBorder(new Rect( params.getInt("left"), params.getInt("top"), params.getInt("right"), params.getInt("bottom") ), borderColor); promise.resolve(null); } catch (Exception e) { rejectWithException(promise, e); } } @ReactMethod public void release(ReadableMap options, Promise promise) { releaseImage2DContext(options.getString("id")); promise.resolve(null); } }
android/src/main/java/io/reactionframework/android/react/image/image2d/Image2DContextModule.java
package io.reactionframework.android.react.image.image2d; import android.graphics.Rect; import android.net.Uri; import android.util.Log; import com.facebook.react.bridge.*; import java.util.HashMap; import java.util.Map; public class Image2DContextModule extends ReactContextBaseJavaModule { private static final String LOG_TAG = Image2DContextModule.class.getSimpleName(); private static final String REACT_MODULE = "Image2DContextModule"; private static Map<String, Image2DContext> mImage2DContexts; private static Map<String, Image2DContext> getImage2DContexts() { return mImage2DContexts == null ? (mImage2DContexts = new HashMap<>()) : mImage2DContexts; } private final ReactApplicationContext mContext; public Image2DContextModule(ReactApplicationContext reactContext) { super(reactContext); mContext = reactContext; } @Override public String getName() { return REACT_MODULE; } private Image2DContext createImage2DContext() { Image2DContext context = new Image2DContext(mContext); getImage2DContexts().put(context.getId(), context); return context; } private Image2DContext getImage2DContext(String id) { return getImage2DContexts().get(id); } private void releaseImage2DContext(String id) { Image2DContext context = getImage2DContext(id); context.release(); getImage2DContexts().remove(id); } private void rejectWithException(Promise promise, Throwable exception) { Log.e(LOG_TAG, exception.getMessage()); exception.printStackTrace(); promise.reject(exception.getMessage()); } @ReactMethod public void create(ReadableMap options, Promise promise) { Image2DContext context = createImage2DContext(); try { if (!options.hasKey("maxWidth") || !options.hasKey("maxHeight")) { throw new IllegalArgumentException("Image2DContext requires maxWidth and maxHeight arguments."); } int maxWidth = options.getInt("maxWidth"); int maxHeight = options.getInt("maxHeight"); if (options.hasKey("fileUrl")) { context.createFromFileUrl(options.getString("fileUrl"), maxWidth, maxHeight); promise.resolve(context.getId()); return; } if (options.hasKey("base64String")) { context.createFromBase64String(options.getString("base64String"), maxWidth, maxHeight); promise.resolve(context.getId()); return; } throw new IllegalArgumentException("Image2DContext requires fileUrl or base64String arguments."); } catch (Exception e) { releaseImage2DContext(context.getId()); rejectWithException(promise, e); } } @ReactMethod public void save(ReadableMap options, Promise promise) { try { Uri fileUrl = getImage2DContext(options.getString("id")).save(options.getMap("params").getString("fileName")); if (fileUrl == null) { throw new RuntimeException("Image2DContext could not been saved."); } promise.resolve(fileUrl.toString()); } catch (Exception e) { rejectWithException(promise, e); } } @ReactMethod public void getAsBase64String(ReadableMap options, Promise promise) { try { promise.resolve(getImage2DContext(options.getString("id")).getAsBase64String()); } catch (Exception e) { rejectWithException(promise, e); } } @ReactMethod public void getWidth(ReadableMap options, Promise promise) { try { promise.resolve(getImage2DContext(options.getString("id")).getWidth()); } catch (Exception e) { rejectWithException(promise, e); } } @ReactMethod public void getHeight(ReadableMap options, Promise promise) { try { promise.resolve(getImage2DContext(options.getString("id")).getHeight()); } catch (Exception e) { rejectWithException(promise, e); } } @ReactMethod public void crop(ReadableMap options, Promise promise) { try { Image2DContext image2DContext = getImage2DContext(options.getString("id")); ReadableMap params = options.getMap("params"); image2DContext.crop(new Rect( params.getInt("left"), params.getInt("top"), image2DContext.getWidth() - params.getInt("right"), image2DContext.getHeight() - params.getInt("bottom") )); promise.resolve(null); } catch (Exception e) { rejectWithException(promise, e); } } @ReactMethod public void drawBorder(ReadableMap options, Promise promise) { try { Image2DContext image2DContext = getImage2DContext(options.getString("id")); ReadableMap params = options.getMap("params"); String borderColor = params.getString("color"); image2DContext.drawBorder(new Rect( params.getInt("left"), params.getInt("top"), params.getInt("right"), params.getInt("bottom") ), borderColor); promise.resolve(null); } catch (Exception e) { rejectWithException(promise, e); } } @ReactMethod public void release(ReadableMap options, Promise promise) { releaseImage2DContext(options.getString("id")); promise.resolve(null); } }
Android export name module fix
android/src/main/java/io/reactionframework/android/react/image/image2d/Image2DContextModule.java
Android export name module fix
<ide><path>ndroid/src/main/java/io/reactionframework/android/react/image/image2d/Image2DContextModule.java <ide> <ide> public class Image2DContextModule extends ReactContextBaseJavaModule { <ide> private static final String LOG_TAG = Image2DContextModule.class.getSimpleName(); <del> private static final String REACT_MODULE = "Image2DContextModule"; <add> private static final String REACT_MODULE = "RCTIONImage2DContextModule"; <ide> <ide> private static Map<String, Image2DContext> mImage2DContexts; <ide>
Java
apache-2.0
78f279165b3315ef15857a8a39b066c6d4ce8370
0
dasein-cloud/dasein-cloud-openstack,mariapavlova/dasein-cloud-openstack,daniellemayne/dasein-cloud-openstack_old,drewlyall/dasein-cloud-openstack,maksimov/dasein-cloud-openstack,daniellemayne/dasein-cloud-openstack,maksimov/dasein-cloud-openstack_old,greese/dasein-cloud-openstack
/** * Copyright (C) 2009-2013 Dell, Inc. * See annotations for authorship information * * ==================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ package org.dasein.cloud.openstack.nova.os.compute; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.codec.binary.Base64; import org.apache.commons.net.util.SubnetUtils; import org.apache.http.HttpStatus; import org.apache.log4j.Logger; import org.dasein.cloud.CloudErrorType; import org.dasein.cloud.CloudException; import org.dasein.cloud.InternalException; import org.dasein.cloud.OperationNotSupportedException; import org.dasein.cloud.ResourceStatus; import org.dasein.cloud.compute.AbstractVMSupport; import org.dasein.cloud.compute.Architecture; import org.dasein.cloud.compute.MachineImage; import org.dasein.cloud.compute.Platform; import org.dasein.cloud.compute.VMLaunchOptions; import org.dasein.cloud.compute.VirtualMachine; import org.dasein.cloud.compute.VirtualMachineCapabilities; import org.dasein.cloud.compute.VirtualMachineProduct; import org.dasein.cloud.compute.VirtualMachineProductFilterOptions; import org.dasein.cloud.compute.VmState; import org.dasein.cloud.network.Firewall; import org.dasein.cloud.network.FirewallSupport; import org.dasein.cloud.network.IPVersion; import org.dasein.cloud.network.IpAddress; import org.dasein.cloud.network.IpAddressSupport; import org.dasein.cloud.network.NetworkServices; import org.dasein.cloud.network.RawAddress; import org.dasein.cloud.network.VLAN; import org.dasein.cloud.network.VLANSupport; import org.dasein.cloud.network.Subnet; import org.dasein.cloud.openstack.nova.os.NovaException; import org.dasein.cloud.openstack.nova.os.NovaMethod; import org.dasein.cloud.openstack.nova.os.NovaOpenStack; import org.dasein.cloud.openstack.nova.os.OpenStackProvider; import org.dasein.cloud.openstack.nova.os.network.NovaNetworkServices; import org.dasein.cloud.openstack.nova.os.network.Quantum; import org.dasein.cloud.util.APITrace; import org.dasein.cloud.util.Cache; import org.dasein.cloud.util.CacheLevel; import org.dasein.util.CalendarWrapper; import org.dasein.util.uom.storage.Gigabyte; import org.dasein.util.uom.storage.Megabyte; import org.dasein.util.uom.storage.Storage; import org.dasein.util.uom.time.Day; import org.dasein.util.uom.time.TimePeriod; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * Implements services supporting interaction with cloud virtual machines. * @author George Reese ([email protected]) * @version 2012.09 addressed issue with alternate security group lookup in some OpenStack environments (issue #1) * @version 2013.02 implemented setting kernel/ramdisk image IDs (see issue #40 in dasein-cloud-core) * @version 2013.02 updated with support for Dasein Cloud 2013.02 model * @version 2013.02 added support for fetching shell keys (issue #4) * @since unknown */ public class NovaServer extends AbstractVMSupport<NovaOpenStack> { static private final Logger logger = NovaOpenStack.getLogger(NovaServer.class, "std"); static public final String SERVICE = "compute"; NovaServer(NovaOpenStack provider) { super(provider); } private @Nonnull String getTenantId() throws CloudException, InternalException { return ((NovaOpenStack)getProvider()).getAuthenticationContext().getTenantId(); } private transient volatile NovaServerCapabilities capabilities; @Nonnull @Override public VirtualMachineCapabilities getCapabilities() throws InternalException, CloudException { if( capabilities == null ) { capabilities = new NovaServerCapabilities(getProvider()); } return capabilities; } @Override public @Nonnull String getConsoleOutput(@Nonnull String vmId) throws CloudException, InternalException { APITrace.begin(getProvider(), "VM.getConsoleOutput"); try { VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } HashMap<String,Object> json = new HashMap<String,Object>(); json.put("os-getConsoleOutput", new HashMap<String,Object>()); NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); String console = method.postServersForString("/servers", vmId, new JSONObject(json), true); return (console == null ? "" : console); } finally { APITrace.end(); } } @Override public @Nullable VirtualMachineProduct getProduct(@Nonnull String productId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.getProduct"); try { for( VirtualMachineProduct product : listProducts(Architecture.I64) ) { if( product.getProviderProductId().equals(productId) ) { return product; } } return null; } finally { APITrace.end(); } } @Override public @Nullable VirtualMachine getVirtualMachine(@Nonnull String vmId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.getVirtualMachine"); try { NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); JSONObject ob = method.getServers("/servers", vmId, true); if( ob == null ) { return null; } Iterable<IpAddress> ipv4, ipv6; Iterable<VLAN> networks; NetworkServices services = getProvider().getNetworkServices(); if( services != null ) { IpAddressSupport support = services.getIpAddressSupport(); if( support != null ) { ipv4 = support.listIpPool(IPVersion.IPV4, false); ipv6 = support.listIpPool(IPVersion.IPV6, false); } else { ipv4 = ipv6 = Collections.emptyList(); } VLANSupport vs = services.getVlanSupport(); if( vs != null ) { networks = vs.listVlans(); } else { networks = Collections.emptyList(); } } else { ipv4 = ipv6 = Collections.emptyList(); networks = Collections.emptyList(); } try { if( ob.has("server") ) { JSONObject server = ob.getJSONObject("server"); VirtualMachine vm = toVirtualMachine(server, ipv4, ipv6, networks); if( vm != null ) { return vm; } } } catch( JSONException e ) { logger.error("getVirtualMachine(): Unable to identify expected values in JSON: " + e.getMessage()); throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for servers"); } return null; } finally { APITrace.end(); } } @Override public boolean isSubscribed() throws CloudException, InternalException { APITrace.begin(getProvider(), "VM.isSubscribed"); try { return (getProvider().testContext() != null); } finally { APITrace.end(); } } @Override public @Nonnull VirtualMachine launch(@Nonnull VMLaunchOptions options) throws CloudException, InternalException { APITrace.begin(getProvider(), "VM.launch"); try { MachineImage targetImage = getProvider().getComputeServices().getImageSupport().getImage(options.getMachineImageId()); if( targetImage == null ) { throw new CloudException("No such machine image: " + options.getMachineImageId()); } HashMap<String,Object> wrapper = new HashMap<String,Object>(); HashMap<String,Object> json = new HashMap<String,Object>(); NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); json.put("name", options.getHostName()); if( options.getUserData() != null ) { try { json.put("user_data", Base64.encodeBase64String(options.getUserData().getBytes("utf-8"))); } catch( UnsupportedEncodingException e ) { throw new InternalException(e); } } if( ((NovaOpenStack)getProvider()).getMinorVersion() == 0 && ((NovaOpenStack)getProvider()).getMajorVersion() == 1 ) { json.put("imageId", String.valueOf(options.getMachineImageId())); json.put("flavorId", options.getStandardProductId()); } else { if( getProvider().getProviderName().equals("HP") ) { json.put("imageRef", options.getMachineImageId()); } else { json.put("imageRef", ((NovaOpenStack)getProvider()).getComputeServices().getImageSupport().getImageRef(options.getMachineImageId())); } json.put("flavorRef", getFlavorRef(options.getStandardProductId())); } if( options.getVlanId() != null && ((NovaOpenStack)getProvider()).isRackspace() ) { ArrayList<Map<String,Object>> vlans = new ArrayList<Map<String, Object>>(); HashMap<String,Object> vlan = new HashMap<String, Object>(); vlan.put("uuid", options.getVlanId()); vlans.add(vlan); json.put("networks", vlans); } else { if( options.getVlanId() != null && !((NovaOpenStack)getProvider()).isRackspace() ) { NovaNetworkServices services = ((NovaOpenStack)getProvider()).getNetworkServices(); if( services != null ) { Quantum support = services.getVlanSupport(); if( support != null ) { ArrayList<Map<String,Object>> vlans = new ArrayList<Map<String, Object>>(); HashMap<String,Object> vlan = new HashMap<String, Object>(); try { vlan.put("port", support.createPort(options.getSubnetId(), options.getHostName())); vlans.add(vlan); json.put("networks", vlans); } catch (CloudException e) { if (e.getHttpCode() != 403) { throw new CloudException(e.getMessage()); } logger.warn("Unable to create port - trying to launch into general network"); Subnet subnet = support.getSubnet(options.getSubnetId()); vlan.put("uuid", subnet.getProviderVlanId()); vlans.add(vlan); json.put("networks", vlans); } } } } } if( options.getBootstrapKey() != null ) { json.put("key_name", options.getBootstrapKey()); } if( options.getFirewallIds().length > 0 ) { ArrayList<HashMap<String,Object>> firewalls = new ArrayList<HashMap<String,Object>>(); for( String id : options.getFirewallIds() ) { NetworkServices services = getProvider().getNetworkServices(); Firewall firewall = null; if( services != null ) { FirewallSupport support = services.getFirewallSupport(); if( support != null ) { firewall = support.getFirewall(id); } } if( firewall != null ) { HashMap<String,Object> fw = new HashMap<String, Object>(); fw.put("name", firewall.getName()); firewalls.add(fw); } } json.put("security_groups", firewalls); } if( !targetImage.getPlatform().equals(Platform.UNKNOWN) ) { options.withMetaData("org.dasein.platform", targetImage.getPlatform().name()); } options.withMetaData("org.dasein.description", options.getDescription()); json.put("metadata", options.getMetaData()); wrapper.put("server", json); JSONObject result = method.postServers("/servers", null, new JSONObject(wrapper), true); if( result.has("server") ) { try { Collection<IpAddress> ips = Collections.emptyList(); Collection<VLAN> nets = Collections.emptyList(); JSONObject server = result.getJSONObject("server"); VirtualMachine vm = toVirtualMachine(server, ips, ips, nets); if( vm != null ) { return vm; } } catch( JSONException e ) { logger.error("launch(): Unable to understand launch response: " + e.getMessage()); if( logger.isTraceEnabled() ) { e.printStackTrace(); } throw new CloudException(e); } } logger.error("launch(): No server was created by the launch attempt, and no error was returned"); throw new CloudException("No virtual machine was launched"); } finally { APITrace.end(); } } private @Nonnull Iterable<String> listFirewalls(@Nonnull String vmId, @Nonnull JSONObject server) throws InternalException, CloudException { try { if( server.has("security_groups") ) { NetworkServices services = getProvider().getNetworkServices(); Collection<Firewall> firewalls = null; if( services != null ) { FirewallSupport support = services.getFirewallSupport(); if( support != null ) { firewalls = support.list(); } } if( firewalls == null ) { firewalls = Collections.emptyList(); } JSONArray groups = server.getJSONArray("security_groups"); ArrayList<String> results = new ArrayList<String>(); for( int i=0; i<groups.length(); i++ ) { JSONObject group = groups.getJSONObject(i); String id = group.has("id") ? group.getString("id") : null; String name = group.has("name") ? group.getString("name") : null; if( id != null || name != null ) { for( Firewall fw : firewalls ) { if( id != null ) { if( id.equals(fw.getProviderFirewallId()) ) { results.add(id); } } else if( name.equals(fw.getName()) ) { results.add(fw.getProviderFirewallId()); } } } } return results; } else { ArrayList<String> results = new ArrayList<String>(); NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); JSONObject ob = method.getServers("/os-security-groups/servers", vmId + "/os-security-groups", true); if( ob != null ) { if( ob.has("security_groups") ) { JSONArray groups = ob.getJSONArray("security_groups"); for( int i=0; i<groups.length(); i++ ) { JSONObject group = groups.getJSONObject(i); if( group.has("id") ) { results.add(group.getString("id")); } } } } return results; } } catch( JSONException e ) { throw new CloudException(e); } } @Override public @Nonnull Iterable<String> listFirewalls(@Nonnull String vmId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.listFirewalls"); try { NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); JSONObject ob = method.getServers("/servers", vmId, true); if( ob == null ) { return Collections.emptyList(); } try { if( ob.has("server") ) { JSONObject server = ob.getJSONObject("server"); return listFirewalls(vmId, server); } throw new CloudException("No such server: " + vmId); } catch( JSONException e ) { logger.error("listFirewalls(): Unable to identify expected values in JSON: " + e.getMessage()); throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for servers"); } } finally { APITrace.end(); } } static public class FlavorRef { public String id; public String[][] links; VirtualMachineProduct product; public String toString() { return (id + " -> " + product); } } private @Nonnull Iterable<FlavorRef> listFlavors() throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.listFlavors"); try { Cache<FlavorRef> cache = Cache.getInstance(getProvider(), "flavorRefs", FlavorRef.class, CacheLevel.REGION_ACCOUNT, new TimePeriod<Day>(1, TimePeriod.DAY)); Iterable<FlavorRef> refs = cache.get(getContext()); if( refs != null ) { return refs; } NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); JSONObject ob = method.getServers("/flavors", null, true); ArrayList<FlavorRef> flavors = new ArrayList<FlavorRef>(); try { if( ob != null && ob.has("flavors") ) { JSONArray list = ob.getJSONArray("flavors"); for( int i=0; i<list.length(); i++ ) { JSONObject p = list.getJSONObject(i); FlavorRef ref = new FlavorRef(); if( p.has("id") ) { ref.id = p.getString("id"); } else { continue; } if( p.has("links") ) { JSONArray links = p.getJSONArray("links"); ref.links = new String[links.length()][]; for( int j=0; j<links.length(); j++ ) { JSONObject link = links.getJSONObject(j); ref.links[j] = new String[2]; if( link.has("rel") ) { ref.links[j][0] = link.getString("rel"); } if( link.has("href") ) { ref.links[j][1] = link.getString("href"); } } } else { ref.links = new String[0][]; } ref.product = toProduct(p); if( ref.product != null ) { flavors.add(ref); } } } } catch( JSONException e ) { logger.error("listProducts(): Unable to identify expected values in JSON: " + e.getMessage()); throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for flavors: " + e.getMessage()); } cache.put(getContext(), flavors); return flavors; } finally { APITrace.end(); } } public @Nullable String getFlavorRef(@Nonnull String flavorId) throws InternalException, CloudException { for( FlavorRef ref : listFlavors() ) { if( ref.id.equals(flavorId) ) { String def = null; for( String[] link : ref.links ) { if( link[0] != null && link[0].equals("self") && link[1] != null ) { return link[1]; } else if( def == null && link[1] != null ) { def = link[1]; } } return def; } } return null; } @Nonnull @Override public Iterable<VirtualMachineProduct> listProducts(@Nullable VirtualMachineProductFilterOptions options, @Nullable Architecture architecture) throws InternalException, CloudException { if( architecture != null && !architecture.equals(Architecture.I32) && !architecture.equals(Architecture.I64) ) { return Collections.emptyList(); } APITrace.begin(getProvider(), "VM.listProducts"); try { ArrayList<VirtualMachineProduct> products = new ArrayList<VirtualMachineProduct>(); for( FlavorRef flavor : listFlavors() ) { if (options != null) { if (options.matches(flavor.product)) { products.add(flavor.product); } } else { products.add(flavor.product); } } return products; } finally { APITrace.end(); } } @Override public @Nonnull Iterable<ResourceStatus> listVirtualMachineStatus() throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.listVirtualMachineStatus"); try { NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); JSONObject ob = method.getServers("/servers", null, true); ArrayList<ResourceStatus> servers = new ArrayList<ResourceStatus>(); try { if( ob != null && ob.has("servers") ) { JSONArray list = ob.getJSONArray("servers"); for( int i=0; i<list.length(); i++ ) { JSONObject server = list.getJSONObject(i); ResourceStatus vm = toStatus(server); if( vm != null ) { servers.add(vm); } } } } catch( JSONException e ) { logger.error("listVirtualMachines(): Unable to identify expected values in JSON: " + e.getMessage()); e.printStackTrace(); throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for servers in " + ob.toString()); } return servers; } finally { APITrace.end(); } } @Override public @Nonnull Iterable<VirtualMachine> listVirtualMachines() throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.listVirtualMachines"); try { NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); JSONObject ob = method.getServers("/servers", null, true); ArrayList<VirtualMachine> servers = new ArrayList<VirtualMachine>(); Iterable<IpAddress> ipv4 = Collections.emptyList(), ipv6 = Collections.emptyList(); Iterable<VLAN> nets = Collections.emptyList(); NetworkServices services = getProvider().getNetworkServices(); if( services != null ) { IpAddressSupport support = services.getIpAddressSupport(); if( support != null ) { ipv4 = support.listIpPool(IPVersion.IPV4, false); ipv6 = support.listIpPool(IPVersion.IPV6, false); } VLANSupport vs = services.getVlanSupport(); if( vs != null ) { nets = vs.listVlans(); } } try { if( ob != null && ob.has("servers") ) { JSONArray list = ob.getJSONArray("servers"); for( int i=0; i<list.length(); i++ ) { JSONObject server = list.getJSONObject(i); VirtualMachine vm = toVirtualMachine(server, ipv4, ipv6, nets); if( vm != null ) { servers.add(vm); } } } } catch( JSONException e ) { logger.error("listVirtualMachines(): Unable to identify expected values in JSON: " + e.getMessage()); e.printStackTrace(); throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for servers in " + ob.toString()); } return servers; } finally { APITrace.end(); } } @Override public void pause(@Nonnull String vmId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.pause"); try { VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } if( !supportsPauseUnpause(vm) ) { throw new OperationNotSupportedException("Pause/unpause is not supported in " + getProvider().getCloudName()); } HashMap<String,Object> json = new HashMap<String,Object>(); json.put("pause", null); NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); method.postServers("/servers", vmId, new JSONObject(json), true); } finally { APITrace.end(); } } @Override public void resume(@Nonnull String vmId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.resume"); try { VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } if( !supportsSuspendResume(vm) ) { throw new OperationNotSupportedException("Suspend/resume is not supported in " + getProvider().getCloudName()); } HashMap<String,Object> json = new HashMap<String,Object>(); json.put("resume", null); NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); method.postServers("/servers", vmId, new JSONObject(json), true); } finally { APITrace.end(); } } @Override public void start(@Nonnull String vmId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.start"); try { VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } if( !supportsStartStop(vm) ) { throw new OperationNotSupportedException("Start/stop is not supported in " + getProvider().getCloudName()); } HashMap<String,Object> json = new HashMap<String,Object>(); json.put("os-start", null); NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); method.postServers("/servers", vmId, new JSONObject(json), true); } finally { APITrace.end(); } } @Override public void stop(@Nonnull String vmId, boolean force) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.stop"); try { VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } if( !supportsStartStop(vm) ) { throw new OperationNotSupportedException("Start/stop is not supported in " + getProvider().getCloudName()); } HashMap<String,Object> json = new HashMap<String,Object>(); json.put("os-stop", null); NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); method.postServers("/servers", vmId, new JSONObject(json), true); } finally { APITrace.end(); } } @Override public void suspend(@Nonnull String vmId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.suspend"); try { VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } if( !supportsSuspendResume(vm) ) { throw new OperationNotSupportedException("Suspend/resume is not supported in " + getProvider().getCloudName()); } HashMap<String,Object> json = new HashMap<String,Object>(); json.put("suspend", null); NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); method.postServers("/servers", vmId, new JSONObject(json), true); } finally { APITrace.end(); } } @Override public void unpause(@Nonnull String vmId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.unpause"); try { VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } if( !supportsPauseUnpause(vm) ) { throw new OperationNotSupportedException("Pause/unpause is not supported in " + getProvider().getCloudName()); } HashMap<String,Object> json = new HashMap<String,Object>(); json.put("unpause", null); NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); method.postServers("/servers", vmId, new JSONObject(json), true); } finally { APITrace.end(); } } @Override public void reboot(@Nonnull String vmId) throws CloudException, InternalException { APITrace.begin(getProvider(), "VM.reboot"); try { HashMap<String,Object> json = new HashMap<String,Object>(); HashMap<String,Object> action = new HashMap<String,Object>(); action.put("type", "HARD"); json.put("reboot", action); NovaMethod method = new NovaMethod(((NovaOpenStack)getProvider())); method.postServers("/servers", vmId, new JSONObject(json), true); } finally { APITrace.end(); } } @Override public void terminate(@Nonnull String vmId, @Nullable String explanation) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.terminate"); try { NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); long timeout = System.currentTimeMillis() + CalendarWrapper.HOUR; do { try { method.deleteServers("/servers", vmId); return; } catch( NovaException e ) { if( e.getHttpCode() != HttpStatus.SC_CONFLICT ) { throw e; } } try { Thread.sleep(CalendarWrapper.MINUTE); } catch( InterruptedException e ) { /* ignore */ } } while( System.currentTimeMillis() < timeout ); } finally { APITrace.end(); } } private @Nullable VirtualMachineProduct toProduct(@Nullable JSONObject json) throws JSONException, InternalException, CloudException { if( json == null ) { return null; } VirtualMachineProduct product = new VirtualMachineProduct(); if( json.has("id") ) { product.setProviderProductId(json.getString("id")); } if( json.has("name") ) { product.setName(json.getString("name")); } if( json.has("description") ) { product.setDescription(json.getString("description")); } if( json.has("ram") ) { product.setRamSize(new Storage<Megabyte>(json.getInt("ram"), Storage.MEGABYTE)); } if( json.has("disk") ) { product.setRootVolumeSize(new Storage<Gigabyte>(json.getInt("disk"), Storage.GIGABYTE)); } product.setCpuCount(1); if( product.getProviderProductId() == null ) { return null; } if( product.getName() == null ) { product.setName(product.getProviderProductId()); } if( product.getDescription() == null ) { product.setDescription(product.getName()); } return product; } private @Nullable ResourceStatus toStatus(@Nullable JSONObject server) throws JSONException, InternalException, CloudException { if( server == null ) { return null; } String serverId = null; if( server.has("id") ) { serverId = server.getString("id"); } if( serverId == null ) { return null; } VmState state = VmState.PENDING; if( server.has("status") ) { String s = server.getString("status").toLowerCase(); if( s.equals("active") ) { state = VmState.RUNNING; } else if( s.equals("build") ) { state = VmState.PENDING; } else if( s.equals("deleted") ) { state = VmState.TERMINATED; } else if( s.equals("suspended") ) { state = VmState.SUSPENDED; } else if( s.equalsIgnoreCase("paused") ) { state = VmState.PAUSED; } else if( s.equalsIgnoreCase("stopped") || s.equalsIgnoreCase("shutoff")) { state = VmState.STOPPED; } else if( s.equalsIgnoreCase("stopping") ) { state = VmState.STOPPING; } else if( s.equalsIgnoreCase("pausing") ) { state = VmState.PAUSING; } else if( s.equalsIgnoreCase("suspending") ) { state = VmState.SUSPENDING; } else if( s.equals("error") ) { return null; } else if( s.equals("reboot") || s.equals("hard_reboot") ) { state = VmState.REBOOTING; } else { logger.warn("toVirtualMachine(): Unknown server state: " + s); state = VmState.PENDING; } } return new ResourceStatus(serverId, state); } private @Nullable VirtualMachine toVirtualMachine(@Nullable JSONObject server, @Nonnull Iterable<IpAddress> ipv4, @Nonnull Iterable<IpAddress> ipv6, @Nonnull Iterable<VLAN> networks) throws JSONException, InternalException, CloudException { if( server == null ) { return null; } VirtualMachine vm = new VirtualMachine(); String description = null; vm.setCurrentState(VmState.RUNNING); vm.setArchitecture(Architecture.I64); vm.setClonable(false); vm.setCreationTimestamp(-1L); vm.setImagable(false); vm.setLastBootTimestamp(-1L); vm.setLastPauseTimestamp(-1L); vm.setPausable(false); vm.setPersistent(true); vm.setPlatform(Platform.UNKNOWN); vm.setRebootable(true); vm.setProviderOwnerId(getTenantId()); if (getProvider().getCloudProvider().equals(OpenStackProvider.RACKSPACE)) { vm.setPersistent(false); } if( server.has("id") ) { vm.setProviderVirtualMachineId(server.getString("id")); } if( server.has("name") ) { vm.setName(server.getString("name")); } if( server.has("description") && !server.isNull("description") ) { description = server.getString("description"); } if( server.has("kernel_id") ) { vm.setProviderKernelImageId(server.getString("kernel_id")); } if( server.has("ramdisk_id") ) { vm.setProviderRamdiskImageId(server.getString("ramdisk_id")); } JSONObject md = (server.has("metadata") && !server.isNull("metadata")) ? server.getJSONObject("metadata") : null; HashMap<String,String> map = new HashMap<String,String>(); boolean imaging = false; if( md != null ) { if( md.has("org.dasein.description") && vm.getDescription() == null ) { description = md.getString("org.dasein.description"); } else if( md.has("Server Label") ) { description = md.getString("Server Label"); } if( md.has("org.dasein.platform") ) { try { vm.setPlatform(Platform.valueOf(md.getString("org.dasein.platform"))); } catch( Throwable ignore ) { // ignore } } String[] keys = JSONObject.getNames(md); if( keys != null ) { for( String key : keys ) { String value = md.getString(key); if( value != null ) { map.put(key, value); } } } } if( server.has("OS-EXT-STS:task_state") && !server.isNull("OS-EXT-STS:task_state") ) { String t = server.getString("OS-EXT-STS:task_state"); map.put("OS-EXT-STS:task_state", t); imaging = t.equalsIgnoreCase("image_snapshot"); } if( description == null ) { if( vm.getName() == null ) { vm.setName(vm.getProviderVirtualMachineId()); } vm.setDescription(vm.getName()); } else { vm.setDescription(description); } if( server.has("hostId") ) { map.put("host", server.getString("hostId")); } vm.setTags(map); if( server.has("image") ) { JSONObject img = server.getJSONObject("image"); if( img.has("id") ) { vm.setProviderMachineImageId(img.getString("id")); } } if( server.has("flavor") ) { JSONObject f = server.getJSONObject("flavor"); if( f.has("id") ) { vm.setProductId(f.getString("id")); } } else if( server.has("flavorId") ) { vm.setProductId(server.getString("flavorId")); } if( server.has("adminPass") ) { vm.setRootPassword(server.getString("adminPass")); } if( server.has("key_name") ) { vm.setProviderShellKeyIds(server.getString("key_name")); } if( server.has("status") ) { String s = server.getString("status").toLowerCase(); if( s.equals("active") ) { vm.setCurrentState(VmState.RUNNING); } else if( s.startsWith("build") ) { vm.setCurrentState(VmState.PENDING); } else if( s.equals("deleted") ) { vm.setCurrentState(VmState.TERMINATED); } else if( s.equals("suspended") ) { vm.setCurrentState(VmState.SUSPENDED); } else if( s.equalsIgnoreCase("paused") ) { vm.setCurrentState(VmState.PAUSED); } else if( s.equalsIgnoreCase("stopped") || s.equalsIgnoreCase("shutoff")) { vm.setCurrentState(VmState.STOPPED); } else if( s.equalsIgnoreCase("stopping") ) { vm.setCurrentState(VmState.STOPPING); } else if( s.equalsIgnoreCase("pausing") ) { vm.setCurrentState(VmState.PAUSING); } else if( s.equalsIgnoreCase("suspending") ) { vm.setCurrentState(VmState.SUSPENDING); } else if( s.equals("error") ) { return null; } else if( s.equals("reboot") || s.equals("hard_reboot") ) { vm.setCurrentState(VmState.REBOOTING); } else { logger.warn("toVirtualMachine(): Unknown server state: " + s); vm.setCurrentState(VmState.PENDING); } } if( vm.getCurrentState().equals(VmState.RUNNING) && imaging ) { vm.setCurrentState(VmState.PENDING); } if( server.has("created") ) { vm.setCreationTimestamp(((NovaOpenStack)getProvider()).parseTimestamp(server.getString("created"))); } if( server.has("addresses") ) { JSONObject addrs = server.getJSONObject("addresses"); String[] names = JSONObject.getNames(addrs); if( names != null && names.length > 0 ) { ArrayList<RawAddress> pub = new ArrayList<RawAddress>(); ArrayList<RawAddress> priv = new ArrayList<RawAddress>(); for( String name : names ) { JSONArray arr = addrs.getJSONArray(name); String subnet = null; for( int i=0; i<arr.length(); i++ ) { RawAddress addr = null; if( ((NovaOpenStack)getProvider()).getMinorVersion() == 0 && ((NovaOpenStack)getProvider()).getMajorVersion() == 1 ) { addr = new RawAddress(arr.getString(i).trim(), IPVersion.IPV4); } else { JSONObject a = arr.getJSONObject(i); if( a.has("version") && a.getInt("version") == 4 && a.has("addr") ) { subnet = a.getString("addr"); addr = new RawAddress(a.getString("addr"), IPVersion.IPV4); } else if( a.has("version") && a.getInt("version") == 6 && a.has("addr") ) { subnet = a.getString("addr"); addr = new RawAddress(a.getString("addr"), IPVersion.IPV6); } } if( addr != null ) { if( addr.isPublicIpAddress() ) { pub.add(addr); } else { priv.add(addr); } } } if( vm.getProviderVlanId() == null && !name.equals("public") && !name.equals("private") && !name.equals("nova_fixed") ) { for( VLAN network : networks ) { if( network.getName().equals(name) ) { vm.setProviderVlanId(network.getProviderVlanId()); //get subnet NetworkServices services = getProvider().getNetworkServices(); VLANSupport support = services.getVlanSupport(); Iterable<Subnet> subnets = support.listSubnets(network.getProviderVlanId()); for (Subnet sub : subnets) { SubnetUtils utils = new SubnetUtils(sub.getCidr()); if (utils.getInfo().isInRange(subnet)) { vm.setProviderSubnetId(sub.getProviderSubnetId()); break; } } break; } } } } vm.setPublicAddresses(pub.toArray(new RawAddress[pub.size()])); vm.setPrivateAddresses(priv.toArray(new RawAddress[priv.size()])); } RawAddress[] raw = vm.getPublicAddresses(); if( raw != null ) { for( RawAddress addr : vm.getPublicAddresses() ) { if( addr.getVersion().equals(IPVersion.IPV4) ) { for( IpAddress a : ipv4 ) { if( a.getRawAddress().getIpAddress().equals(addr.getIpAddress()) ) { vm.setProviderAssignedIpAddressId(a.getProviderIpAddressId()); break; } } } else if( addr.getVersion().equals(IPVersion.IPV6) ) { for( IpAddress a : ipv6 ) { if( a.getRawAddress().getIpAddress().equals(addr.getIpAddress()) ) { vm.setProviderAssignedIpAddressId(a.getProviderIpAddressId()); break; } } } } } if( vm.getProviderAssignedIpAddressId() == null ) { for( IpAddress addr : ipv4 ) { String serverId = addr.getServerId(); if( serverId != null && serverId.equals(vm.getProviderVirtualMachineId()) ) { vm.setProviderAssignedIpAddressId(addr.getProviderIpAddressId()); break; } } if( vm.getProviderAssignedIpAddressId() == null ) { for( IpAddress addr : ipv6 ) { String serverId = addr.getServerId(); if( serverId != null && addr.getServerId().equals(vm.getProviderVirtualMachineId()) ) { vm.setProviderAssignedIpAddressId(addr.getProviderIpAddressId()); break; } } } } vm.setProviderRegionId(getContext().getRegionId()); vm.setProviderDataCenterId(vm.getProviderRegionId() + "-a"); vm.setTerminationTimestamp(-1L); if( vm.getProviderVirtualMachineId() == null ) { return null; } if( vm.getProviderAssignedIpAddressId() == null ) { for( IpAddress addr : ipv6 ) { if( addr.getServerId().equals(vm.getProviderVirtualMachineId()) ) { vm.setProviderAssignedIpAddressId(addr.getProviderIpAddressId()); break; } } } } vm.setProviderRegionId(getContext().getRegionId()); vm.setProviderDataCenterId(vm.getProviderRegionId() + "-a"); vm.setTerminationTimestamp(-1L); if( vm.getProviderVirtualMachineId() == null ) { return null; } if( vm.getName() == null ) { vm.setName(vm.getProviderVirtualMachineId()); } if( vm.getDescription() == null ) { vm.setDescription(vm.getName()); } vm.setImagable(vm.getCurrentState().equals(VmState.RUNNING)); vm.setRebootable(vm.getCurrentState().equals(VmState.RUNNING)); if( vm.getPlatform().equals(Platform.UNKNOWN) ) { Platform p = Platform.guess(vm.getName() + " " + vm.getDescription()); if( p.equals(Platform.UNKNOWN) ) { MachineImage img = getProvider().getComputeServices().getImageSupport().getImage(vm.getProviderMachineImageId()); if( img != null ) { p = img.getPlatform(); } } vm.setPlatform(p); } if (getProvider().getProviderName().equalsIgnoreCase("RACKSPACE")){ //Rackspace does not support the concept for firewalls in servers vm.setProviderFirewallIds(null); } else{ Iterable<String> fwIds = listFirewalls(vm.getProviderVirtualMachineId(), server); int count = 0; //noinspection UnusedDeclaration for( String id : fwIds ) { count++; } String[] ids = new String[count]; int i = 0; for( String id : fwIds ) { ids[i++] = id; } vm.setProviderFirewallIds(ids); } return vm; } }
src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaServer.java
/** * Copyright (C) 2009-2013 Dell, Inc. * See annotations for authorship information * * ==================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ package org.dasein.cloud.openstack.nova.os.compute; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.codec.binary.Base64; import org.apache.commons.net.util.SubnetUtils; import org.apache.http.HttpStatus; import org.apache.log4j.Logger; import org.dasein.cloud.CloudErrorType; import org.dasein.cloud.CloudException; import org.dasein.cloud.InternalException; import org.dasein.cloud.OperationNotSupportedException; import org.dasein.cloud.ResourceStatus; import org.dasein.cloud.compute.AbstractVMSupport; import org.dasein.cloud.compute.Architecture; import org.dasein.cloud.compute.MachineImage; import org.dasein.cloud.compute.Platform; import org.dasein.cloud.compute.VMLaunchOptions; import org.dasein.cloud.compute.VirtualMachine; import org.dasein.cloud.compute.VirtualMachineCapabilities; import org.dasein.cloud.compute.VirtualMachineProduct; import org.dasein.cloud.compute.VmState; import org.dasein.cloud.network.Firewall; import org.dasein.cloud.network.FirewallSupport; import org.dasein.cloud.network.IPVersion; import org.dasein.cloud.network.IpAddress; import org.dasein.cloud.network.IpAddressSupport; import org.dasein.cloud.network.NetworkServices; import org.dasein.cloud.network.RawAddress; import org.dasein.cloud.network.VLAN; import org.dasein.cloud.network.VLANSupport; import org.dasein.cloud.network.Subnet; import org.dasein.cloud.openstack.nova.os.NovaException; import org.dasein.cloud.openstack.nova.os.NovaMethod; import org.dasein.cloud.openstack.nova.os.NovaOpenStack; import org.dasein.cloud.openstack.nova.os.OpenStackProvider; import org.dasein.cloud.openstack.nova.os.network.NovaNetworkServices; import org.dasein.cloud.openstack.nova.os.network.Quantum; import org.dasein.cloud.util.APITrace; import org.dasein.cloud.util.Cache; import org.dasein.cloud.util.CacheLevel; import org.dasein.util.CalendarWrapper; import org.dasein.util.uom.storage.Gigabyte; import org.dasein.util.uom.storage.Megabyte; import org.dasein.util.uom.storage.Storage; import org.dasein.util.uom.time.Day; import org.dasein.util.uom.time.TimePeriod; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * Implements services supporting interaction with cloud virtual machines. * @author George Reese ([email protected]) * @version 2012.09 addressed issue with alternate security group lookup in some OpenStack environments (issue #1) * @version 2013.02 implemented setting kernel/ramdisk image IDs (see issue #40 in dasein-cloud-core) * @version 2013.02 updated with support for Dasein Cloud 2013.02 model * @version 2013.02 added support for fetching shell keys (issue #4) * @since unknown */ public class NovaServer extends AbstractVMSupport<NovaOpenStack> { static private final Logger logger = NovaOpenStack.getLogger(NovaServer.class, "std"); static public final String SERVICE = "compute"; NovaServer(NovaOpenStack provider) { super(provider); } private @Nonnull String getTenantId() throws CloudException, InternalException { return ((NovaOpenStack)getProvider()).getAuthenticationContext().getTenantId(); } private transient volatile NovaServerCapabilities capabilities; @Nonnull @Override public VirtualMachineCapabilities getCapabilities() throws InternalException, CloudException { if( capabilities == null ) { capabilities = new NovaServerCapabilities(getProvider()); } return capabilities; } @Override public @Nonnull String getConsoleOutput(@Nonnull String vmId) throws CloudException, InternalException { APITrace.begin(getProvider(), "VM.getConsoleOutput"); try { VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } HashMap<String,Object> json = new HashMap<String,Object>(); json.put("os-getConsoleOutput", new HashMap<String,Object>()); NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); String console = method.postServersForString("/servers", vmId, new JSONObject(json), true); return (console == null ? "" : console); } finally { APITrace.end(); } } @Override public @Nullable VirtualMachineProduct getProduct(@Nonnull String productId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.getProduct"); try { for( VirtualMachineProduct product : listProducts(Architecture.I64) ) { if( product.getProviderProductId().equals(productId) ) { return product; } } return null; } finally { APITrace.end(); } } @Override public @Nullable VirtualMachine getVirtualMachine(@Nonnull String vmId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.getVirtualMachine"); try { NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); JSONObject ob = method.getServers("/servers", vmId, true); if( ob == null ) { return null; } Iterable<IpAddress> ipv4, ipv6; Iterable<VLAN> networks; NetworkServices services = getProvider().getNetworkServices(); if( services != null ) { IpAddressSupport support = services.getIpAddressSupport(); if( support != null ) { ipv4 = support.listIpPool(IPVersion.IPV4, false); ipv6 = support.listIpPool(IPVersion.IPV6, false); } else { ipv4 = ipv6 = Collections.emptyList(); } VLANSupport vs = services.getVlanSupport(); if( vs != null ) { networks = vs.listVlans(); } else { networks = Collections.emptyList(); } } else { ipv4 = ipv6 = Collections.emptyList(); networks = Collections.emptyList(); } try { if( ob.has("server") ) { JSONObject server = ob.getJSONObject("server"); VirtualMachine vm = toVirtualMachine(server, ipv4, ipv6, networks); if( vm != null ) { return vm; } } } catch( JSONException e ) { logger.error("getVirtualMachine(): Unable to identify expected values in JSON: " + e.getMessage()); throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for servers"); } return null; } finally { APITrace.end(); } } @Override public boolean isSubscribed() throws CloudException, InternalException { APITrace.begin(getProvider(), "VM.isSubscribed"); try { return (getProvider().testContext() != null); } finally { APITrace.end(); } } @Override public @Nonnull VirtualMachine launch(@Nonnull VMLaunchOptions options) throws CloudException, InternalException { APITrace.begin(getProvider(), "VM.launch"); try { MachineImage targetImage = getProvider().getComputeServices().getImageSupport().getImage(options.getMachineImageId()); if( targetImage == null ) { throw new CloudException("No such machine image: " + options.getMachineImageId()); } HashMap<String,Object> wrapper = new HashMap<String,Object>(); HashMap<String,Object> json = new HashMap<String,Object>(); NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); json.put("name", options.getHostName()); if( options.getUserData() != null ) { try { json.put("user_data", Base64.encodeBase64String(options.getUserData().getBytes("utf-8"))); } catch( UnsupportedEncodingException e ) { throw new InternalException(e); } } if( ((NovaOpenStack)getProvider()).getMinorVersion() == 0 && ((NovaOpenStack)getProvider()).getMajorVersion() == 1 ) { json.put("imageId", String.valueOf(options.getMachineImageId())); json.put("flavorId", options.getStandardProductId()); } else { if( getProvider().getProviderName().equals("HP") ) { json.put("imageRef", options.getMachineImageId()); } else { json.put("imageRef", ((NovaOpenStack)getProvider()).getComputeServices().getImageSupport().getImageRef(options.getMachineImageId())); } json.put("flavorRef", getFlavorRef(options.getStandardProductId())); } if( options.getVlanId() != null && ((NovaOpenStack)getProvider()).isRackspace() ) { ArrayList<Map<String,Object>> vlans = new ArrayList<Map<String, Object>>(); HashMap<String,Object> vlan = new HashMap<String, Object>(); vlan.put("uuid", options.getVlanId()); vlans.add(vlan); json.put("networks", vlans); } else { if( options.getVlanId() != null && !((NovaOpenStack)getProvider()).isRackspace() ) { NovaNetworkServices services = ((NovaOpenStack)getProvider()).getNetworkServices(); if( services != null ) { Quantum support = services.getVlanSupport(); if( support != null ) { ArrayList<Map<String,Object>> vlans = new ArrayList<Map<String, Object>>(); HashMap<String,Object> vlan = new HashMap<String, Object>(); try { vlan.put("port", support.createPort(options.getVlanId(), options.getHostName())); vlans.add(vlan); json.put("networks", vlans); } catch (CloudException e) { if (e.getHttpCode() != 403) { throw new CloudException(e.getMessage()); } logger.warn("Unable to create port - trying to launch into general network"); Subnet subnet = support.getSubnet(options.getVlanId()); vlan.put("uuid", subnet.getProviderVlanId()); vlans.add(vlan); json.put("networks", vlans); } } } } } if( options.getBootstrapKey() != null ) { json.put("key_name", options.getBootstrapKey()); } if( options.getFirewallIds().length > 0 ) { ArrayList<HashMap<String,Object>> firewalls = new ArrayList<HashMap<String,Object>>(); for( String id : options.getFirewallIds() ) { NetworkServices services = getProvider().getNetworkServices(); Firewall firewall = null; if( services != null ) { FirewallSupport support = services.getFirewallSupport(); if( support != null ) { firewall = support.getFirewall(id); } } if( firewall != null ) { HashMap<String,Object> fw = new HashMap<String, Object>(); fw.put("name", firewall.getName()); firewalls.add(fw); } } json.put("security_groups", firewalls); } if( !targetImage.getPlatform().equals(Platform.UNKNOWN) ) { options.withMetaData("org.dasein.platform", targetImage.getPlatform().name()); } options.withMetaData("org.dasein.description", options.getDescription()); json.put("metadata", options.getMetaData()); wrapper.put("server", json); JSONObject result = method.postServers("/servers", null, new JSONObject(wrapper), true); if( result.has("server") ) { try { Collection<IpAddress> ips = Collections.emptyList(); Collection<VLAN> nets = Collections.emptyList(); JSONObject server = result.getJSONObject("server"); VirtualMachine vm = toVirtualMachine(server, ips, ips, nets); if( vm != null ) { return vm; } } catch( JSONException e ) { logger.error("launch(): Unable to understand launch response: " + e.getMessage()); if( logger.isTraceEnabled() ) { e.printStackTrace(); } throw new CloudException(e); } } logger.error("launch(): No server was created by the launch attempt, and no error was returned"); throw new CloudException("No virtual machine was launched"); } finally { APITrace.end(); } } private @Nonnull Iterable<String> listFirewalls(@Nonnull String vmId, @Nonnull JSONObject server) throws InternalException, CloudException { try { if( server.has("security_groups") ) { NetworkServices services = getProvider().getNetworkServices(); Collection<Firewall> firewalls = null; if( services != null ) { FirewallSupport support = services.getFirewallSupport(); if( support != null ) { firewalls = support.list(); } } if( firewalls == null ) { firewalls = Collections.emptyList(); } JSONArray groups = server.getJSONArray("security_groups"); ArrayList<String> results = new ArrayList<String>(); for( int i=0; i<groups.length(); i++ ) { JSONObject group = groups.getJSONObject(i); String id = group.has("id") ? group.getString("id") : null; String name = group.has("name") ? group.getString("name") : null; if( id != null || name != null ) { for( Firewall fw : firewalls ) { if( id != null ) { if( id.equals(fw.getProviderFirewallId()) ) { results.add(id); } } else if( name.equals(fw.getName()) ) { results.add(fw.getProviderFirewallId()); } } } } return results; } else { ArrayList<String> results = new ArrayList<String>(); NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); JSONObject ob = method.getServers("/os-security-groups/servers", vmId + "/os-security-groups", true); if( ob != null ) { if( ob.has("security_groups") ) { JSONArray groups = ob.getJSONArray("security_groups"); for( int i=0; i<groups.length(); i++ ) { JSONObject group = groups.getJSONObject(i); if( group.has("id") ) { results.add(group.getString("id")); } } } } return results; } } catch( JSONException e ) { throw new CloudException(e); } } @Override public @Nonnull Iterable<String> listFirewalls(@Nonnull String vmId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.listFirewalls"); try { NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); JSONObject ob = method.getServers("/servers", vmId, true); if( ob == null ) { return Collections.emptyList(); } try { if( ob.has("server") ) { JSONObject server = ob.getJSONObject("server"); return listFirewalls(vmId, server); } throw new CloudException("No such server: " + vmId); } catch( JSONException e ) { logger.error("listFirewalls(): Unable to identify expected values in JSON: " + e.getMessage()); throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for servers"); } } finally { APITrace.end(); } } static public class FlavorRef { public String id; public String[][] links; VirtualMachineProduct product; public String toString() { return (id + " -> " + product); } } private @Nonnull Iterable<FlavorRef> listFlavors() throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.listFlavors"); try { Cache<FlavorRef> cache = Cache.getInstance(getProvider(), "flavorRefs", FlavorRef.class, CacheLevel.REGION_ACCOUNT, new TimePeriod<Day>(1, TimePeriod.DAY)); Iterable<FlavorRef> refs = cache.get(getContext()); if( refs != null ) { return refs; } NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); JSONObject ob = method.getServers("/flavors", null, true); ArrayList<FlavorRef> flavors = new ArrayList<FlavorRef>(); try { if( ob != null && ob.has("flavors") ) { JSONArray list = ob.getJSONArray("flavors"); for( int i=0; i<list.length(); i++ ) { JSONObject p = list.getJSONObject(i); FlavorRef ref = new FlavorRef(); if( p.has("id") ) { ref.id = p.getString("id"); } else { continue; } if( p.has("links") ) { JSONArray links = p.getJSONArray("links"); ref.links = new String[links.length()][]; for( int j=0; j<links.length(); j++ ) { JSONObject link = links.getJSONObject(j); ref.links[j] = new String[2]; if( link.has("rel") ) { ref.links[j][0] = link.getString("rel"); } if( link.has("href") ) { ref.links[j][1] = link.getString("href"); } } } else { ref.links = new String[0][]; } ref.product = toProduct(p); if( ref.product != null ) { flavors.add(ref); } } } } catch( JSONException e ) { logger.error("listProducts(): Unable to identify expected values in JSON: " + e.getMessage()); throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for flavors: " + e.getMessage()); } cache.put(getContext(), flavors); return flavors; } finally { APITrace.end(); } } public @Nullable String getFlavorRef(@Nonnull String flavorId) throws InternalException, CloudException { for( FlavorRef ref : listFlavors() ) { if( ref.id.equals(flavorId) ) { String def = null; for( String[] link : ref.links ) { if( link[0] != null && link[0].equals("self") && link[1] != null ) { return link[1]; } else if( def == null && link[1] != null ) { def = link[1]; } } return def; } } return null; } @Override public @Nonnull Iterable<VirtualMachineProduct> listProducts(@Nonnull Architecture architecture) throws InternalException, CloudException { if( !architecture.equals(Architecture.I32) && !architecture.equals(Architecture.I64) ) { return Collections.emptyList(); } APITrace.begin(getProvider(), "VM.listProducts"); try { ArrayList<VirtualMachineProduct> products = new ArrayList<VirtualMachineProduct>(); for( FlavorRef flavor : listFlavors() ) { products.add(flavor.product); } return products; } finally { APITrace.end(); } } @Override public @Nonnull Iterable<ResourceStatus> listVirtualMachineStatus() throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.listVirtualMachineStatus"); try { NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); JSONObject ob = method.getServers("/servers", null, true); ArrayList<ResourceStatus> servers = new ArrayList<ResourceStatus>(); try { if( ob != null && ob.has("servers") ) { JSONArray list = ob.getJSONArray("servers"); for( int i=0; i<list.length(); i++ ) { JSONObject server = list.getJSONObject(i); ResourceStatus vm = toStatus(server); if( vm != null ) { servers.add(vm); } } } } catch( JSONException e ) { logger.error("listVirtualMachines(): Unable to identify expected values in JSON: " + e.getMessage()); e.printStackTrace(); throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for servers in " + ob.toString()); } return servers; } finally { APITrace.end(); } } @Override public @Nonnull Iterable<VirtualMachine> listVirtualMachines() throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.listVirtualMachines"); try { NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); JSONObject ob = method.getServers("/servers", null, true); ArrayList<VirtualMachine> servers = new ArrayList<VirtualMachine>(); Iterable<IpAddress> ipv4 = Collections.emptyList(), ipv6 = Collections.emptyList(); Iterable<VLAN> nets = Collections.emptyList(); NetworkServices services = getProvider().getNetworkServices(); if( services != null ) { IpAddressSupport support = services.getIpAddressSupport(); if( support != null ) { ipv4 = support.listIpPool(IPVersion.IPV4, false); ipv6 = support.listIpPool(IPVersion.IPV6, false); } VLANSupport vs = services.getVlanSupport(); if( vs != null ) { nets = vs.listVlans(); } } try { if( ob != null && ob.has("servers") ) { JSONArray list = ob.getJSONArray("servers"); for( int i=0; i<list.length(); i++ ) { JSONObject server = list.getJSONObject(i); VirtualMachine vm = toVirtualMachine(server, ipv4, ipv6, nets); if( vm != null ) { servers.add(vm); } } } } catch( JSONException e ) { logger.error("listVirtualMachines(): Unable to identify expected values in JSON: " + e.getMessage()); e.printStackTrace(); throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for servers in " + ob.toString()); } return servers; } finally { APITrace.end(); } } @Override public void pause(@Nonnull String vmId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.pause"); try { VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } if( !supportsPauseUnpause(vm) ) { throw new OperationNotSupportedException("Pause/unpause is not supported in " + getProvider().getCloudName()); } HashMap<String,Object> json = new HashMap<String,Object>(); json.put("pause", null); NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); method.postServers("/servers", vmId, new JSONObject(json), true); } finally { APITrace.end(); } } @Override public void resume(@Nonnull String vmId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.resume"); try { VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } if( !supportsSuspendResume(vm) ) { throw new OperationNotSupportedException("Suspend/resume is not supported in " + getProvider().getCloudName()); } HashMap<String,Object> json = new HashMap<String,Object>(); json.put("resume", null); NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); method.postServers("/servers", vmId, new JSONObject(json), true); } finally { APITrace.end(); } } @Override public void start(@Nonnull String vmId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.start"); try { VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } if( !supportsStartStop(vm) ) { throw new OperationNotSupportedException("Start/stop is not supported in " + getProvider().getCloudName()); } HashMap<String,Object> json = new HashMap<String,Object>(); json.put("os-start", null); NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); method.postServers("/servers", vmId, new JSONObject(json), true); } finally { APITrace.end(); } } @Override public void stop(@Nonnull String vmId, boolean force) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.stop"); try { VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } if( !supportsStartStop(vm) ) { throw new OperationNotSupportedException("Start/stop is not supported in " + getProvider().getCloudName()); } HashMap<String,Object> json = new HashMap<String,Object>(); json.put("os-stop", null); NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); method.postServers("/servers", vmId, new JSONObject(json), true); } finally { APITrace.end(); } } @Override public void suspend(@Nonnull String vmId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.suspend"); try { VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } if( !supportsSuspendResume(vm) ) { throw new OperationNotSupportedException("Suspend/resume is not supported in " + getProvider().getCloudName()); } HashMap<String,Object> json = new HashMap<String,Object>(); json.put("suspend", null); NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); method.postServers("/servers", vmId, new JSONObject(json), true); } finally { APITrace.end(); } } @Override public void unpause(@Nonnull String vmId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.unpause"); try { VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } if( !supportsPauseUnpause(vm) ) { throw new OperationNotSupportedException("Pause/unpause is not supported in " + getProvider().getCloudName()); } HashMap<String,Object> json = new HashMap<String,Object>(); json.put("unpause", null); NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); method.postServers("/servers", vmId, new JSONObject(json), true); } finally { APITrace.end(); } } @Override public void reboot(@Nonnull String vmId) throws CloudException, InternalException { APITrace.begin(getProvider(), "VM.reboot"); try { HashMap<String,Object> json = new HashMap<String,Object>(); HashMap<String,Object> action = new HashMap<String,Object>(); action.put("type", "HARD"); json.put("reboot", action); NovaMethod method = new NovaMethod(((NovaOpenStack)getProvider())); method.postServers("/servers", vmId, new JSONObject(json), true); } finally { APITrace.end(); } } @Override public void terminate(@Nonnull String vmId, @Nullable String explanation) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.terminate"); try { NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); long timeout = System.currentTimeMillis() + CalendarWrapper.HOUR; do { try { method.deleteServers("/servers", vmId); return; } catch( NovaException e ) { if( e.getHttpCode() != HttpStatus.SC_CONFLICT ) { throw e; } } try { Thread.sleep(CalendarWrapper.MINUTE); } catch( InterruptedException e ) { /* ignore */ } } while( System.currentTimeMillis() < timeout ); } finally { APITrace.end(); } } private @Nullable VirtualMachineProduct toProduct(@Nullable JSONObject json) throws JSONException, InternalException, CloudException { if( json == null ) { return null; } VirtualMachineProduct product = new VirtualMachineProduct(); if( json.has("id") ) { product.setProviderProductId(json.getString("id")); } if( json.has("name") ) { product.setName(json.getString("name")); } if( json.has("description") ) { product.setDescription(json.getString("description")); } if( json.has("ram") ) { product.setRamSize(new Storage<Megabyte>(json.getInt("ram"), Storage.MEGABYTE)); } if( json.has("disk") ) { product.setRootVolumeSize(new Storage<Gigabyte>(json.getInt("disk"), Storage.GIGABYTE)); } product.setCpuCount(1); if( product.getProviderProductId() == null ) { return null; } if( product.getName() == null ) { product.setName(product.getProviderProductId()); } if( product.getDescription() == null ) { product.setDescription(product.getName()); } return product; } private @Nullable ResourceStatus toStatus(@Nullable JSONObject server) throws JSONException, InternalException, CloudException { if( server == null ) { return null; } String serverId = null; if( server.has("id") ) { serverId = server.getString("id"); } if( serverId == null ) { return null; } VmState state = VmState.PENDING; if( server.has("status") ) { String s = server.getString("status").toLowerCase(); if( s.equals("active") ) { state = VmState.RUNNING; } else if( s.equals("build") ) { state = VmState.PENDING; } else if( s.equals("deleted") ) { state = VmState.TERMINATED; } else if( s.equals("suspended") ) { state = VmState.SUSPENDED; } else if( s.equalsIgnoreCase("paused") ) { state = VmState.PAUSED; } else if( s.equalsIgnoreCase("stopped") || s.equalsIgnoreCase("shutoff")) { state = VmState.STOPPED; } else if( s.equalsIgnoreCase("stopping") ) { state = VmState.STOPPING; } else if( s.equalsIgnoreCase("pausing") ) { state = VmState.PAUSING; } else if( s.equalsIgnoreCase("suspending") ) { state = VmState.SUSPENDING; } else if( s.equals("error") ) { return null; } else if( s.equals("reboot") || s.equals("hard_reboot") ) { state = VmState.REBOOTING; } else { logger.warn("toVirtualMachine(): Unknown server state: " + s); state = VmState.PENDING; } } return new ResourceStatus(serverId, state); } private @Nullable VirtualMachine toVirtualMachine(@Nullable JSONObject server, @Nonnull Iterable<IpAddress> ipv4, @Nonnull Iterable<IpAddress> ipv6, @Nonnull Iterable<VLAN> networks) throws JSONException, InternalException, CloudException { if( server == null ) { return null; } VirtualMachine vm = new VirtualMachine(); String description = null; vm.setCurrentState(VmState.RUNNING); vm.setArchitecture(Architecture.I64); vm.setClonable(false); vm.setCreationTimestamp(-1L); vm.setImagable(false); vm.setLastBootTimestamp(-1L); vm.setLastPauseTimestamp(-1L); vm.setPausable(false); vm.setPersistent(true); vm.setPlatform(Platform.UNKNOWN); vm.setRebootable(true); vm.setProviderOwnerId(getTenantId()); if (getProvider().getCloudProvider().equals(OpenStackProvider.RACKSPACE)) { vm.setPersistent(false); } if( server.has("id") ) { vm.setProviderVirtualMachineId(server.getString("id")); } if( server.has("name") ) { vm.setName(server.getString("name")); } if( server.has("description") && !server.isNull("description") ) { description = server.getString("description"); } if( server.has("kernel_id") ) { vm.setProviderKernelImageId(server.getString("kernel_id")); } if( server.has("ramdisk_id") ) { vm.setProviderRamdiskImageId(server.getString("ramdisk_id")); } JSONObject md = (server.has("metadata") && !server.isNull("metadata")) ? server.getJSONObject("metadata") : null; HashMap<String,String> map = new HashMap<String,String>(); boolean imaging = false; if( md != null ) { if( md.has("org.dasein.description") && vm.getDescription() == null ) { description = md.getString("org.dasein.description"); } else if( md.has("Server Label") ) { description = md.getString("Server Label"); } if( md.has("org.dasein.platform") ) { try { vm.setPlatform(Platform.valueOf(md.getString("org.dasein.platform"))); } catch( Throwable ignore ) { // ignore } } String[] keys = JSONObject.getNames(md); if( keys != null ) { for( String key : keys ) { String value = md.getString(key); if( value != null ) { map.put(key, value); } } } } if( server.has("OS-EXT-STS:task_state") && !server.isNull("OS-EXT-STS:task_state") ) { String t = server.getString("OS-EXT-STS:task_state"); map.put("OS-EXT-STS:task_state", t); imaging = t.equalsIgnoreCase("image_snapshot"); } if( description == null ) { if( vm.getName() == null ) { vm.setName(vm.getProviderVirtualMachineId()); } vm.setDescription(vm.getName()); } else { vm.setDescription(description); } if( server.has("hostId") ) { map.put("host", server.getString("hostId")); } vm.setTags(map); if( server.has("image") ) { JSONObject img = server.getJSONObject("image"); if( img.has("id") ) { vm.setProviderMachineImageId(img.getString("id")); } } if( server.has("flavor") ) { JSONObject f = server.getJSONObject("flavor"); if( f.has("id") ) { vm.setProductId(f.getString("id")); } } else if( server.has("flavorId") ) { vm.setProductId(server.getString("flavorId")); } if( server.has("adminPass") ) { vm.setRootPassword(server.getString("adminPass")); } if( server.has("key_name") ) { vm.setProviderShellKeyIds(server.getString("key_name")); } if( server.has("status") ) { String s = server.getString("status").toLowerCase(); if( s.equals("active") ) { vm.setCurrentState(VmState.RUNNING); } else if( s.startsWith("build") ) { vm.setCurrentState(VmState.PENDING); } else if( s.equals("deleted") ) { vm.setCurrentState(VmState.TERMINATED); } else if( s.equals("suspended") ) { vm.setCurrentState(VmState.SUSPENDED); } else if( s.equalsIgnoreCase("paused") ) { vm.setCurrentState(VmState.PAUSED); } else if( s.equalsIgnoreCase("stopped") || s.equalsIgnoreCase("shutoff")) { vm.setCurrentState(VmState.STOPPED); } else if( s.equalsIgnoreCase("stopping") ) { vm.setCurrentState(VmState.STOPPING); } else if( s.equalsIgnoreCase("pausing") ) { vm.setCurrentState(VmState.PAUSING); } else if( s.equalsIgnoreCase("suspending") ) { vm.setCurrentState(VmState.SUSPENDING); } else if( s.equals("error") ) { return null; } else if( s.equals("reboot") || s.equals("hard_reboot") ) { vm.setCurrentState(VmState.REBOOTING); } else { logger.warn("toVirtualMachine(): Unknown server state: " + s); vm.setCurrentState(VmState.PENDING); } } if( vm.getCurrentState().equals(VmState.RUNNING) && imaging ) { vm.setCurrentState(VmState.PENDING); } if( server.has("created") ) { vm.setCreationTimestamp(((NovaOpenStack)getProvider()).parseTimestamp(server.getString("created"))); } if( server.has("addresses") ) { JSONObject addrs = server.getJSONObject("addresses"); String[] names = JSONObject.getNames(addrs); if( names != null && names.length > 0 ) { ArrayList<RawAddress> pub = new ArrayList<RawAddress>(); ArrayList<RawAddress> priv = new ArrayList<RawAddress>(); for( String name : names ) { JSONArray arr = addrs.getJSONArray(name); String subnet = null; for( int i=0; i<arr.length(); i++ ) { RawAddress addr = null; if( ((NovaOpenStack)getProvider()).getMinorVersion() == 0 && ((NovaOpenStack)getProvider()).getMajorVersion() == 1 ) { addr = new RawAddress(arr.getString(i).trim(), IPVersion.IPV4); } else { JSONObject a = arr.getJSONObject(i); if( a.has("version") && a.getInt("version") == 4 && a.has("addr") ) { subnet = a.getString("addr"); addr = new RawAddress(a.getString("addr"), IPVersion.IPV4); } else if( a.has("version") && a.getInt("version") == 6 && a.has("addr") ) { subnet = a.getString("addr"); addr = new RawAddress(a.getString("addr"), IPVersion.IPV6); } } if( addr != null ) { if( addr.isPublicIpAddress() ) { pub.add(addr); } else { priv.add(addr); } } } if( vm.getProviderVlanId() == null && !name.equals("public") && !name.equals("private") && !name.equals("nova_fixed") ) { for( VLAN network : networks ) { if( network.getName().equals(name) ) { vm.setProviderVlanId(network.getProviderVlanId()); //get subnet NetworkServices services = getProvider().getNetworkServices(); VLANSupport support = services.getVlanSupport(); Iterable<Subnet> subnets = support.listSubnets(network.getProviderVlanId()); for (Subnet sub : subnets) { SubnetUtils utils = new SubnetUtils(sub.getCidr()); if (utils.getInfo().isInRange(subnet)) { vm.setProviderSubnetId(sub.getProviderSubnetId()); break; } } break; } } } } vm.setPublicAddresses(pub.toArray(new RawAddress[pub.size()])); vm.setPrivateAddresses(priv.toArray(new RawAddress[priv.size()])); } RawAddress[] raw = vm.getPublicAddresses(); if( raw != null ) { for( RawAddress addr : vm.getPublicAddresses() ) { if( addr.getVersion().equals(IPVersion.IPV4) ) { for( IpAddress a : ipv4 ) { if( a.getRawAddress().getIpAddress().equals(addr.getIpAddress()) ) { vm.setProviderAssignedIpAddressId(a.getProviderIpAddressId()); break; } } } else if( addr.getVersion().equals(IPVersion.IPV6) ) { for( IpAddress a : ipv6 ) { if( a.getRawAddress().getIpAddress().equals(addr.getIpAddress()) ) { vm.setProviderAssignedIpAddressId(a.getProviderIpAddressId()); break; } } } } } if( vm.getProviderAssignedIpAddressId() == null ) { for( IpAddress addr : ipv4 ) { String serverId = addr.getServerId(); if( serverId != null && serverId.equals(vm.getProviderVirtualMachineId()) ) { vm.setProviderAssignedIpAddressId(addr.getProviderIpAddressId()); break; } } if( vm.getProviderAssignedIpAddressId() == null ) { for( IpAddress addr : ipv6 ) { String serverId = addr.getServerId(); if( serverId != null && addr.getServerId().equals(vm.getProviderVirtualMachineId()) ) { vm.setProviderAssignedIpAddressId(addr.getProviderIpAddressId()); break; } } } } vm.setProviderRegionId(getContext().getRegionId()); vm.setProviderDataCenterId(vm.getProviderRegionId() + "-a"); vm.setTerminationTimestamp(-1L); if( vm.getProviderVirtualMachineId() == null ) { return null; } if( vm.getProviderAssignedIpAddressId() == null ) { for( IpAddress addr : ipv6 ) { if( addr.getServerId().equals(vm.getProviderVirtualMachineId()) ) { vm.setProviderAssignedIpAddressId(addr.getProviderIpAddressId()); break; } } } } vm.setProviderRegionId(getContext().getRegionId()); vm.setProviderDataCenterId(vm.getProviderRegionId() + "-a"); vm.setTerminationTimestamp(-1L); if( vm.getProviderVirtualMachineId() == null ) { return null; } if( vm.getName() == null ) { vm.setName(vm.getProviderVirtualMachineId()); } if( vm.getDescription() == null ) { vm.setDescription(vm.getName()); } vm.setImagable(vm.getCurrentState().equals(VmState.RUNNING)); vm.setRebootable(vm.getCurrentState().equals(VmState.RUNNING)); if( vm.getPlatform().equals(Platform.UNKNOWN) ) { Platform p = Platform.guess(vm.getName() + " " + vm.getDescription()); if( p.equals(Platform.UNKNOWN) ) { MachineImage img = getProvider().getComputeServices().getImageSupport().getImage(vm.getProviderMachineImageId()); if( img != null ) { p = img.getPlatform(); } } vm.setPlatform(p); } if (getProvider().getProviderName().equalsIgnoreCase("RACKSPACE")){ //Rackspace does not support the concept for firewalls in servers vm.setProviderFirewallIds(null); } else{ Iterable<String> fwIds = listFirewalls(vm.getProviderVirtualMachineId(), server); int count = 0; //noinspection UnusedDeclaration for( String id : fwIds ) { count++; } String[] ids = new String[count]; int i = 0; for( String id : fwIds ) { ids[i++] = id; } vm.setProviderFirewallIds(ids); } return vm; } }
updated listProducts implementation and subnet bug fix
src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaServer.java
updated listProducts implementation and subnet bug fix
<ide><path>rc/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaServer.java <ide> import org.dasein.cloud.compute.VirtualMachine; <ide> import org.dasein.cloud.compute.VirtualMachineCapabilities; <ide> import org.dasein.cloud.compute.VirtualMachineProduct; <add>import org.dasein.cloud.compute.VirtualMachineProductFilterOptions; <ide> import org.dasein.cloud.compute.VmState; <ide> import org.dasein.cloud.network.Firewall; <ide> import org.dasein.cloud.network.FirewallSupport; <ide> HashMap<String,Object> vlan = new HashMap<String, Object>(); <ide> <ide> try { <del> vlan.put("port", support.createPort(options.getVlanId(), options.getHostName())); <add> vlan.put("port", support.createPort(options.getSubnetId(), options.getHostName())); <ide> vlans.add(vlan); <ide> json.put("networks", vlans); <ide> } <ide> } <ide> <ide> logger.warn("Unable to create port - trying to launch into general network"); <del> Subnet subnet = support.getSubnet(options.getVlanId()); <add> Subnet subnet = support.getSubnet(options.getSubnetId()); <ide> <ide> vlan.put("uuid", subnet.getProviderVlanId()); <ide> vlans.add(vlan); <ide> } <ide> return null; <ide> } <del> <del> @Override <del> public @Nonnull Iterable<VirtualMachineProduct> listProducts(@Nonnull Architecture architecture) throws InternalException, CloudException { <del> if( !architecture.equals(Architecture.I32) && !architecture.equals(Architecture.I64) ) { <add> <add> @Nonnull <add> @Override <add> public Iterable<VirtualMachineProduct> listProducts(@Nullable VirtualMachineProductFilterOptions options, @Nullable Architecture architecture) throws InternalException, CloudException { <add> if( architecture != null && !architecture.equals(Architecture.I32) && !architecture.equals(Architecture.I64) ) { <ide> return Collections.emptyList(); <ide> } <ide> APITrace.begin(getProvider(), "VM.listProducts"); <ide> ArrayList<VirtualMachineProduct> products = new ArrayList<VirtualMachineProduct>(); <ide> <ide> for( FlavorRef flavor : listFlavors() ) { <del> products.add(flavor.product); <add> if (options != null) { <add> if (options.matches(flavor.product)) { <add> products.add(flavor.product); <add> } <add> } <add> else { <add> products.add(flavor.product); <add> } <ide> } <ide> return products; <ide> }
Java
mit
a526995a9d1fe88de5a8d3b5298037a2d9c12169
0
feamorx86/java-game-server,chongtianfeiyu/java-game-server,cancobanoglu/java-game-server,wuzhenda/java-game-server,xiexingguang/java-game-server,niuqinghua/java-game-server,xiexingguang/java-game-server,chongtianfeiyu/java-game-server,rayue/java-game-server,menacher/java-game-server,menacher/java-game-server,wuzhenda/java-game-server,rayue/java-game-server,menacher/java-game-server,cancobanoglu/java-game-server,niuqinghua/java-game-server,wuzhenda/java-game-server,feamorx86/java-game-server,xiexingguang/java-game-server,rayue/java-game-server,niuqinghua/java-game-server,feamorx86/java-game-server,cancobanoglu/java-game-server
package org.menacheri.server.netty; import org.jboss.netty.bootstrap.Bootstrap; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.group.ChannelGroupFuture; import org.menacheri.handlers.netty.LoginHandler; import org.menacheri.service.IGameAdminService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Required; public abstract class NettyServer implements INettyServerManager { private static final Logger LOG = LoggerFactory.getLogger(NettyServer.class); int portNumber = 18090; Bootstrap serverBootstrap; ChannelPipelineFactory pipelineFactory; IGameAdminService gameAdminService; public NettyServer() { super(); } public NettyServer(int portNumber, ServerBootstrap serverBootstrap, ChannelPipelineFactory pipelineFactory,IGameAdminService gameAdminService) { super(); this.portNumber = portNumber; this.serverBootstrap = serverBootstrap; this.pipelineFactory = pipelineFactory; this.gameAdminService = gameAdminService; } public abstract void startServer(int port); public abstract void startServer(); public boolean stopServer() { LOG.debug("In stopServer method of class: {}", this.getClass().getName()); ChannelGroupFuture future = LoginHandler.ALL_CHANNELS.close(); try { future.await(); } catch (InterruptedException e) { LOG.error("Execption occurred while waiting for channels to close: {}",e); } serverBootstrap.releaseExternalResources(); gameAdminService.shutdown(); return true; } public void configureServerBootStrap(String[] optionsList) { // For clients who do not use spring. if(null == serverBootstrap){ createServerBootstrap(); } serverBootstrap.setPipelineFactory(pipelineFactory); if (null != optionsList && optionsList.length > 0) { for (String option : optionsList) { serverBootstrap.setOption(option, Boolean.valueOf(true)); } } } public int getPortNumber(String[] args) { if (null == args || args.length < 1) { return portNumber; } try { return Integer.parseInt(args[0]); } catch (NumberFormatException e) { LOG.error("Exception occurred while " + "trying to parse the port number: {}", args[0]); LOG.error("NumberFormatException: {}",e); throw e; } } @Override public Bootstrap getServerBootstrap() { return serverBootstrap; } @Override public void setServerBootstrap(Bootstrap serverBootstrap) { this.serverBootstrap = serverBootstrap; } public ChannelPipelineFactory getPipelineFactory() { return pipelineFactory; } @Override @Required public void setPipelineFactory(ChannelPipelineFactory factory) { pipelineFactory = factory; } public int getPortNumber() { return portNumber; } public void setPortNumber(int portNumber) { this.portNumber = portNumber; } public IGameAdminService getGameAdminService() { return gameAdminService; } public void setGameAdminService(IGameAdminService gameAdminService) { this.gameAdminService = gameAdminService; } }
jetserver/src/main/java/org/menacheri/server/netty/NettyServer.java
package org.menacheri.server.netty; import org.jboss.netty.bootstrap.Bootstrap; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.group.ChannelGroupFuture; import org.menacheri.handlers.netty.LoginHandler; import org.menacheri.service.IGameAdminService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Required; public abstract class NettyServer implements INettyServerManager { private static final Logger LOG = LoggerFactory.getLogger(NettyServer.class); int portNumber = 8090; Bootstrap serverBootstrap; ChannelPipelineFactory pipelineFactory; IGameAdminService gameAdminService; public NettyServer() { super(); } public NettyServer(int portNumber, ServerBootstrap serverBootstrap, ChannelPipelineFactory pipelineFactory,IGameAdminService gameAdminService) { super(); this.portNumber = portNumber; this.serverBootstrap = serverBootstrap; this.pipelineFactory = pipelineFactory; this.gameAdminService = gameAdminService; } public abstract void startServer(int port); public boolean stopServer() { LOG.debug("In stopServer method of class: {}", this.getClass().getName()); ChannelGroupFuture future = LoginHandler.ALL_CHANNELS.close(); try { future.await(); } catch (InterruptedException e) { LOG.error("Execption occurred while waiting for channels to close: {}",e); } serverBootstrap.releaseExternalResources(); gameAdminService.shutdown(); return true; } public void configureServerBootStrap(String[] optionsList) { // For clients who do not use spring. if(null == serverBootstrap){ createServerBootstrap(); } serverBootstrap.setPipelineFactory(pipelineFactory); if (null != optionsList && optionsList.length > 0) { for (String option : optionsList) { serverBootstrap.setOption(option, Boolean.valueOf(true)); } } } public int getPortNumber(String[] args) { if (null == args || args.length < 1) { return portNumber; } try { return Integer.parseInt(args[0]); } catch (NumberFormatException e) { LOG.error("Exception occurred while " + "trying to parse the port number: {}", args[0]); LOG.error("NumberFormatException: {}",e); throw e; } } @Override public Bootstrap getServerBootstrap() { return serverBootstrap; } @Override public void setServerBootstrap(Bootstrap serverBootstrap) { this.serverBootstrap = serverBootstrap; } public ChannelPipelineFactory getPipelineFactory() { return pipelineFactory; } @Override @Required public void setPipelineFactory(ChannelPipelineFactory factory) { pipelineFactory = factory; } public int getPortNumber() { return portNumber; } public void setPortNumber(int portNumber) { this.portNumber = portNumber; } public IGameAdminService getGameAdminService() { return gameAdminService; } public void setGameAdminService(IGameAdminService gameAdminService) { this.gameAdminService = gameAdminService; } }
Added overloaded method to startserver and also altered default port number.
jetserver/src/main/java/org/menacheri/server/netty/NettyServer.java
Added overloaded method to startserver and also altered default port number.
<ide><path>etserver/src/main/java/org/menacheri/server/netty/NettyServer.java <ide> { <ide> private static final Logger LOG = LoggerFactory.getLogger(NettyServer.class); <ide> <del> int portNumber = 8090; <add> int portNumber = 18090; <ide> Bootstrap serverBootstrap; <ide> ChannelPipelineFactory pipelineFactory; <ide> IGameAdminService gameAdminService; <ide> <ide> public abstract void startServer(int port); <ide> <add> public abstract void startServer(); <ide> <ide> public boolean stopServer() <ide> {
Java
bsd-2-clause
5e0d52bc8e3bfbeee0188224f81453967bdfdd51
0
seraphr/CollectionUtil
package jp.seraphr.collection; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import jp.seraphr.collection.builder.Builder; import jp.seraphr.collection.builder.ListBuilder; import jp.seraphr.common.Converter; import jp.seraphr.common.Converter2; import jp.seraphr.common.Equivalence; import jp.seraphr.common.NotPredicate; import jp.seraphr.common.Predicate; import jp.seraphr.common.Tuple2; /** * コレクションに対する高階関数群を提供するユーティリティクラスです。 * このクラスのユーティリティは注記のない限り、副作用はありません。 */ public final class CollectionUtils { private CollectionUtils() { } /** * 与えられたListの要素をそれぞれ{@link Converter} によって変換した、新しいListを作って返します。 * * @param <_Source> 変換元要素の型 * @param <_Dest> 変換先要素の型 * @param aSource 変換元List * @param aConverter 変換関数 * @return 変換結果List */ public static <_Source, _Dest> List<_Dest> map(List<_Source> aSource, Converter<? super _Source, ? extends _Dest> aConverter) { return map(aSource, new ListBuilder<_Dest>(), aConverter); } /** * 与えられたIterableの要素をそれぞれ{@link Converter} によって変換し、変換結果をaBuilderに与えて{@link Builder#build()} 結果を返します。 * * @param <_Source> 変換元要素の型 * @param <_Dest> 変換先要素の型 * @param <_Result> 変換先の型 * @param aSource 変換元Iterable * @param aBuilder 結果オブジェクトのビルダ * @param aConverter 要素の変換関数 * @return 変換結果オブジェクト */ public static <_Source, _Dest, _Result> _Result map(Iterable<_Source> aSource, Builder<_Dest, _Result> aBuilder, Converter<? super _Source, ? extends _Dest> aConverter) { for (_Source tSource : aSource) { aBuilder.add(aConverter.convert(tSource)); } return aBuilder.build(); } /** * 副作用有り。 * * @param <_Element> * @param aSource * @param aPredicate * @return * @deprecated つーかこれ消す。 use filterNot */ public static <_Element> List<_Element> remove(List<_Element> aSource, Predicate<? super _Element> aPredicate) { List<_Element> tResult = new ArrayList<_Element>(); Iterator<_Element> tIterator = aSource.iterator(); while (tIterator.hasNext()) { _Element tElement = tIterator.next(); if (aPredicate.apply(tElement)) { tIterator.remove(); tResult.add(tElement); } } return tResult; } /** * 与えられたListの要素のうち、与えられた条件に合致するもののみを含むListを生成して返します。 * * @param <_Element> 要素型 * @param aSource 元となるList * @param aPredicate 条件関数 * @return aPreicateの{@link Predicate#apply(Object)}がtrueを返すもののみを含むリスト */ public static <_Element> List<_Element> filter(List<_Element> aSource, Predicate<? super _Element> aPredicate) { return filter(aSource, new ListBuilder<_Element>(), aPredicate); } /** * 与えられたIterableの要素のうち、与えられた条件に合致するもののみをビルダに与え、{@link Builder#build()} 結果を返します。 * * @param <_Elem> 要素型 * @param <_Result> 結果型 * @param aSource 元となるIterable * @param aBuilder 結果オブジェクトのビルダ * @param aPredicate 要件関数 * @return aBuilderによって生成されたオブジェクト */ public static <_Elem, _Result> _Result filter(Iterable<_Elem> aSource, Builder<_Elem, _Result> aBuilder, Predicate<? super _Elem> aPredicate) { for (_Elem tElement : aSource) { if (aPredicate.apply(tElement)) aBuilder.add(tElement); } return aBuilder.build(); } /** * {@link #filter(List, Predicate)}の逆。 * 条件に合致しないもののみを含むListを生成して返します。 * * @see #filter(List, Predicate) * @param <_Element> * @param aSource * @param aPredicate * @return */ public static <_Element> List<_Element> filterNot(List<_Element> aSource, Predicate<? super _Element> aPredicate) { return filter(aSource, NotPredicate.create(aPredicate)); } /** * {@link #filter(Iterable, Builder, Predicate)}の逆。 * 条件に合致しないもののみをビルダに与え、{@link Builder#build()} 結果を返します。 * * @see #filter(Iterable, Builder, Predicate) * @param <_Elem> * @param <_Result> * @param aSource * @param aBuilder * @param aPredicate * @return */ public static <_Elem, _Result> _Result filterNot(Iterable<_Elem> aSource, Builder<_Elem, _Result> aBuilder, Predicate<? super _Elem> aPredicate){ return filter(aSource, aBuilder, NotPredicate.create(aPredicate)); } /** * 与えられたIterableの要素内から、与えられた条件に合致するものを探して返します。 * * @param <_Element> 要素型 * @param aSource 探索対象Iterable * @param aPredicate 条件関数 * @return 条件に合致するものがあった場合そのオブジェクト、そうでない場合null */ public static <_Element> _Element find(Iterable<_Element> aSource, Predicate<? super _Element> aPredicate) { for (_Element tElement : aSource) { if (aPredicate.apply(tElement)) return tElement; } return null; } /** * 与えられたListの要素内から、与えられた条件に合致するものを探し、その要素番号を返します。 * * @param <_Element> 要素型 * @param aSource 探索対象List * @param aPredicate 条件関数 * @return 条件に合致するものが見つかった場合その要素番号、そうでない場合負の数 */ public static <_Element> int findIndex(List<_Element> aSource, Predicate<? super _Element> aPredicate) { int tLength = aSource.size(); for (int i = 0; i < tLength; i++) { if (aPredicate.apply(aSource.get(i))) return i; } return -1; } /** * 与えられたIterableの要素から、与えられた条件に合致するものが存在するかどうかを返します。 * * @param <_Element> 要素型 * @param aSource 探索対象Iterable * @param aPredicate 条件関数 * @return 条件に合致するものが見つかった場合true */ public static <_Element> boolean contains(Iterable<_Element> aSource, Predicate<? super _Element> aPredicate) { return find(aSource, aPredicate) != null; } /** * 与えられたIterableの要素と、与えられた条件オブジェクトを、{@link Equivalence}で確認し、同一性が認められるものが存在するかどうかを返します。 * * @param <_Element1> Iterableの要素型 * @param <_Element2> 条件オブジェクト型 * @param aSource 探索対象Iterable * @param aTarget 条件オブジェクト * @param aEquivalence 同一性検査器 * @return 同一性が認められるものが存在したらtrue */ public static <_Element1, _Element2> boolean contains(Iterable<_Element1> aSource, _Element2 aTarget, Equivalence<? super _Element1, ? super _Element2> aEquivalence) { final _Element2 tTarget = aTarget; final Equivalence<? super _Element1, ? super _Element2> tEquivalence = aEquivalence; Predicate<_Element1> tPredicate = new Predicate<_Element1>() { @Override public boolean apply(_Element1 aTarget) { return tEquivalence.apply(aTarget, tTarget); } }; return contains(aSource, tPredicate); } /** * aSourceを畳み込み、_Result型の結果を返します。 * 畳込みは先頭側から行われます。 * * @param <_Elem> 要素型 * @param <_Result> 結果型 * @param aSource 畳み込み対象のコレクション * @param aFirst 畳み込み結果の初期値。 aSourceの長さが0の場合、この値が返る * @param aConverter 畳み込み演算を表す{@link Converter2}。 {@link Converter2#convert(Object, Object)}の第一引数は畳み込み演算の途中結果、第二引数はコレクションの要素を表す。 * @return 畳み込み演算結果 */ public static <_Elem, _Result> _Result foldLeft(Iterable<_Elem> aSource, _Result aFirst, Converter2<_Result, _Elem, _Result> aConverter){ _Result tResult = aFirst; for (_Elem tElem : aSource) { tResult = aConverter.convert(tResult, tElem); } return tResult; } /** * aSourceを畳み込み、_Elem型の結果を返します。 * 畳込みは先頭側から行われます。 * * 畳込みの初期値としてaSourceの先頭要素が使用されます。 * aSourceの長さが0の場合例外を発生させます。 * aSourceの長さが1の場合先頭の要素を返します。 * * * @param <_Elem> * @param aSource 畳み込み対象コレクション 長さが0の場合例外 * @param aConverter 畳み込み演算を表す{@link Converter2}。 {@link Converter2#convert(Object, Object)}の第一引数は畳み込み演算の途中結果、第二引数はコレクションの要素を表す。 * @return */ public static <_Elem> _Elem reduceLeft(Iterable<_Elem> aSource, Converter2<_Elem, _Elem, _Elem> aConverter){ Iterator<_Elem> tIterator = aSource.iterator(); if(!tIterator.hasNext()) throw new RuntimeException("aSource has no element."); _Elem tResult = tIterator.next(); while(tIterator.hasNext()){ tResult = aConverter.convert(tResult, tIterator.next()); } return tResult; } /** * 2つのリストから、{@link Tuple2}のリストを生成して返します。 * 結果Listの長さは、与えられた2つのリストの長さのうち短い方と同じになります。 * * @param <_E1> 一つ目のListの要素型 * @param <_E2> 二つ目のListの要素型 * @param aList1 * @param aList2 * @return */ public static <_E1, _E2> List<Tuple2<_E1, _E2>> zip(List<_E1> aList1, List<_E2> aList2) { return zip(aList1, aList2, new ListBuilder<Tuple2<_E1, _E2>>()); } /** * 2つのIterableから、{@link Tuple2}を生成し、aBuilderに与え、{@link Builder#build()}の結果を返します。 * * @param <_E1> 一つ目の要素型 * @param <_E2> 二つ目の要素型 * @param <_Result> 生成されるコンテナの型 * @param aSource1 * @param aSource2 * @param aBuilder * @return 生成されたコンテナ * @see CollectionUtils#zip(List, List) */ public static <_E1, _E2, _Result> _Result zip(Iterable<_E1> aSource1, Iterable<_E2> aSource2, Builder<Tuple2<_E1, _E2>, _Result> aBuilder){ Iterator<_E1> tIterator1 = aSource1.iterator(); Iterator<_E2> tIterator2 = aSource2.iterator(); while(tIterator1.hasNext() && tIterator2.hasNext()){ aBuilder.add(Tuple2.create(tIterator1.next(), tIterator2.next())); } return aBuilder.build(); } /** * 与えられたリストを、(要素, 添字番号)の{@link Tuple2}のリストに変換して返します。 * * @param <_E> 要素型 * @param aList * @return */ public static <_E> List<Tuple2<_E, Integer>> zipWithIndex(List<_E> aList) { List<Tuple2<_E, Integer>> tResult = new ArrayList<Tuple2<_E, Integer>>(); int tLength = aList.size(); for (int i = 0; i < tLength; i++) { tResult.add(Tuple2.create(aList.get(i), i)); } return tResult; } /** * 与えられたリストの要素を、与えられた2つのConverterで変換し、新しいListを作って返します。 * * @param <_Source> * @param <_E1> * @param <_E2> * @param aSourceList * @param aConverter1 * @param aConverter2 * @return */ public static <_Source, _E1, _E2> List<Tuple2<_E1, _E2>> zip(List<_Source> aSourceList, Converter<? super _Source, ? extends _E1> aConverter1, Converter<? super _Source, ? extends _E2> aConverter2) { final Converter<? super _Source, ? extends _E1> tConverter1 = aConverter1; final Converter<? super _Source, ? extends _E2> tConverter2 = aConverter2; return map(aSourceList, new Converter<_Source, Tuple2<_E1, _E2>>() { @Override public Tuple2<_E1, _E2> convert(_Source aSource) { return Tuple2.<_E1, _E2>create(tConverter1.convert(aSource), tConverter2.convert(aSource)); } }); } /** * {@link Tuple2}のリストから、Tupleの要素を分離した2つのリストを作成して返します。 * * @param <_E1> * @param <_E2> * @param aTupleList * @return */ public static <_E1, _E2> Tuple2<List<_E1>, List<_E2>> unzip(List<Tuple2<_E1, _E2>> aTupleList) { List<_E1> tResult1 = new ArrayList<_E1>(); List<_E2> tResult2 = new ArrayList<_E2>(); List<Tuple2<_E1, _E2>> tSource = aTupleList; for (Tuple2<_E1, _E2> tTuple2 : tSource) { tResult1.add(tTuple2.get1()); tResult2.add(tTuple2.get2()); } return Tuple2.create(tResult1, tResult2); } public static <_E1, _E2> List<_E1> unzip1(List<Tuple2<_E1, _E2>> aTupleList) { List<_E1> tResult = new ArrayList<_E1>(); List<Tuple2<_E1, _E2>> tSource = aTupleList; for (Tuple2<_E1, _E2> tTuple2 : tSource) { tResult.add(tTuple2.get1()); } return tResult; } public static <_E1, _E2> List<_E2> unzip2(List<Tuple2<_E1, _E2>> aTupleList) { List<_E2> tResult = new ArrayList<_E2>(); List<Tuple2<_E1, _E2>> tSource = aTupleList; for (Tuple2<_E1, _E2> tTuple2 : tSource) { tResult.add(tTuple2.get2()); } return tResult; } public static <_E1, _E2> Tuple2<_E1, _E2> findElement1(List<Tuple2<_E1, _E2>> aTupleList, _E1 aTarget) { int tIndex = findElementIndex1(aTupleList, aTarget); if (tIndex < 0) return null; return aTupleList.get(tIndex); } public static <_E1, _E2> int findElementIndex1(List<Tuple2<_E1, _E2>> aTupleList, final _E1 aTarget) { return findIndex(aTupleList, new Predicate<Tuple2<_E1, _E2>>() { @Override public boolean apply(Tuple2<_E1, _E2> aTuple) { return aTuple.get1().equals(aTarget); } }); } public static <_E1, _E2> Tuple2<_E1, _E2> findElement2(List<Tuple2<_E1, _E2>> aTupleList, _E2 aTarget) { int tIndex = findElementIndex2(aTupleList, aTarget); if (tIndex < 0) return null; return aTupleList.get(tIndex); } public static <_E1, _E2> int findElementIndex2(List<Tuple2<_E1, _E2>> aTupleList, final _E2 aTarget) { return findIndex(aTupleList, new Predicate<Tuple2<_E1, _E2>>() { @Override public boolean apply(Tuple2<_E1, _E2> aTuple) { return aTuple.get2().equals(aTarget); } }); } }
src/main/java/jp/seraphr/collection/CollectionUtils.java
package jp.seraphr.collection; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import jp.seraphr.collection.builder.Builder; import jp.seraphr.collection.builder.ListBuilder; import jp.seraphr.common.Converter; import jp.seraphr.common.Converter2; import jp.seraphr.common.Equivalence; import jp.seraphr.common.NotPredicate; import jp.seraphr.common.Predicate; import jp.seraphr.common.Tuple2; /** * コレクションに対する高階関数群を提供するユーティリティクラスです。 * このクラスのユーティリティは注記のない限り、副作用はありません。 */ public final class CollectionUtils { private CollectionUtils() { } /** * 与えられたListの要素をそれぞれ{@link Converter} によって変換した、新しいListを作って返します。 * * @param <_Source> 変換元要素の型 * @param <_Dest> 変換先要素の型 * @param aSource 変換元List * @param aConverter 変換関数 * @return 変換結果List */ public static <_Source, _Dest> List<_Dest> map(List<_Source> aSource, Converter<? super _Source, ? extends _Dest> aConverter) { return map(aSource, new ListBuilder<_Dest>(), aConverter); } /** * 与えられたIterableの要素をそれぞれ{@link Converter} によって変換し、変換結果をaBuilderに与えて{@link Builder#build()} 結果を返します。 * * @param <_Source> 変換元要素の型 * @param <_Dest> 変換先要素の型 * @param <_Result> 変換先の型 * @param aSource 変換元Iterable * @param aBuilder 結果オブジェクトのビルダ * @param aConverter 要素の変換関数 * @return 変換結果オブジェクト */ public static <_Source, _Dest, _Result> _Result map(Iterable<_Source> aSource, Builder<_Dest, _Result> aBuilder, Converter<? super _Source, ? extends _Dest> aConverter) { for (_Source tSource : aSource) { aBuilder.add(aConverter.convert(tSource)); } return aBuilder.build(); } /** * 副作用有り。 * * @param <_Element> * @param aSource * @param aPredicate * @return * @deprecated つーかこれ消す。 use filterNot */ public static <_Element> List<_Element> remove(List<_Element> aSource, Predicate<? super _Element> aPredicate) { List<_Element> tResult = new ArrayList<_Element>(); Iterator<_Element> tIterator = aSource.iterator(); while (tIterator.hasNext()) { _Element tElement = tIterator.next(); if (aPredicate.apply(tElement)) { tIterator.remove(); tResult.add(tElement); } } return tResult; } /** * 与えられたListの要素のうち、与えられた条件に合致するもののみを含むListを生成して返します。 * * @param <_Element> 要素型 * @param aSource 元となるList * @param aPredicate 条件関数 * @return aPreicateの{@link Predicate#apply(Object)}がtrueを返すもののみを含むリスト */ public static <_Element> List<_Element> filter(List<_Element> aSource, Predicate<? super _Element> aPredicate) { return filter(aSource, new ListBuilder<_Element>(), aPredicate); } /** * 与えられたIterableの要素のうち、与えられた条件に合致するもののみをビルダに与え、{@link Builder#build()} 結果を返します。 * * @param <_Elem> 要素型 * @param <_Result> 結果型 * @param aSource 元となるIterable * @param aBuilder 結果オブジェクトのビルダ * @param aPredicate 要件関数 * @return aBuilderによって生成されたオブジェクト */ public static <_Elem, _Result> _Result filter(Iterable<_Elem> aSource, Builder<_Elem, _Result> aBuilder, Predicate<? super _Elem> aPredicate) { for (_Elem tElement : aSource) { if (aPredicate.apply(tElement)) aBuilder.add(tElement); } return aBuilder.build(); } /** * {@link #filter(List, Predicate)}の逆。 * 条件に合致しないもののみを含むListを生成して返します。 * * @see #filter(List, Predicate) * @param <_Element> * @param aSource * @param aPredicate * @return */ public static <_Element> List<_Element> filterNot(List<_Element> aSource, Predicate<? super _Element> aPredicate) { return filter(aSource, NotPredicate.create(aPredicate)); } /** * {@link #filter(Iterable, Builder, Predicate)}の逆。 * 条件に合致しないもののみをビルダに与え、{@link Builder#build()} 結果を返します。 * * @see #filter(Iterable, Builder, Predicate) * @param <_Elem> * @param <_Result> * @param aSource * @param aBuilder * @param aPredicate * @return */ public static <_Elem, _Result> _Result filterNot(Iterable<_Elem> aSource, Builder<_Elem, _Result> aBuilder, Predicate<? super _Elem> aPredicate){ return filter(aSource, aBuilder, NotPredicate.create(aPredicate)); } /** * 与えられたIterableの要素内から、与えられた条件に合致するものを探して返します。 * * @param <_Element> 要素型 * @param aSource 探索対象Iterable * @param aPredicate 条件関数 * @return 条件に合致するものがあった場合そのオブジェクト、そうでない場合null */ public static <_Element> _Element find(Iterable<_Element> aSource, Predicate<? super _Element> aPredicate) { for (_Element tElement : aSource) { if (aPredicate.apply(tElement)) return tElement; } return null; } /** * 与えられたListの要素内から、与えられた条件に合致するものを探し、その要素番号を返します。 * * @param <_Element> 要素型 * @param aSource 探索対象List * @param aPredicate 条件関数 * @return 条件に合致するものが見つかった場合その要素番号、そうでない場合負の数 */ public static <_Element> int findIndex(List<_Element> aSource, Predicate<? super _Element> aPredicate) { int tLength = aSource.size(); for (int i = 0; i < tLength; i++) { if (aPredicate.apply(aSource.get(i))) return i; } return -1; } /** * 与えられたIterableの要素から、与えられた条件に合致するものが存在するかどうかを返します。 * * @param <_Element> 要素型 * @param aSource 探索対象Iterable * @param aPredicate 条件関数 * @return 条件に合致するものが見つかった場合true */ public static <_Element> boolean contains(Iterable<_Element> aSource, Predicate<? super _Element> aPredicate) { return find(aSource, aPredicate) != null; } /** * 与えられたIterableの要素と、与えられた条件オブジェクトを、{@link Equivalence}で確認し、同一性が認められるものが存在するかどうかを返します。 * * @param <_Element1> Iterableの要素型 * @param <_Element2> 条件オブジェクト型 * @param aSource 探索対象Iterable * @param aTarget 条件オブジェクト * @param aEquivalence 同一性検査器 * @return 同一性が認められるものが存在したらtrue */ public static <_Element1, _Element2> boolean contains(Iterable<_Element1> aSource, _Element2 aTarget, Equivalence<? super _Element1, ? super _Element2> aEquivalence) { final _Element2 tTarget = aTarget; final Equivalence<? super _Element1, ? super _Element2> tEquivalence = aEquivalence; Predicate<_Element1> tPredicate = new Predicate<_Element1>() { @Override public boolean apply(_Element1 aTarget) { return tEquivalence.apply(aTarget, tTarget); } }; return contains(aSource, tPredicate); } /** * aSourceを畳み込み、_Result型の結果を返します。 * 畳込みは先頭側から行われます。 * * @param <_Elem> 要素型 * @param <_Result> 結果型 * @param aSource 畳み込み対象のコレクション * @param aFirst 畳み込み結果の初期値。 aSourceの長さが0の場合、この値が返る * @param aConverter 畳み込み演算を表す{@link Converter2}。 {@link Converter2#convert(Object, Object)}の第一引数は畳み込み演算の途中結果、第二引数はコレクションの要素を表す。 * @return 畳み込み演算結果 */ public static <_Elem, _Result> _Result foldLeft(Iterable<_Elem> aSource, _Result aFirst, Converter2<_Result, _Elem, _Result> aConverter){ _Result tResult = aFirst; for (_Elem tElem : aSource) { tResult = aConverter.convert(tResult, tElem); } return tResult; } /** * aSourceを畳み込み、_Elem型の結果を返します。 * 畳込みは先頭側から行われます。 * * 畳込みの初期値としてaSourceの先頭要素が使用されます。 * aSourceの長さが0の場合例外を発生させます。 * aSourceの長さが1の場合先頭の要素を返します。 * * * @param <_Elem> * @param aSource 畳み込み対象コレクション 長さが0の場合例外 * @param aConverter 畳み込み演算を表す{@link Converter2}。 {@link Converter2#convert(Object, Object)}の第一引数は畳み込み演算の途中結果、第二引数はコレクションの要素を表す。 * @return */ public static <_Elem> _Elem reduceLeft(Iterable<_Elem> aSource, Converter2<_Elem, _Elem, _Elem> aConverter){ Iterator<_Elem> tIterator = aSource.iterator(); if(!tIterator.hasNext()) throw new RuntimeException("aSource has no element."); _Elem tResult = tIterator.next(); while(tIterator.hasNext()){ tResult = aConverter.convert(tResult, tIterator.next()); } return tResult; } /** * 2つのリストから、{@link Tuple2}のリストを生成して返します。 * 結果Listの長さは、与えられた2つのリストの長さのうち短い方と同じになります。 * * @param <_E1> 一つ目のListの要素型 * @param <_E2> 二つ目のListの要素型 * @param aList1 * @param aList2 * @return */ public static <_E1, _E2> List<Tuple2<_E1, _E2>> zip(List<_E1> aList1, List<_E2> aList2) { int tLength = Math.min(aList1.size(), aList2.size()); List<Tuple2<_E1, _E2>> tResult = new ArrayList<Tuple2<_E1, _E2>>(); for (int i = 0; i < tLength; i++) { tResult.add(new Tuple2<_E1, _E2>(aList1.get(i), aList2.get(i))); } return tResult; } /** * 与えられたリストを、(要素, 添字番号)の{@link Tuple2}のリストに変換して返します。 * * @param <_E> 要素型 * @param aList * @return */ public static <_E> List<Tuple2<_E, Integer>> zipWithIndex(List<_E> aList) { List<Tuple2<_E, Integer>> tResult = new ArrayList<Tuple2<_E, Integer>>(); int tLength = aList.size(); for (int i = 0; i < tLength; i++) { tResult.add(Tuple2.create(aList.get(i), i)); } return tResult; } /** * 与えられたリストの要素を、与えられた2つのConverterで変換し、新しいListを作って返します。 * * @param <_Source> * @param <_E1> * @param <_E2> * @param aSourceList * @param aConverter1 * @param aConverter2 * @return */ public static <_Source, _E1, _E2> List<Tuple2<_E1, _E2>> zip(List<_Source> aSourceList, Converter<? super _Source, ? extends _E1> aConverter1, Converter<? super _Source, ? extends _E2> aConverter2) { final Converter<? super _Source, ? extends _E1> tConverter1 = aConverter1; final Converter<? super _Source, ? extends _E2> tConverter2 = aConverter2; return map(aSourceList, new Converter<_Source, Tuple2<_E1, _E2>>() { @Override public Tuple2<_E1, _E2> convert(_Source aSource) { return Tuple2.<_E1, _E2>create(tConverter1.convert(aSource), tConverter2.convert(aSource)); } }); } /** * {@link Tuple2}のリストから、Tupleの要素を分離した2つのリストを作成して返します。 * * @param <_E1> * @param <_E2> * @param aTupleList * @return */ public static <_E1, _E2> Tuple2<List<_E1>, List<_E2>> unzip(List<Tuple2<_E1, _E2>> aTupleList) { List<_E1> tResult1 = new ArrayList<_E1>(); List<_E2> tResult2 = new ArrayList<_E2>(); List<Tuple2<_E1, _E2>> tSource = aTupleList; for (Tuple2<_E1, _E2> tTuple2 : tSource) { tResult1.add(tTuple2.get1()); tResult2.add(tTuple2.get2()); } return Tuple2.create(tResult1, tResult2); } public static <_E1, _E2> List<_E1> unzip1(List<Tuple2<_E1, _E2>> aTupleList) { List<_E1> tResult = new ArrayList<_E1>(); List<Tuple2<_E1, _E2>> tSource = aTupleList; for (Tuple2<_E1, _E2> tTuple2 : tSource) { tResult.add(tTuple2.get1()); } return tResult; } public static <_E1, _E2> List<_E2> unzip2(List<Tuple2<_E1, _E2>> aTupleList) { List<_E2> tResult = new ArrayList<_E2>(); List<Tuple2<_E1, _E2>> tSource = aTupleList; for (Tuple2<_E1, _E2> tTuple2 : tSource) { tResult.add(tTuple2.get2()); } return tResult; } public static <_E1, _E2> Tuple2<_E1, _E2> findElement1(List<Tuple2<_E1, _E2>> aTupleList, _E1 aTarget) { int tIndex = findElementIndex1(aTupleList, aTarget); if (tIndex < 0) return null; return aTupleList.get(tIndex); } public static <_E1, _E2> int findElementIndex1(List<Tuple2<_E1, _E2>> aTupleList, final _E1 aTarget) { return findIndex(aTupleList, new Predicate<Tuple2<_E1, _E2>>() { @Override public boolean apply(Tuple2<_E1, _E2> aTuple) { return aTuple.get1().equals(aTarget); } }); } public static <_E1, _E2> Tuple2<_E1, _E2> findElement2(List<Tuple2<_E1, _E2>> aTupleList, _E2 aTarget) { int tIndex = findElementIndex2(aTupleList, aTarget); if (tIndex < 0) return null; return aTupleList.get(tIndex); } public static <_E1, _E2> int findElementIndex2(List<Tuple2<_E1, _E2>> aTupleList, final _E2 aTarget) { return findIndex(aTupleList, new Predicate<Tuple2<_E1, _E2>>() { @Override public boolean apply(Tuple2<_E1, _E2> aTuple) { return aTuple.get2().equals(aTarget); } }); } }
zipにBuilderを使用する実装を追加。 既存の実装をそちらに依存するようにした
src/main/java/jp/seraphr/collection/CollectionUtils.java
zipにBuilderを使用する実装を追加。 既存の実装をそちらに依存するようにした
<ide><path>rc/main/java/jp/seraphr/collection/CollectionUtils.java <ide> * @return <ide> */ <ide> public static <_E1, _E2> List<Tuple2<_E1, _E2>> zip(List<_E1> aList1, List<_E2> aList2) { <del> int tLength = Math.min(aList1.size(), aList2.size()); <del> <del> List<Tuple2<_E1, _E2>> tResult = new ArrayList<Tuple2<_E1, _E2>>(); <del> for (int i = 0; i < tLength; i++) { <del> tResult.add(new Tuple2<_E1, _E2>(aList1.get(i), aList2.get(i))); <del> } <del> <del> return tResult; <add> return zip(aList1, aList2, new ListBuilder<Tuple2<_E1, _E2>>()); <add> } <add> <add> /** <add> * 2つのIterableから、{@link Tuple2}を生成し、aBuilderに与え、{@link Builder#build()}の結果を返します。 <add> * <add> * @param <_E1> 一つ目の要素型 <add> * @param <_E2> 二つ目の要素型 <add> * @param <_Result> 生成されるコンテナの型 <add> * @param aSource1 <add> * @param aSource2 <add> * @param aBuilder <add> * @return 生成されたコンテナ <add> * @see CollectionUtils#zip(List, List) <add> */ <add> public static <_E1, _E2, _Result> _Result zip(Iterable<_E1> aSource1, Iterable<_E2> aSource2, Builder<Tuple2<_E1, _E2>, _Result> aBuilder){ <add> Iterator<_E1> tIterator1 = aSource1.iterator(); <add> Iterator<_E2> tIterator2 = aSource2.iterator(); <add> <add> while(tIterator1.hasNext() && tIterator2.hasNext()){ <add> aBuilder.add(Tuple2.create(tIterator1.next(), tIterator2.next())); <add> } <add> <add> return aBuilder.build(); <ide> } <ide> <ide> /**
Java
apache-2.0
5329f5419acd376e2597ca2a30dadf7ad8898af4
0
facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho; import static androidx.core.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO; import static com.facebook.litho.Component.isHostSpec; import static com.facebook.litho.Component.isMountViewSpec; import static com.facebook.litho.ComponentHostUtils.maybeSetDrawableState; import static com.facebook.litho.FrameworkLogEvents.EVENT_MOUNT; import static com.facebook.litho.FrameworkLogEvents.PARAM_IS_DIRTY; import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_CONTENT; import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_COUNT; import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_EXTRAS; import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_TIME; import static com.facebook.litho.FrameworkLogEvents.PARAM_MOVED_COUNT; import static com.facebook.litho.FrameworkLogEvents.PARAM_NO_OP_COUNT; import static com.facebook.litho.FrameworkLogEvents.PARAM_UNCHANGED_COUNT; import static com.facebook.litho.FrameworkLogEvents.PARAM_UNMOUNTED_CONTENT; import static com.facebook.litho.FrameworkLogEvents.PARAM_UNMOUNTED_COUNT; import static com.facebook.litho.FrameworkLogEvents.PARAM_UNMOUNTED_TIME; import static com.facebook.litho.FrameworkLogEvents.PARAM_UPDATED_CONTENT; import static com.facebook.litho.FrameworkLogEvents.PARAM_UPDATED_COUNT; import static com.facebook.litho.FrameworkLogEvents.PARAM_UPDATED_TIME; import static com.facebook.litho.FrameworkLogEvents.PARAM_VISIBILITY_HANDLER; import static com.facebook.litho.FrameworkLogEvents.PARAM_VISIBILITY_HANDLERS_TOTAL_TIME; import static com.facebook.litho.FrameworkLogEvents.PARAM_VISIBILITY_HANDLER_TIME; import static com.facebook.litho.LayoutOutput.getLayoutOutput; import static com.facebook.litho.LithoMountData.getMountData; import static com.facebook.litho.LithoMountData.isViewClickable; import static com.facebook.litho.LithoMountData.isViewEnabled; import static com.facebook.litho.LithoMountData.isViewFocusable; import static com.facebook.litho.LithoMountData.isViewLongClickable; import static com.facebook.litho.LithoMountData.isViewSelected; import static com.facebook.litho.LithoRenderUnit.getComponentContext; import static com.facebook.litho.ThreadUtils.assertMainThread; import static com.facebook.rendercore.MountState.ROOT_HOST_ID; import android.animation.AnimatorInflater; import android.animation.StateListAnimator; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.TextUtils; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import android.view.ViewOutlineProvider; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import androidx.collection.LongSparseArray; import androidx.core.util.Preconditions; import androidx.core.view.ViewCompat; import com.facebook.infer.annotation.ThreadConfined; import com.facebook.litho.config.ComponentsConfiguration; import com.facebook.litho.stats.LithoStats; import com.facebook.rendercore.ErrorReporter; import com.facebook.rendercore.Host; import com.facebook.rendercore.LogLevel; import com.facebook.rendercore.MountDelegate; import com.facebook.rendercore.MountDelegateTarget; import com.facebook.rendercore.MountItem; import com.facebook.rendercore.RenderCoreExtensionHost; import com.facebook.rendercore.RenderTree; import com.facebook.rendercore.RenderTreeNode; import com.facebook.rendercore.UnmountDelegateExtension; import com.facebook.rendercore.extensions.ExtensionState; import com.facebook.rendercore.extensions.MountExtension; import com.facebook.rendercore.incrementalmount.IncrementalMountOutput; import com.facebook.rendercore.utils.BoundsUtils; import com.facebook.rendercore.visibility.VisibilityItem; import com.facebook.rendercore.visibility.VisibilityMountExtension; import java.util.ArrayList; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; /** * Encapsulates the mounted state of a {@link Component}. Provides APIs to update state by recycling * existing UI elements e.g. {@link Drawable}s. * * @see #mount(LayoutState, Rect, boolean) * @see LithoView * @see LayoutState */ @ThreadConfined(ThreadConfined.UI) class MountState implements MountDelegateTarget { private static final String INVALID_REENTRANT_MOUNTS = "MountState:InvalidReentrantMounts"; private static final double NS_IN_MS = 1000000.0; private static final Rect sTempRect = new Rect(); // Holds the current list of mounted items. // Should always be used within a draw lock. private final LongSparseArray<MountItem> mIndexToItemMap; // Holds a list of MountItems that are currently mounted which can mount incrementally. private final LongSparseArray<MountItem> mCanMountIncrementallyMountItems; // A map from test key to a list of one or more `TestItem`s which is only allocated // and populated during test runs. private final Map<String, Deque<TestItem>> mTestItemMap; // Both these arrays are updated in prepareMount(), thus during mounting they hold the information // about the LayoutState that is being mounted, not mLastMountedLayoutState @Nullable private long[] mLayoutOutputsIds; // True if we are receiving a new LayoutState and we need to completely // refresh the content of the HostComponent. Always set from the main thread. private boolean mIsDirty; // True if MountState is currently performing mount. private boolean mIsMounting; // See #needsRemount() private boolean mNeedsRemount; // Holds the list of known component hosts during a mount pass. private final LongSparseArray<ComponentHost> mHostsByMarker = new LongSparseArray<>(); private final ComponentContext mContext; private final LithoView mLithoView; private final Rect mPreviousLocalVisibleRect = new Rect(); private final PrepareMountStats mPrepareMountStats = new PrepareMountStats(); private final MountStats mMountStats = new MountStats(); private int mPreviousTopsIndex; private int mPreviousBottomsIndex; private int mLastMountedComponentTreeId = ComponentTree.INVALID_ID; private @Nullable LayoutState mLayoutState; private @Nullable LayoutState mLastMountedLayoutState; private int mLastDisappearRangeStart = -1; private int mLastDisappearRangeEnd = -1; private final MountItem mRootHostMountItem; private final @Nullable VisibilityMountExtension mVisibilityExtension; private final @Nullable ExtensionState mVisibilityExtensionState; private final Set<Long> mComponentIdsMountedInThisFrame = new HashSet<>(); private final DynamicPropsManager mDynamicPropsManager = new DynamicPropsManager(); private @Nullable MountDelegate mMountDelegate; private @Nullable UnmountDelegateExtension mUnmountDelegateExtension; private @Nullable TransitionsExtension mTransitionsExtension; private @Nullable ExtensionState mTransitionsExtensionState; private @ComponentTree.RecyclingMode int mRecyclingMode = ComponentTree.RecyclingMode.DEFAULT; public MountState(LithoView view) { mIndexToItemMap = new LongSparseArray<>(); mCanMountIncrementallyMountItems = new LongSparseArray<>(); mContext = view.getComponentContext(); mLithoView = view; mIsDirty = true; mTestItemMap = ComponentsConfiguration.isEndToEndTestRun ? new HashMap<String, Deque<TestItem>>() : null; // The mount item representing the top-level root host (LithoView) which // is always automatically mounted. mRootHostMountItem = LithoMountData.createRootHostMountItem(mLithoView); if (ComponentsConfiguration.enableVisibilityExtension) { mVisibilityExtension = VisibilityMountExtension.getInstance(); mVisibilityExtensionState = mVisibilityExtension.createExtensionState(new MountDelegate(this)); VisibilityMountExtension.setRootHost(mVisibilityExtensionState, mLithoView); } else { mVisibilityExtension = null; mVisibilityExtensionState = null; } // Using Incremental Mount Extension and the Transition Extension here is not allowed. if (ComponentsConfiguration.enableTransitionsExtension) { if (!mLithoView.usingExtensionsWithMountDelegate()) { mTransitionsExtension = TransitionsExtension.getInstance( (AnimationsDebug.ENABLED ? AnimationsDebug.TAG : null)); registerMountDelegateExtension(mTransitionsExtension); mTransitionsExtensionState = getExtensionState(mTransitionsExtension); } } else { mTransitionsExtension = null; mTransitionsExtensionState = null; } } @Override public void registerMountDelegateExtension(MountExtension mountExtension) { if (mMountDelegate == null) { mMountDelegate = new MountDelegate(this); } mMountDelegate.addExtension(mountExtension); } @Override public void unregisterMountDelegateExtension(MountExtension mountExtension) { if (mMountDelegate == null) { return; } mMountDelegate.removeExtension(mountExtension); } /** * To be called whenever the components needs to start the mount process from scratch e.g. when * the component's props or layout change or when the components gets attached to a host. */ void setDirty() { assertMainThread(); mIsDirty = true; mPreviousLocalVisibleRect.setEmpty(); } boolean isDirty() { assertMainThread(); return mIsDirty; } /** * True if we have manually unmounted content (e.g. via unmountAllItems) which means that while we * may not have a new LayoutState, the mounted content does not match what the viewport for the * LithoView may be. */ @Override public boolean needsRemount() { assertMainThread(); return mNeedsRemount; } void setRecyclingMode(@ComponentTree.RecyclingMode int recyclingMode) { this.mRecyclingMode = recyclingMode; } /** * Mount the layoutState on the pre-set HostView. * * @param layoutState a new {@link LayoutState} to mount * @param localVisibleRect If this variable is null, then mount everything, since incremental * mount is not enabled. Otherwise mount only what the rect (in local coordinates) contains * @param processVisibilityOutputs whether to process visibility outputs as part of the mount */ void mount( LayoutState layoutState, @Nullable Rect localVisibleRect, boolean processVisibilityOutputs) { final ComponentTree componentTree = mLithoView.getComponentTree(); final boolean isIncrementalMountEnabled = componentTree.isIncrementalMountEnabled(); final boolean isVisibilityProcessingEnabled = componentTree.isVisibilityProcessingEnabled() && processVisibilityOutputs; assertMainThread(); if (layoutState == null) { throw new IllegalStateException("Trying to mount a null layoutState"); } if (mVisibilityExtension != null && mIsDirty) { mVisibilityExtension.beforeMount(mVisibilityExtensionState, layoutState, localVisibleRect); } if (mTransitionsExtension != null && mIsDirty) { mTransitionsExtension.beforeMount(mTransitionsExtensionState, layoutState, localVisibleRect); } mLayoutState = layoutState; if (mIsMounting) { ComponentsReporter.emitMessage( ComponentsReporter.LogLevel.FATAL, INVALID_REENTRANT_MOUNTS, "Trying to mount while already mounting! " + getMountItemDebugMessage(mRootHostMountItem)); } mIsMounting = true; final boolean isTracing = ComponentsSystrace.isTracing(); if (isTracing) { String sectionName = isIncrementalMountEnabled ? "incrementalMount" : "mount"; ComponentsSystrace.beginSectionWithArgs(sectionName) .arg("treeId", layoutState.getComponentTreeId()) .arg("component", componentTree.getSimpleName()) .arg("logTag", componentTree.getContext().getLogTag()) .flush(); // We also would like to trace this section attributed with component name // for component share analysis. ComponentsSystrace.beginSection(sectionName + "_" + componentTree.getSimpleName()); } final ComponentsLogger logger = componentTree.getContext().getLogger(); final int componentTreeId = layoutState.getComponentTreeId(); if (componentTreeId != mLastMountedComponentTreeId) { // If we're mounting a new ComponentTree, don't keep around and use the previous LayoutState // since things like transition animations aren't relevant. clearLastMountedLayoutState(); } final PerfEvent mountPerfEvent = logger == null ? null : LogTreePopulator.populatePerfEventFromLogger( componentTree.getContext(), logger, logger.newPerformanceEvent(componentTree.getContext(), EVENT_MOUNT)); if (mIsDirty) { // Prepare the data structure for the new LayoutState and removes mountItems // that are not present anymore if isUpdateMountInPlace is enabled. if (mountPerfEvent != null) { mountPerfEvent.markerPoint("PREPARE_MOUNT_START"); } prepareMount(layoutState, mountPerfEvent); if (mountPerfEvent != null) { mountPerfEvent.markerPoint("PREPARE_MOUNT_END"); } } mMountStats.reset(); if (mountPerfEvent != null && logger.isTracing(mountPerfEvent)) { mMountStats.enableLogging(); } if (!isIncrementalMountEnabled || !performIncrementalMount(layoutState, localVisibleRect, processVisibilityOutputs)) { final MountItem rootMountItem = mIndexToItemMap.get(ROOT_HOST_ID); final Rect absoluteBounds = new Rect(); for (int i = 0, size = layoutState.getMountableOutputCount(); i < size; i++) { final RenderTreeNode node = layoutState.getMountableOutputAt(i); final LayoutOutput layoutOutput = getLayoutOutput(node); final Component component = layoutOutput.getComponent(); if (isTracing) { ComponentsSystrace.beginSection(component.getSimpleName()); } final MountItem currentMountItem = getItemAt(i); final boolean isMounted = currentMountItem != null; final boolean isRoot = currentMountItem != null && currentMountItem == rootMountItem; final boolean isMountable = !isIncrementalMountEnabled || isMountedHostWithChildContent(currentMountItem) || Rect.intersects(localVisibleRect, node.getAbsoluteBounds(absoluteBounds)) || isAnimationLocked(node) || isRoot; if (isMountable && !isMounted) { mountLayoutOutput(i, node, layoutOutput, layoutState); if (isIncrementalMountEnabled) { applyMountBinders(layoutOutput, getItemAt(i), i); } } else if (!isMountable && isMounted) { unmountItem(i, mHostsByMarker); } else if (isMounted) { if (mIsDirty || (isRoot && mNeedsRemount)) { final boolean useUpdateValueFromLayoutOutput = mLastMountedLayoutState != null && mLastMountedLayoutState.getId() == layoutState.getPreviousLayoutStateId(); final long startTime = System.nanoTime(); final boolean itemUpdated = updateMountItemIfNeeded( node, currentMountItem, useUpdateValueFromLayoutOutput, componentTreeId, i); if (mMountStats.isLoggingEnabled) { if (itemUpdated) { mMountStats.updatedNames.add(component.getSimpleName()); mMountStats.updatedTimes.add((System.nanoTime() - startTime) / NS_IN_MS); mMountStats.updatedCount++; } else { mMountStats.noOpCount++; } } } if (isIncrementalMountEnabled && component.hasChildLithoViews()) { mountItemIncrementally(currentMountItem, processVisibilityOutputs); } } if (isTracing) { ComponentsSystrace.endSection(); } } if (isIncrementalMountEnabled) { setupPreviousMountableOutputData(layoutState, localVisibleRect); } } afterMountMaybeUpdateAnimations(); if (isVisibilityProcessingEnabled) { if (isTracing) { ComponentsSystrace.beginSection("processVisibilityOutputs"); } if (mountPerfEvent != null) { mountPerfEvent.markerPoint("EVENT_PROCESS_VISIBILITY_OUTPUTS_START"); } processVisibilityOutputs( layoutState, localVisibleRect, mPreviousLocalVisibleRect, mIsDirty, mountPerfEvent); if (mountPerfEvent != null) { mountPerfEvent.markerPoint("EVENT_PROCESS_VISIBILITY_OUTPUTS_END"); } if (isTracing) { ComponentsSystrace.endSection(); } } final boolean wasDirty = mIsDirty; mIsDirty = false; mNeedsRemount = false; if (localVisibleRect != null) { mPreviousLocalVisibleRect.set(localVisibleRect); } clearLastMountedLayoutState(); mLastMountedComponentTreeId = componentTreeId; mLastMountedLayoutState = layoutState; processTestOutputs(layoutState); if (mountPerfEvent != null) { logMountPerfEvent(logger, mountPerfEvent, wasDirty); } if (isTracing) { ComponentsSystrace.endSection(); ComponentsSystrace.endSection(); } LithoStats.incrementComponentMountCount(); mIsMounting = false; } private void clearLastMountedLayoutState() { mLastMountedLayoutState = null; } private void afterMountMaybeUpdateAnimations() { if (mTransitionsExtension != null && mIsDirty) { mTransitionsExtension.afterMount(mTransitionsExtensionState); } } @Override public void mount(RenderTree renderTree) { final LayoutState layoutState = (LayoutState) renderTree.getRenderTreeData(); mount(layoutState, true); } /** * Mount only. Similar shape to RenderCore's mount. For extras such as incremental mount, * visibility outputs etc register an extension. To do: extract transitions logic from here. */ void mount(LayoutState layoutState, boolean processVisibilityOutputs) { assertMainThread(); if (layoutState == null) { throw new IllegalStateException("Trying to mount a null layoutState"); } mLayoutState = layoutState; if (mIsMounting) { ComponentsReporter.emitMessage( ComponentsReporter.LogLevel.FATAL, INVALID_REENTRANT_MOUNTS, "Trying to mount while already mounting! " + getMountItemDebugMessage(mRootHostMountItem)); } mIsMounting = true; final ComponentTree componentTree = mLithoView.getComponentTree(); final boolean isTracing = ComponentsSystrace.isTracing(); if (isTracing) { ComponentsSystrace.beginSectionWithArgs("mount") .arg("treeId", layoutState.getComponentTreeId()) .arg("component", componentTree.getSimpleName()) .arg("logTag", componentTree.getContext().getLogTag()) .flush(); } final ComponentsLogger logger = componentTree.getContext().getLogger(); final int componentTreeId = layoutState.getComponentTreeId(); if (componentTreeId != mLastMountedComponentTreeId) { // If we're mounting a new ComponentTree, don't keep around and use the previous LayoutState // since things like transition animations aren't relevant. clearLastMountedLayoutState(); } final PerfEvent mountPerfEvent = logger == null ? null : LogTreePopulator.populatePerfEventFromLogger( componentTree.getContext(), logger, logger.newPerformanceEvent(componentTree.getContext(), EVENT_MOUNT)); // Prepare the data structure for the new LayoutState and removes mountItems // that are not present anymore if isUpdateMountInPlace is enabled. if (mountPerfEvent != null) { mountPerfEvent.markerPoint("PREPARE_MOUNT_START"); } prepareMount(layoutState, mountPerfEvent); if (mountPerfEvent != null) { mountPerfEvent.markerPoint("PREPARE_MOUNT_END"); } mMountStats.reset(); if (mountPerfEvent != null && logger.isTracing(mountPerfEvent)) { mMountStats.enableLogging(); } for (int i = 0, size = layoutState.getMountableOutputCount(); i < size; i++) { final RenderTreeNode renderTreeNode = layoutState.getMountableOutputAt(i); final LayoutOutput layoutOutput = getLayoutOutput(renderTreeNode); final Component component = layoutOutput.getComponent(); if (isTracing) { ComponentsSystrace.beginSection(component.getSimpleName()); } final MountItem currentMountItem = getItemAt(i); final boolean isMounted = currentMountItem != null; final boolean isMountable = isMountable(renderTreeNode, i); if (!isMountable) { if (isMounted) { unmountItem(i, mHostsByMarker); } } else if (!isMounted) { mountLayoutOutput(i, renderTreeNode, layoutOutput, layoutState); applyMountBinders(layoutOutput, getItemAt(i), i); } else { final boolean useUpdateValueFromLayoutOutput = mLastMountedLayoutState != null && mLastMountedLayoutState.getId() == layoutState.getPreviousLayoutStateId(); final long startTime = System.nanoTime(); final boolean itemUpdated = updateMountItemIfNeeded( renderTreeNode, currentMountItem, useUpdateValueFromLayoutOutput, componentTreeId, i); if (mMountStats.isLoggingEnabled) { if (itemUpdated) { mMountStats.updatedNames.add(component.getSimpleName()); mMountStats.updatedTimes.add((System.nanoTime() - startTime) / NS_IN_MS); mMountStats.updatedCount++; } else { mMountStats.noOpCount++; } } applyBindBinders(currentMountItem); } if (isTracing) { ComponentsSystrace.endSection(); } } final boolean wasDirty = mIsDirty; mIsDirty = false; mNeedsRemount = false; clearLastMountedLayoutState(); mLastMountedComponentTreeId = componentTreeId; mLastMountedLayoutState = layoutState; if (mountPerfEvent != null) { logMountPerfEvent(logger, mountPerfEvent, wasDirty); } if (isTracing) { ComponentsSystrace.endSection(); } LithoStats.incrementComponentMountCount(); mIsMounting = false; } private void applyMountBinders(LayoutOutput layoutOutput, MountItem mountItem, int position) { if (mTransitionsExtension != null) { mTransitionsExtension.onMountItem( mTransitionsExtensionState, mountItem.getRenderTreeNode().getRenderUnit(), mountItem.getContent(), mountItem.getRenderTreeNode().getLayoutData()); } else if (mMountDelegate != null) { mMountDelegate.onMountItem( mountItem.getRenderTreeNode().getRenderUnit(), mountItem.getContent(), mountItem.getRenderTreeNode().getLayoutData()); } } private void applyBindBinders(MountItem mountItem) { if (mMountDelegate == null) { return; } } private void applyUnbindBinders(LayoutOutput output, MountItem mountItem) { if (mTransitionsExtension != null) { mTransitionsExtension.onUnbindItem( mTransitionsExtensionState, mountItem.getRenderTreeNode().getRenderUnit(), output, mountItem.getRenderTreeNode().getLayoutData()); } else if (mMountDelegate != null) { mMountDelegate.onUnmountItem( mountItem.getRenderTreeNode().getRenderUnit(), output, mountItem.getContent()); } } private boolean isMountable(RenderTreeNode renderTreeNode, int position) { if (mMountDelegate == null) { return true; } final boolean isLockedForMount = mMountDelegate.maybeLockForMount(renderTreeNode, position); return isLockedForMount; } @Override public void notifyMount(long id) { if (mLayoutState == null) { return; } final int position = mLayoutState.getPositionForId(id); if (position < 0 || getItemAt(position) != null) { return; } final RenderTreeNode node = mLayoutState.getMountableOutputAt(position); mountLayoutOutput(position, node, getLayoutOutput(node), mLayoutState); } @Override public void notifyUnmount(long id) { final MountItem item = mIndexToItemMap.get(id); if (item == null || mLayoutState == null) { return; } final int position = mLayoutState.getPositionForId(id); if (position >= 0) { unmountItem(position, mHostsByMarker); } } private void logMountPerfEvent( ComponentsLogger logger, PerfEvent mountPerfEvent, boolean isDirty) { if (!mMountStats.isLoggingEnabled) { logger.cancelPerfEvent(mountPerfEvent); return; } // MOUNT events that don't mount any content are not valuable enough to log at the moment. // We will likely enable them again in the future. T31729233 if (mMountStats.mountedCount == 0 || mMountStats.mountedNames.isEmpty()) { logger.cancelPerfEvent(mountPerfEvent); return; } mountPerfEvent.markerAnnotate(PARAM_MOUNTED_COUNT, mMountStats.mountedCount); mountPerfEvent.markerAnnotate( PARAM_MOUNTED_CONTENT, mMountStats.mountedNames.toArray(new String[0])); mountPerfEvent.markerAnnotate( PARAM_MOUNTED_TIME, mMountStats.mountTimes.toArray(new Double[0])); mountPerfEvent.markerAnnotate(PARAM_UNMOUNTED_COUNT, mMountStats.unmountedCount); mountPerfEvent.markerAnnotate( PARAM_UNMOUNTED_CONTENT, mMountStats.unmountedNames.toArray(new String[0])); mountPerfEvent.markerAnnotate( PARAM_UNMOUNTED_TIME, mMountStats.unmountedTimes.toArray(new Double[0])); mountPerfEvent.markerAnnotate(PARAM_MOUNTED_EXTRAS, mMountStats.extras.toArray(new String[0])); mountPerfEvent.markerAnnotate(PARAM_UPDATED_COUNT, mMountStats.updatedCount); mountPerfEvent.markerAnnotate( PARAM_UPDATED_CONTENT, mMountStats.updatedNames.toArray(new String[0])); mountPerfEvent.markerAnnotate( PARAM_UPDATED_TIME, mMountStats.updatedTimes.toArray(new Double[0])); mountPerfEvent.markerAnnotate( PARAM_VISIBILITY_HANDLERS_TOTAL_TIME, mMountStats.visibilityHandlersTotalTime); mountPerfEvent.markerAnnotate( PARAM_VISIBILITY_HANDLER, mMountStats.visibilityHandlerNames.toArray(new String[0])); mountPerfEvent.markerAnnotate( PARAM_VISIBILITY_HANDLER_TIME, mMountStats.visibilityHandlerTimes.toArray(new Double[0])); mountPerfEvent.markerAnnotate(PARAM_NO_OP_COUNT, mMountStats.noOpCount); mountPerfEvent.markerAnnotate(PARAM_IS_DIRTY, isDirty); logger.logPerfEvent(mountPerfEvent); } void processVisibilityOutputs( LayoutState layoutState, @Nullable Rect localVisibleRect, Rect previousLocalVisibleRect, boolean isDirty, @Nullable PerfEvent mountPerfEvent) { if (mVisibilityExtension == null) { return; } if (isDirty) { mVisibilityExtension.afterMount(mVisibilityExtensionState); } else { mVisibilityExtension.onVisibleBoundsChanged(mVisibilityExtensionState, localVisibleRect); } } @VisibleForTesting Map<String, VisibilityItem> getVisibilityIdToItemMap() { return VisibilityMountExtension.getVisibilityIdToItemMap(mVisibilityExtensionState); } @VisibleForTesting @Override public ArrayList<Host> getHosts() { final ArrayList<Host> hosts = new ArrayList<>(); for (int i = 0, size = mHostsByMarker.size(); i < size; i++) { hosts.add(mHostsByMarker.valueAt(i)); } return hosts; } @Override public int getMountItemCount() { return mIndexToItemMap.size(); } @Override public int getRenderUnitCount() { assertMainThread(); return mLayoutOutputsIds == null ? 0 : mLayoutOutputsIds.length; } @Override public @Nullable MountItem getMountItemAt(int position) { return getItemAt(position); } @Override public void setUnmountDelegateExtension(UnmountDelegateExtension unmountDelegateExtension) { mUnmountDelegateExtension = unmountDelegateExtension; } @Override public void removeUnmountDelegateExtension() { mUnmountDelegateExtension = null; } @Override public @Nullable ExtensionState getExtensionState(MountExtension mountExtension) { if (mountExtension == mVisibilityExtension) { return mVisibilityExtensionState; } return mMountDelegate.getExtensionState(mountExtension); } /** Clears and re-populates the test item map if we are in e2e test mode. */ private void processTestOutputs(LayoutState layoutState) { if (mTestItemMap == null) { return; } mTestItemMap.clear(); for (int i = 0, size = layoutState.getTestOutputCount(); i < size; i++) { final TestOutput testOutput = layoutState.getTestOutputAt(i); final long hostMarker = testOutput.getHostMarker(); final long layoutOutputId = testOutput.getLayoutOutputId(); final MountItem mountItem = layoutOutputId == -1 ? null : mIndexToItemMap.get(layoutOutputId); final TestItem testItem = new TestItem(); testItem.setHost(hostMarker == -1 ? null : mHostsByMarker.get(hostMarker)); testItem.setBounds(testOutput.getBounds()); testItem.setTestKey(testOutput.getTestKey()); testItem.setContent(mountItem == null ? null : mountItem.getContent()); final Deque<TestItem> items = mTestItemMap.get(testOutput.getTestKey()); final Deque<TestItem> updatedItems = items == null ? new LinkedList<TestItem>() : items; updatedItems.add(testItem); mTestItemMap.put(testOutput.getTestKey(), updatedItems); } } private static boolean isMountedHostWithChildContent(@Nullable MountItem mountItem) { if (mountItem == null) { return false; } final Object content = mountItem.getContent(); if (!(content instanceof ComponentHost)) { return false; } final ComponentHost host = (ComponentHost) content; return host.getMountItemCount() > 0; } private void setupPreviousMountableOutputData(LayoutState layoutState, Rect localVisibleRect) { if (localVisibleRect.isEmpty()) { return; } final ArrayList<IncrementalMountOutput> layoutOutputTops = layoutState.getOutputsOrderedByTopBounds(); final ArrayList<IncrementalMountOutput> layoutOutputBottoms = layoutState.getOutputsOrderedByBottomBounds(); final int mountableOutputCount = layoutState.getMountableOutputCount(); mPreviousTopsIndex = layoutState.getMountableOutputCount(); for (int i = 0; i < mountableOutputCount; i++) { if (localVisibleRect.bottom <= layoutOutputTops.get(i).getBounds().top) { mPreviousTopsIndex = i; break; } } mPreviousBottomsIndex = layoutState.getMountableOutputCount(); for (int i = 0; i < mountableOutputCount; i++) { if (localVisibleRect.top < layoutOutputBottoms.get(i).getBounds().bottom) { mPreviousBottomsIndex = i; break; } } } List<LithoView> getChildLithoViewsFromCurrentlyMountedItems() { final ArrayList<LithoView> childLithoViews = new ArrayList<>(); for (int i = 0; i < mIndexToItemMap.size(); i++) { final long layoutOutputId = mIndexToItemMap.keyAt(i); final MountItem mountItem = mIndexToItemMap.get(layoutOutputId); if (mountItem != null && mountItem.getContent() instanceof HasLithoViewChildren) { ((HasLithoViewChildren) mountItem.getContent()).obtainLithoViewChildren(childLithoViews); } } return childLithoViews; } void clearVisibilityItems() { if (mVisibilityExtension != null) { VisibilityMountExtension.clearVisibilityItems(mVisibilityExtensionState); } } private void registerHost(long id, ComponentHost host) { mHostsByMarker.put(id, host); } private static int computeRectArea(Rect rect) { return rect.isEmpty() ? 0 : (rect.width() * rect.height()); } private boolean updateMountItemIfNeeded( RenderTreeNode node, MountItem currentMountItem, boolean useUpdateValueFromLayoutOutput, int componentTreeId, int index) { final LayoutOutput nextLayoutOutput = getLayoutOutput(node); final Component layoutOutputComponent = nextLayoutOutput.getComponent(); final LayoutOutput currentLayoutOutput = getLayoutOutput(currentMountItem); final Component itemComponent = currentLayoutOutput.getComponent(); final Object currentContent = currentMountItem.getContent(); final ComponentHost host = (ComponentHost) currentMountItem.getHost(); final ComponentContext currentContext = getComponentContext(currentMountItem); final ComponentContext nextContext = getComponentContext(node); final LithoLayoutData nextLayoutData = (LithoLayoutData) node.getLayoutData(); final LithoLayoutData currentLayoutData = (LithoLayoutData) currentMountItem.getRenderTreeNode().getLayoutData(); if (layoutOutputComponent == null) { throw new RuntimeException("Trying to update a MountItem with a null Component."); } // 1. Check if the mount item generated from the old component should be updated. final boolean shouldUpdate = shouldUpdateMountItem( nextLayoutOutput, nextLayoutData, nextContext, currentLayoutOutput, currentLayoutData, currentContext, useUpdateValueFromLayoutOutput); final boolean shouldUpdateViewInfo = shouldUpdate || shouldUpdateViewInfo(nextLayoutOutput, currentLayoutOutput); // 2. Reset all the properties like click handler, content description and tags related to // this item if it needs to be updated. the update mount item will re-set the new ones. if (shouldUpdateViewInfo) { maybeUnsetViewAttributes(currentMountItem); } // 3. We will re-bind this later in 7 regardless so let's make sure it's currently unbound. if (currentMountItem.isBound()) { unbindComponentFromContent(currentMountItem, itemComponent, currentMountItem.getContent()); } // 4. Re initialize the MountItem internal state with the new attributes from LayoutOutput currentMountItem.update(node); // 5. If the mount item is not valid for this component update its content and view attributes. if (shouldUpdate) { updateMountedContent( currentMountItem, layoutOutputComponent, nextContext, nextLayoutData, itemComponent, currentContext, currentLayoutData); } if (shouldUpdateViewInfo) { setViewAttributes(currentMountItem); } // 6. Set the mounted content on the Component and call the bind callback. bindComponentToContent( currentMountItem, layoutOutputComponent, nextContext, nextLayoutData, currentContent); // 7. Update the bounds of the mounted content. This needs to be done regardless of whether // the component has been updated or not since the mounted item might might have the same // size and content but a different position. updateBoundsForMountedLayoutOutput(node, nextLayoutOutput, currentMountItem); if (currentMountItem.getContent() instanceof Drawable) { maybeSetDrawableState( host, (Drawable) currentContent, currentLayoutOutput.getFlags(), currentLayoutOutput.getNodeInfo()); } return shouldUpdate; } static boolean shouldUpdateViewInfo( final LayoutOutput nextLayoutOutput, final LayoutOutput currentLayoutOutput) { final ViewNodeInfo nextViewNodeInfo = nextLayoutOutput.getViewNodeInfo(); final ViewNodeInfo currentViewNodeInfo = currentLayoutOutput.getViewNodeInfo(); if ((currentViewNodeInfo == null && nextViewNodeInfo != null) || (currentViewNodeInfo != null && !currentViewNodeInfo.isEquivalentTo(nextViewNodeInfo))) { return true; } final NodeInfo nextNodeInfo = nextLayoutOutput.getNodeInfo(); final NodeInfo currentNodeInfo = currentLayoutOutput.getNodeInfo(); return (currentNodeInfo == null && nextNodeInfo != null) || (currentNodeInfo != null && !currentNodeInfo.isEquivalentTo(nextNodeInfo)); } static boolean shouldUpdateMountItem( final LayoutOutput nextLayoutOutput, final @Nullable LithoLayoutData nextLayoutData, final @Nullable ComponentContext nextContext, final LayoutOutput currentLayoutOutput, final @Nullable LithoLayoutData currentLayoutData, final @Nullable ComponentContext currentContext, final boolean useUpdateValueFromLayoutOutput) { @LayoutOutput.UpdateState final int updateState = nextLayoutOutput.getUpdateState(); final Component currentComponent = currentLayoutOutput.getComponent(); final Component nextComponent = nextLayoutOutput.getComponent(); // If the two components have different sizes and the mounted content depends on the size we // just return true immediately. if (nextComponent.isMountSizeDependent() && !sameSize( Preconditions.checkNotNull(nextLayoutData), Preconditions.checkNotNull(currentLayoutData))) { return true; } if (useUpdateValueFromLayoutOutput) { if (updateState == LayoutOutput.STATE_UPDATED) { // Check for incompatible ReferenceLifecycle. return currentComponent instanceof DrawableComponent && nextComponent instanceof DrawableComponent && shouldUpdate(currentComponent, currentContext, nextComponent, nextContext); } else if (updateState == LayoutOutput.STATE_DIRTY) { return true; } } return shouldUpdate(currentComponent, currentContext, nextComponent, nextContext); } private static boolean shouldUpdate( Component currentComponent, ComponentContext currentScopedContext, Component nextComponent, ComponentContext nextScopedContext) { try { return currentComponent.shouldComponentUpdate( currentScopedContext, currentComponent, nextScopedContext, nextComponent); } catch (Exception e) { ComponentUtils.handle(nextScopedContext, e); return true; } } static boolean sameSize(final LithoLayoutData next, final LithoLayoutData current) { return next.width == current.width && next.height == current.height; } private static void updateBoundsForMountedLayoutOutput( final RenderTreeNode node, final LayoutOutput layoutOutput, final MountItem item) { // MountState should never update the bounds of the top-level host as this // should be done by the ViewGroup containing the LithoView. if (node.getRenderUnit().getId() == ROOT_HOST_ID) { return; } final Rect bounds = node.getBounds(); final boolean forceTraversal = Component.isMountViewSpec(layoutOutput.getComponent()) && ((View) item.getContent()).isLayoutRequested(); applyBoundsToMountContent( item.getContent(), bounds.left, bounds.top, bounds.right, bounds.bottom, forceTraversal /* force */); } /** Prepare the {@link MountState} to mount a new {@link LayoutState}. */ private void prepareMount(LayoutState layoutState, @Nullable PerfEvent perfEvent) { final boolean isTracing = ComponentsSystrace.isTracing(); if (isTracing) { ComponentsSystrace.beginSection("prepareMount"); } final PrepareMountStats stats = unmountOrMoveOldItems(layoutState); if (perfEvent != null) { perfEvent.markerAnnotate(PARAM_UNMOUNTED_COUNT, stats.unmountedCount); perfEvent.markerAnnotate(PARAM_MOVED_COUNT, stats.movedCount); perfEvent.markerAnnotate(PARAM_UNCHANGED_COUNT, stats.unchangedCount); } if (mIndexToItemMap.get(ROOT_HOST_ID) == null || mHostsByMarker.get(ROOT_HOST_ID) == null) { // Mounting always starts with the root host. registerHost(ROOT_HOST_ID, mLithoView); // Root host is implicitly marked as mounted. mIndexToItemMap.put(ROOT_HOST_ID, mRootHostMountItem); } final int outputCount = layoutState.getMountableOutputCount(); if (mLayoutOutputsIds == null || outputCount != mLayoutOutputsIds.length) { mLayoutOutputsIds = new long[outputCount]; } for (int i = 0; i < outputCount; i++) { mLayoutOutputsIds[i] = layoutState.getMountableOutputAt(i).getRenderUnit().getId(); } if (isTracing) { ComponentsSystrace.endSection(); } } /** * Go over all the mounted items from the leaves to the root and unmount only the items that are * not present in the new LayoutOutputs. If an item is still present but in a new position move * the item inside its host. The condition where an item changed host doesn't need any special * treatment here since we mark them as removed and re-added when calculating the new * LayoutOutputs */ private PrepareMountStats unmountOrMoveOldItems(LayoutState newLayoutState) { mPrepareMountStats.reset(); if (mLayoutOutputsIds == null) { return mPrepareMountStats; } // Traversing from the beginning since mLayoutOutputsIds unmounting won't remove entries there // but only from mIndexToItemMap. If an host changes we're going to unmount it and recursively // all its mounted children. for (int i = 0; i < mLayoutOutputsIds.length; i++) { final int newPosition = newLayoutState.getPositionForId(mLayoutOutputsIds[i]); final @Nullable RenderTreeNode newRenderTreeNode = newPosition != -1 ? newLayoutState.getMountableOutputAt(newPosition) : null; final @Nullable LayoutOutput newLayoutOutput = newRenderTreeNode != null ? getLayoutOutput(newRenderTreeNode) : null; final MountItem oldItem = getItemAt(i); final boolean hasUnmountDelegate = mUnmountDelegateExtension != null && oldItem != null ? mUnmountDelegateExtension.shouldDelegateUnmount( mMountDelegate.getUnmountDelegateExtensionState(), oldItem) : false; if (hasUnmountDelegate) { continue; } if (newPosition == -1) { unmountItem(i, mHostsByMarker); mPrepareMountStats.unmountedCount++; } else { final long newHostMarker = i != 0 ? newRenderTreeNode.getParent().getRenderUnit().getId() : -1; if (oldItem == null) { // This was previously unmounted. mPrepareMountStats.unmountedCount++; } else if (oldItem.getHost() != mHostsByMarker.get(newHostMarker)) { // If the id is the same but the parent host is different we simply unmount the item and // re-mount it later. If the item to unmount is a ComponentHost, all the children will be // recursively unmounted. unmountItem(i, mHostsByMarker); mPrepareMountStats.unmountedCount++; } else if (newPosition != i) { // If a MountItem for this id exists and the hostMarker has not changed but its position // in the outputs array has changed we need to update the position in the Host to ensure // the z-ordering. oldItem.getHost().moveItem(oldItem, i, newPosition); mPrepareMountStats.movedCount++; } else { mPrepareMountStats.unchangedCount++; } } } return mPrepareMountStats; } private void updateMountedContent( final MountItem item, final Component newComponent, final ComponentContext newContext, final LithoLayoutData nextLayoutData, final Component previousComponent, final ComponentContext previousContext, final LithoLayoutData currentLayoutData) { if (isHostSpec(newComponent)) { return; } final Object previousContent = item.getContent(); // Call unmount and mount in sequence to make sure all the the resources are correctly // de-allocated. It's possible for previousContent to equal null - when the root is // interactive we create a LayoutOutput without content in order to set up click handling. previousComponent.unmount( previousContext, previousContent, currentLayoutData.interStagePropsContainer); newComponent.mount(newContext, previousContent, nextLayoutData.interStagePropsContainer); } private void mountLayoutOutput( final int index, final RenderTreeNode node, final LayoutOutput layoutOutput, final LayoutState layoutState) { // 1. Resolve the correct host to mount our content to. final long startTime = System.nanoTime(); // parent should never be null final long hostMarker = node.getParent().getRenderUnit().getId(); ComponentHost host = mHostsByMarker.get(hostMarker); if (host == null) { // Host has not yet been mounted - mount it now. final int hostMountIndex = layoutState.getPositionForId(hostMarker); final RenderTreeNode hostNode = layoutState.getMountableOutputAt(hostMountIndex); final LayoutOutput hostLayoutOutput = getLayoutOutput(hostNode); mountLayoutOutput(hostMountIndex, hostNode, hostLayoutOutput, layoutState); host = mHostsByMarker.get(hostMarker); } // 2. Generate the component's mount state (this might also be a ComponentHost View). final Component component = layoutOutput.getComponent(); if (component == null) { throw new RuntimeException("Trying to mount a LayoutOutput with a null Component."); } final Object content = ComponentsPools.acquireMountContent( mContext.getAndroidContext(), component, mRecyclingMode); final ComponentContext context = getContextForComponent(node); final LithoLayoutData layoutData = (LithoLayoutData) node.getLayoutData(); component.mount(context, content, layoutData.interStagePropsContainer); // 3. If it's a ComponentHost, add the mounted View to the list of Hosts. if (isHostSpec(component)) { ComponentHost componentHost = (ComponentHost) content; registerHost(node.getRenderUnit().getId(), componentHost); } // 4. Mount the content into the selected host. final MountItem item = mountContent(index, component, content, host, node, layoutOutput); // 5. Notify the component that mounting has completed bindComponentToContent(item, component, context, layoutData, content); // 6. Apply the bounds to the Mount content now. It's important to do so after bind as calling // bind might have triggered a layout request within a View. final Rect bounds = node.getBounds(); applyBoundsToMountContent( item.getContent(), bounds.left, bounds.top, bounds.right, bounds.bottom, true /* force */); // 6. Update the mount stats if (mMountStats.isLoggingEnabled) { mMountStats.mountTimes.add((System.nanoTime() - startTime) / NS_IN_MS); mMountStats.mountedNames.add(component.getSimpleName()); mMountStats.mountedCount++; final ComponentContext scopedContext = getComponentContext(node); mMountStats.extras.add( LogTreePopulator.getAnnotationBundleFromLogger(scopedContext, context.getLogger())); } } // The content might be null because it's the LayoutSpec for the root host // (the very first LayoutOutput). private MountItem mountContent( int index, Component component, Object content, ComponentHost host, RenderTreeNode node, LayoutOutput layoutOutput) { final MountItem item = new MountItem(node, host, content); item.setMountData(new LithoMountData(content)); // Create and keep a MountItem even for the layoutSpec with null content // that sets the root host interactions. mIndexToItemMap.put(mLayoutOutputsIds[index], item); if (component.hasChildLithoViews()) { mCanMountIncrementallyMountItems.put(mLayoutOutputsIds[index], item); } mount(host, index, content, item, node); setViewAttributes(item); return item; } private static void mount( final ComponentHost host, final int index, final Object content, final MountItem item, final RenderTreeNode node) { host.mount(index, item, node.getBounds()); } private static void unmount( final ComponentHost host, final int index, final Object content, final MountItem item, final LayoutOutput output) { host.unmount(index, item); } private static void applyBoundsToMountContent( Object content, int left, int top, int right, int bottom, boolean force) { assertMainThread(); BoundsUtils.applyBoundsToMountContent(left, top, right, bottom, null, content, force); } private static void setViewAttributes(MountItem item) { setViewAttributes(item.getContent(), getLayoutOutput(item)); } static void setViewAttributes(Object content, LayoutOutput output) { final Component component = output.getComponent(); if (!isMountViewSpec(component)) { return; } final View view = (View) content; final NodeInfo nodeInfo = output.getNodeInfo(); if (nodeInfo != null) { setClickHandler(nodeInfo.getClickHandler(), view); setLongClickHandler(nodeInfo.getLongClickHandler(), view); setFocusChangeHandler(nodeInfo.getFocusChangeHandler(), view); setTouchHandler(nodeInfo.getTouchHandler(), view); setInterceptTouchHandler(nodeInfo.getInterceptTouchHandler(), view); setAccessibilityDelegate(view, nodeInfo); setViewTag(view, nodeInfo.getViewTag()); setViewTags(view, nodeInfo.getViewTags()); setShadowElevation(view, nodeInfo.getShadowElevation()); setOutlineProvider(view, nodeInfo.getOutlineProvider()); setClipToOutline(view, nodeInfo.getClipToOutline()); setClipChildren(view, nodeInfo); setContentDescription(view, nodeInfo.getContentDescription()); setFocusable(view, nodeInfo.getFocusState()); setClickable(view, nodeInfo.getClickableState()); setEnabled(view, nodeInfo.getEnabledState()); setSelected(view, nodeInfo.getSelectedState()); setScale(view, nodeInfo); setAlpha(view, nodeInfo); setRotation(view, nodeInfo); setRotationX(view, nodeInfo); setRotationY(view, nodeInfo); setTransitionName(view, nodeInfo.getTransitionName()); } setImportantForAccessibility(view, output.getImportantForAccessibility()); final ViewNodeInfo viewNodeInfo = output.getViewNodeInfo(); if (viewNodeInfo != null) { final boolean isHostSpec = isHostSpec(component); setViewLayerType(view, viewNodeInfo); setViewStateListAnimator(view, viewNodeInfo); if (LayoutOutput.areDrawableOutputsDisabled(output.getFlags())) { setViewBackground(view, viewNodeInfo); setViewForeground(view, viewNodeInfo); // when background outputs are disabled, they are wrapped by a ComponentHost. // A background can set the padding of a view, but ComponentHost should not have // any padding because the layout calculation has already accounted for padding by // translating the bounds of its children. if (isHostSpec) { view.setPadding(0, 0, 0, 0); } } if (!isHostSpec) { // Set view background, if applicable. Do this before padding // as it otherwise overrides the padding. setViewBackground(view, viewNodeInfo); setViewPadding(view, viewNodeInfo); setViewForeground(view, viewNodeInfo); setViewLayoutDirection(view, viewNodeInfo); } } } private static void setViewLayerType(final View view, final ViewNodeInfo info) { final int type = info.getLayerType(); if (type != LayerType.LAYER_TYPE_NOT_SET) { view.setLayerType(info.getLayerType(), info.getLayoutPaint()); } } private static void unsetViewLayerType(final View view, final int mountFlags) { int type = LithoMountData.getOriginalLayerType(mountFlags); if (type != LayerType.LAYER_TYPE_NOT_SET) { view.setLayerType(type, null); } } private static void maybeUnsetViewAttributes(MountItem item) { final LayoutOutput output = getLayoutOutput(item); final int flags = getMountData(item).getDefaultAttributeValuesFlags(); unsetViewAttributes(item.getContent(), output, flags); } static void unsetViewAttributes( final Object content, final LayoutOutput output, final int mountFlags) { final Component component = output.getComponent(); final boolean isHostView = isHostSpec(component); if (!isMountViewSpec(component)) { return; } final View view = (View) content; final NodeInfo nodeInfo = output.getNodeInfo(); if (nodeInfo != null) { if (nodeInfo.getClickHandler() != null) { unsetClickHandler(view); } if (nodeInfo.getLongClickHandler() != null) { unsetLongClickHandler(view); } if (nodeInfo.getFocusChangeHandler() != null) { unsetFocusChangeHandler(view); } if (nodeInfo.getTouchHandler() != null) { unsetTouchHandler(view); } if (nodeInfo.getInterceptTouchHandler() != null) { unsetInterceptTouchEventHandler(view); } unsetViewTag(view); unsetViewTags(view, nodeInfo.getViewTags()); unsetShadowElevation(view, nodeInfo.getShadowElevation()); unsetOutlineProvider(view, nodeInfo.getOutlineProvider()); unsetClipToOutline(view, nodeInfo.getClipToOutline()); unsetClipChildren(view, nodeInfo.getClipChildren()); if (!TextUtils.isEmpty(nodeInfo.getContentDescription())) { unsetContentDescription(view); } unsetScale(view, nodeInfo); unsetAlpha(view, nodeInfo); unsetRotation(view, nodeInfo); unsetRotationX(view, nodeInfo); unsetRotationY(view, nodeInfo); } view.setClickable(isViewClickable(mountFlags)); view.setLongClickable(isViewLongClickable(mountFlags)); unsetFocusable(view, mountFlags); unsetEnabled(view, mountFlags); unsetSelected(view, mountFlags); if (output.getImportantForAccessibility() != IMPORTANT_FOR_ACCESSIBILITY_AUTO) { unsetImportantForAccessibility(view); } unsetAccessibilityDelegate(view); final ViewNodeInfo viewNodeInfo = output.getViewNodeInfo(); if (viewNodeInfo != null) { unsetViewStateListAnimator(view, viewNodeInfo); // Host view doesn't set its own padding, but gets absolute positions for inner content from // Yoga. Also bg/fg is used as separate drawables instead of using View's bg/fg attribute. if (LayoutOutput.areDrawableOutputsDisabled(output.getFlags())) { unsetViewBackground(view, viewNodeInfo); unsetViewForeground(view, viewNodeInfo); } if (!isHostView) { unsetViewPadding(view, output, viewNodeInfo); unsetViewBackground(view, viewNodeInfo); unsetViewForeground(view, viewNodeInfo); unsetViewLayoutDirection(view); } } unsetViewLayerType(view, mountFlags); } /** * Store a {@link NodeInfo} as a tag in {@code view}. {@link LithoView} contains the logic for * setting/unsetting it whenever accessibility is enabled/disabled * * <p>For non {@link ComponentHost}s this is only done if any {@link EventHandler}s for * accessibility events have been implemented, we want to preserve the original behaviour since * {@code view} might have had a default delegate. */ private static void setAccessibilityDelegate(View view, NodeInfo nodeInfo) { if (!(view instanceof ComponentHost) && !nodeInfo.needsAccessibilityDelegate()) { return; } view.setTag(R.id.component_node_info, nodeInfo); } private static void unsetAccessibilityDelegate(View view) { if (!(view instanceof ComponentHost) && view.getTag(R.id.component_node_info) == null) { return; } view.setTag(R.id.component_node_info, null); if (!(view instanceof ComponentHost)) { ViewCompat.setAccessibilityDelegate(view, null); } } /** * Installs the click listeners that will dispatch the click handler defined in the component's * props. Unconditionally set the clickable flag on the view. */ private static void setClickHandler(@Nullable EventHandler<ClickEvent> clickHandler, View view) { if (clickHandler == null) { return; } ComponentClickListener listener = getComponentClickListener(view); if (listener == null) { listener = new ComponentClickListener(); setComponentClickListener(view, listener); } listener.setEventHandler(clickHandler); view.setClickable(true); } private static void unsetClickHandler(View view) { final ComponentClickListener listener = getComponentClickListener(view); if (listener != null) { listener.setEventHandler(null); } } @Nullable static ComponentClickListener getComponentClickListener(View v) { if (v instanceof ComponentHost) { return ((ComponentHost) v).getComponentClickListener(); } else { return (ComponentClickListener) v.getTag(R.id.component_click_listener); } } static void setComponentClickListener(View v, ComponentClickListener listener) { if (v instanceof ComponentHost) { ((ComponentHost) v).setComponentClickListener(listener); } else { v.setOnClickListener(listener); v.setTag(R.id.component_click_listener, listener); } } /** * Installs the long click listeners that will dispatch the click handler defined in the * component's props. Unconditionally set the clickable flag on the view. */ private static void setLongClickHandler( @Nullable EventHandler<LongClickEvent> longClickHandler, View view) { if (longClickHandler != null) { ComponentLongClickListener listener = getComponentLongClickListener(view); if (listener == null) { listener = new ComponentLongClickListener(); setComponentLongClickListener(view, listener); } listener.setEventHandler(longClickHandler); view.setLongClickable(true); } } private static void unsetLongClickHandler(View view) { final ComponentLongClickListener listener = getComponentLongClickListener(view); if (listener != null) { listener.setEventHandler(null); } } @Nullable static ComponentLongClickListener getComponentLongClickListener(View v) { if (v instanceof ComponentHost) { return ((ComponentHost) v).getComponentLongClickListener(); } else { return (ComponentLongClickListener) v.getTag(R.id.component_long_click_listener); } } static void setComponentLongClickListener(View v, ComponentLongClickListener listener) { if (v instanceof ComponentHost) { ((ComponentHost) v).setComponentLongClickListener(listener); } else { v.setOnLongClickListener(listener); v.setTag(R.id.component_long_click_listener, listener); } } /** * Installs the on focus change listeners that will dispatch the click handler defined in the * component's props. Unconditionally set the clickable flag on the view. */ private static void setFocusChangeHandler( @Nullable EventHandler<FocusChangedEvent> focusChangeHandler, View view) { if (focusChangeHandler == null) { return; } ComponentFocusChangeListener listener = getComponentFocusChangeListener(view); if (listener == null) { listener = new ComponentFocusChangeListener(); setComponentFocusChangeListener(view, listener); } listener.setEventHandler(focusChangeHandler); } private static void unsetFocusChangeHandler(View view) { final ComponentFocusChangeListener listener = getComponentFocusChangeListener(view); if (listener != null) { listener.setEventHandler(null); } } static ComponentFocusChangeListener getComponentFocusChangeListener(View v) { if (v instanceof ComponentHost) { return ((ComponentHost) v).getComponentFocusChangeListener(); } else { return (ComponentFocusChangeListener) v.getTag(R.id.component_focus_change_listener); } } static void setComponentFocusChangeListener(View v, ComponentFocusChangeListener listener) { if (v instanceof ComponentHost) { ((ComponentHost) v).setComponentFocusChangeListener(listener); } else { v.setOnFocusChangeListener(listener); v.setTag(R.id.component_focus_change_listener, listener); } } /** * Installs the touch listeners that will dispatch the touch handler defined in the component's * props. */ private static void setTouchHandler(@Nullable EventHandler<TouchEvent> touchHandler, View view) { if (touchHandler != null) { ComponentTouchListener listener = getComponentTouchListener(view); if (listener == null) { listener = new ComponentTouchListener(); setComponentTouchListener(view, listener); } listener.setEventHandler(touchHandler); } } private static void unsetTouchHandler(View view) { final ComponentTouchListener listener = getComponentTouchListener(view); if (listener != null) { listener.setEventHandler(null); } } /** Sets the intercept touch handler defined in the component's props. */ private static void setInterceptTouchHandler( @Nullable EventHandler<InterceptTouchEvent> interceptTouchHandler, View view) { if (interceptTouchHandler == null) { return; } if (view instanceof ComponentHost) { ((ComponentHost) view).setInterceptTouchEventHandler(interceptTouchHandler); } } private static void unsetInterceptTouchEventHandler(View view) { if (view instanceof ComponentHost) { ((ComponentHost) view).setInterceptTouchEventHandler(null); } } @Nullable static ComponentTouchListener getComponentTouchListener(View v) { if (v instanceof ComponentHost) { return ((ComponentHost) v).getComponentTouchListener(); } else { return (ComponentTouchListener) v.getTag(R.id.component_touch_listener); } } static void setComponentTouchListener(View v, ComponentTouchListener listener) { if (v instanceof ComponentHost) { ((ComponentHost) v).setComponentTouchListener(listener); } else { v.setOnTouchListener(listener); v.setTag(R.id.component_touch_listener, listener); } } private static void setViewTag(View view, @Nullable Object viewTag) { view.setTag(viewTag); } private static void setViewTags(View view, @Nullable SparseArray<Object> viewTags) { if (viewTags == null) { return; } if (view instanceof ComponentHost) { final ComponentHost host = (ComponentHost) view; host.setViewTags(viewTags); } else { for (int i = 0, size = viewTags.size(); i < size; i++) { view.setTag(viewTags.keyAt(i), viewTags.valueAt(i)); } } } private static void unsetViewTag(View view) { view.setTag(null); } private static void unsetViewTags(View view, @Nullable SparseArray<Object> viewTags) { if (view instanceof ComponentHost) { final ComponentHost host = (ComponentHost) view; host.setViewTags(null); } else { if (viewTags != null) { for (int i = 0, size = viewTags.size(); i < size; i++) { view.setTag(viewTags.keyAt(i), null); } } } } private static void setShadowElevation(View view, float shadowElevation) { if (shadowElevation != 0) { ViewCompat.setElevation(view, shadowElevation); } } private static void unsetShadowElevation(View view, float shadowElevation) { if (shadowElevation != 0) { ViewCompat.setElevation(view, 0); } } private static void setOutlineProvider(View view, @Nullable ViewOutlineProvider outlineProvider) { if (outlineProvider != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { view.setOutlineProvider(outlineProvider); } } private static void unsetOutlineProvider( View view, @Nullable ViewOutlineProvider outlineProvider) { if (outlineProvider != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { view.setOutlineProvider(ViewOutlineProvider.BACKGROUND); } } private static void setClipToOutline(View view, boolean clipToOutline) { if (clipToOutline && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { view.setClipToOutline(clipToOutline); } } private static void unsetClipToOutline(View view, boolean clipToOutline) { if (clipToOutline && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { view.setClipToOutline(false); } } private static void setClipChildren(View view, NodeInfo nodeInfo) { if (nodeInfo.isClipChildrenSet() && view instanceof ViewGroup) { ((ViewGroup) view).setClipChildren(nodeInfo.getClipChildren()); } } private static void unsetClipChildren(View view, boolean clipChildren) { if (!clipChildren && view instanceof ViewGroup) { // Default value for clipChildren is 'true'. // If this ViewGroup had clipChildren set to 'false' before mounting we would reset this // property here on recycling. ((ViewGroup) view).setClipChildren(true); } } private static void setContentDescription(View view, @Nullable CharSequence contentDescription) { if (TextUtils.isEmpty(contentDescription)) { return; } view.setContentDescription(contentDescription); } private static void unsetContentDescription(View view) { view.setContentDescription(null); } private static void setImportantForAccessibility(View view, int importantForAccessibility) { if (importantForAccessibility == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { return; } ViewCompat.setImportantForAccessibility(view, importantForAccessibility); } private static void unsetImportantForAccessibility(View view) { ViewCompat.setImportantForAccessibility(view, IMPORTANT_FOR_ACCESSIBILITY_AUTO); } private static void setFocusable(View view, @NodeInfo.FocusState int focusState) { if (focusState == NodeInfo.FOCUS_SET_TRUE) { view.setFocusable(true); } else if (focusState == NodeInfo.FOCUS_SET_FALSE) { view.setFocusable(false); } } private static void unsetFocusable(View view, int flags) { view.setFocusable(isViewFocusable(flags)); } private static void setTransitionName(View view, @Nullable String transitionName) { ViewCompat.setTransitionName(view, transitionName); } private static void setClickable(View view, @NodeInfo.FocusState int clickableState) { if (clickableState == NodeInfo.CLICKABLE_SET_TRUE) { view.setClickable(true); } else if (clickableState == NodeInfo.CLICKABLE_SET_FALSE) { view.setClickable(false); } } private static void setEnabled(View view, @NodeInfo.EnabledState int enabledState) { if (enabledState == NodeInfo.ENABLED_SET_TRUE) { view.setEnabled(true); } else if (enabledState == NodeInfo.ENABLED_SET_FALSE) { view.setEnabled(false); } } private static void unsetEnabled(View view, int flags) { view.setEnabled(isViewEnabled(flags)); } private static void setSelected(View view, @NodeInfo.SelectedState int selectedState) { if (selectedState == NodeInfo.SELECTED_SET_TRUE) { view.setSelected(true); } else if (selectedState == NodeInfo.SELECTED_SET_FALSE) { view.setSelected(false); } } private static void unsetSelected(View view, int flags) { view.setSelected(isViewSelected(flags)); } private static void setScale(View view, NodeInfo nodeInfo) { if (nodeInfo.isScaleSet()) { final float scale = nodeInfo.getScale(); view.setScaleX(scale); view.setScaleY(scale); } } private static void unsetScale(View view, NodeInfo nodeInfo) { if (nodeInfo.isScaleSet()) { if (view.getScaleX() != 1) { view.setScaleX(1); } if (view.getScaleY() != 1) { view.setScaleY(1); } } } private static void setAlpha(View view, NodeInfo nodeInfo) { if (nodeInfo.isAlphaSet()) { view.setAlpha(nodeInfo.getAlpha()); } } private static void unsetAlpha(View view, NodeInfo nodeInfo) { if (nodeInfo.isAlphaSet() && view.getAlpha() != 1) { view.setAlpha(1); } } private static void setRotation(View view, NodeInfo nodeInfo) { if (nodeInfo.isRotationSet()) { view.setRotation(nodeInfo.getRotation()); } } private static void unsetRotation(View view, NodeInfo nodeInfo) { if (nodeInfo.isRotationSet() && view.getRotation() != 0) { view.setRotation(0); } } private static void setRotationX(View view, NodeInfo nodeInfo) { if (nodeInfo.isRotationXSet()) { view.setRotationX(nodeInfo.getRotationX()); } } private static void unsetRotationX(View view, NodeInfo nodeInfo) { if (nodeInfo.isRotationXSet() && view.getRotationX() != 0) { view.setRotationX(0); } } private static void setRotationY(View view, NodeInfo nodeInfo) { if (nodeInfo.isRotationYSet()) { view.setRotationY(nodeInfo.getRotationY()); } } private static void unsetRotationY(View view, NodeInfo nodeInfo) { if (nodeInfo.isRotationYSet() && view.getRotationY() != 0) { view.setRotationY(0); } } private static void setViewPadding(View view, ViewNodeInfo viewNodeInfo) { if (!viewNodeInfo.hasPadding()) { return; } view.setPadding( viewNodeInfo.getPaddingLeft(), viewNodeInfo.getPaddingTop(), viewNodeInfo.getPaddingRight(), viewNodeInfo.getPaddingBottom()); } private static void unsetViewPadding(View view, LayoutOutput output, ViewNodeInfo viewNodeInfo) { if (!viewNodeInfo.hasPadding()) { return; } try { view.setPadding(0, 0, 0, 0); } catch (NullPointerException e) { // T53931759 Gathering extra info around this NPE ErrorReporter.getInstance() .report( LogLevel.ERROR, "LITHO:NPE:UNSET_PADDING", "From component: " + output.getComponent().getSimpleName(), e, 0, null); } } private static void setViewBackground(View view, ViewNodeInfo viewNodeInfo) { final Drawable background = viewNodeInfo.getBackground(); if (background != null) { setBackgroundCompat(view, background); } } private static void unsetViewBackground(View view, ViewNodeInfo viewNodeInfo) { final Drawable background = viewNodeInfo.getBackground(); if (background != null) { setBackgroundCompat(view, null); } } @SuppressWarnings("deprecation") private static void setBackgroundCompat(View view, Drawable drawable) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { view.setBackgroundDrawable(drawable); } else { view.setBackground(drawable); } } private static void setViewForeground(View view, ViewNodeInfo viewNodeInfo) { final Drawable foreground = viewNodeInfo.getForeground(); if (foreground != null) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { throw new IllegalStateException( "MountState has a ViewNodeInfo with foreground however " + "the current Android version doesn't support foreground on Views"); } view.setForeground(foreground); } } private static void unsetViewForeground(View view, ViewNodeInfo viewNodeInfo) { final Drawable foreground = viewNodeInfo.getForeground(); if (foreground != null) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { throw new IllegalStateException( "MountState has a ViewNodeInfo with foreground however " + "the current Android version doesn't support foreground on Views"); } view.setForeground(null); } } private static void setViewLayoutDirection(View view, ViewNodeInfo viewNodeInfo) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { return; } final int viewLayoutDirection; switch (viewNodeInfo.getLayoutDirection()) { case LTR: viewLayoutDirection = View.LAYOUT_DIRECTION_LTR; break; case RTL: viewLayoutDirection = View.LAYOUT_DIRECTION_RTL; break; default: viewLayoutDirection = View.LAYOUT_DIRECTION_INHERIT; } view.setLayoutDirection(viewLayoutDirection); } private static void unsetViewLayoutDirection(View view) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { return; } view.setLayoutDirection(View.LAYOUT_DIRECTION_INHERIT); } private static void setViewStateListAnimator(View view, ViewNodeInfo viewNodeInfo) { StateListAnimator stateListAnimator = viewNodeInfo.getStateListAnimator(); final int stateListAnimatorRes = viewNodeInfo.getStateListAnimatorRes(); if (stateListAnimator == null && stateListAnimatorRes == 0) { return; } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { throw new IllegalStateException( "MountState has a ViewNodeInfo with stateListAnimator, " + "however the current Android version doesn't support stateListAnimator on Views"); } if (stateListAnimator == null) { stateListAnimator = AnimatorInflater.loadStateListAnimator(view.getContext(), stateListAnimatorRes); } view.setStateListAnimator(stateListAnimator); } private static void unsetViewStateListAnimator(View view, ViewNodeInfo viewNodeInfo) { if (viewNodeInfo.getStateListAnimator() == null && viewNodeInfo.getStateListAnimatorRes() == 0) { return; } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { throw new IllegalStateException( "MountState has a ViewNodeInfo with stateListAnimator, " + "however the current Android version doesn't support stateListAnimator on Views"); } view.setStateListAnimator(null); } private static void mountItemIncrementally(MountItem item, boolean processVisibilityOutputs) { final Component component = getLayoutOutput(item).getComponent(); if (!isMountViewSpec(component)) { return; } // We can't just use the bounds of the View since we need the bounds relative to the // hosting LithoView (which is what the localVisibleRect is measured relative to). final View view = (View) item.getContent(); mountViewIncrementally(view, processVisibilityOutputs); } private static void mountViewIncrementally(View view, boolean processVisibilityOutputs) { assertMainThread(); if (view instanceof LithoView) { final LithoView lithoView = (LithoView) view; if (lithoView.isIncrementalMountEnabled()) { if (!processVisibilityOutputs) { lithoView.notifyVisibleBoundsChanged( new Rect(0, 0, view.getWidth(), view.getHeight()), false); } else { lithoView.notifyVisibleBoundsChanged(); } } } else if (view instanceof RenderCoreExtensionHost) { ((RenderCoreExtensionHost) view).notifyVisibleBoundsChanged(); } else if (view instanceof ViewGroup) { final ViewGroup viewGroup = (ViewGroup) view; for (int i = 0; i < viewGroup.getChildCount(); i++) { final View childView = viewGroup.getChildAt(i); mountViewIncrementally(childView, processVisibilityOutputs); } } } private String getMountItemDebugMessage(MountItem item) { final int index = mIndexToItemMap.indexOfValue(item); long id = -1; int layoutOutputIndex = -1; if (index > -1) { id = mIndexToItemMap.keyAt(index); for (int i = 0; i < mLayoutOutputsIds.length; i++) { if (id == mLayoutOutputsIds[i]) { layoutOutputIndex = i; break; } } } final ComponentTree componentTree = mLithoView.getComponentTree(); final String rootComponent = componentTree == null ? "<null_component_tree>" : componentTree.getRoot().getSimpleName(); return "rootComponent=" + rootComponent + ", index=" + layoutOutputIndex + ", mapIndex=" + index + ", id=" + id + ", disappearRange=[" + mLastDisappearRangeStart + "," + mLastDisappearRangeEnd + "], contentType=" + (item.getContent() != null ? item.getContent().getClass() : "<null_content>") + ", component=" + getLayoutOutput(item).getComponent().getSimpleName() + ", host=" + (item.getHost() != null ? item.getHost().getClass() : "<null_host>") + ", isRootHost=" + (mHostsByMarker.get(ROOT_HOST_ID) == item.getHost()); } @Override public void unmountAllItems() { assertMainThread(); if (mLayoutOutputsIds == null) { return; } for (int i = mLayoutOutputsIds.length - 1; i >= 0; i--) { unmountItem(i, mHostsByMarker); } mPreviousLocalVisibleRect.setEmpty(); mNeedsRemount = true; if (mMountDelegate != null) { mMountDelegate.releaseAllAcquiredReferences(); } if (mVisibilityExtension != null) { mVisibilityExtension.onUnmount(mVisibilityExtensionState); } if (mTransitionsExtension != null) { mTransitionsExtension.onUnmount(mTransitionsExtensionState); } clearLastMountedTree(); clearVisibilityItems(); } private void unmountItem(int index, LongSparseArray<ComponentHost> hostsByMarker) { final MountItem item = getItemAt(index); final long startTime = System.nanoTime(); // Already has been unmounted. if (item == null) { return; } // The root host item should never be unmounted as it's a reference // to the top-level LithoView. if (mLayoutOutputsIds[index] == ROOT_HOST_ID) { maybeUnsetViewAttributes(item); return; } final long layoutOutputId = mLayoutOutputsIds[index]; mIndexToItemMap.remove(layoutOutputId); final Object content = item.getContent(); final boolean hasUnmountDelegate = mUnmountDelegateExtension != null && mUnmountDelegateExtension.shouldDelegateUnmount( mMountDelegate.getUnmountDelegateExtensionState(), item); // Recursively unmount mounted children items. // This is the case when mountDiffing is enabled and unmountOrMoveOldItems() has a matching // sub tree. However, traversing the tree bottom-up, it needs to unmount a node holding that // sub tree, that will still have mounted items. (Different sequence number on LayoutOutput id) if ((content instanceof ComponentHost) && !(content instanceof LithoView)) { final ComponentHost host = (ComponentHost) content; // Concurrently remove items therefore traverse backwards. for (int i = host.getMountItemCount() - 1; i >= 0; i--) { final MountItem mountItem = host.getMountItemAt(i); if (mIndexToItemMap.indexOfValue(mountItem) == -1) { final LayoutOutput output = getLayoutOutput(mountItem); final Component component = output.getComponent(); ComponentsReporter.emitMessage( ComponentsReporter.LogLevel.ERROR, "UnmountItem:ChildNotFound", "Child of mount item not found in MountSate mIndexToItemMap" + ", child_component: " + component.getSimpleName()); } final long childLayoutOutputId = mIndexToItemMap.keyAt(mIndexToItemMap.indexOfValue(mountItem)); for (int mountIndex = mLayoutOutputsIds.length - 1; mountIndex >= 0; mountIndex--) { if (mLayoutOutputsIds[mountIndex] == childLayoutOutputId) { unmountItem(mountIndex, hostsByMarker); break; } } } if (!hasUnmountDelegate && host.getMountItemCount() > 0) { final LayoutOutput output = getLayoutOutput(item); final Component component = output.getComponent(); ComponentsReporter.emitMessage( ComponentsReporter.LogLevel.ERROR, "UnmountItem:ChildsNotUnmounted", "Recursively unmounting items from a ComponentHost, left some items behind maybe because not tracked by its MountState" + ", component: " + component.getSimpleName()); throw new IllegalStateException( "Recursively unmounting items from a ComponentHost, left" + " some items behind maybe because not tracked by its MountState"); } } final ComponentHost host = (ComponentHost) item.getHost(); final LayoutOutput output = getLayoutOutput(item); final Component component = output.getComponent(); if (component.hasChildLithoViews()) { mCanMountIncrementallyMountItems.delete(mLayoutOutputsIds[index]); } if (isHostSpec(component)) { final ComponentHost componentHost = (ComponentHost) content; hostsByMarker.removeAt(hostsByMarker.indexOfValue(componentHost)); } if (hasUnmountDelegate) { mUnmountDelegateExtension.unmount( mMountDelegate.getUnmountDelegateExtensionState(), item, host); } else { /* * The mounted content might contain other LithoViews which are not reachable from * this MountState. If that content contains other LithoViews, we need to unmount them as well, * so that their contents are recycled and reused next time. */ if (content instanceof HasLithoViewChildren) { final ArrayList<LithoView> lithoViews = new ArrayList<>(); ((HasLithoViewChildren) content).obtainLithoViewChildren(lithoViews); for (int i = lithoViews.size() - 1; i >= 0; i--) { final LithoView lithoView = lithoViews.get(i); lithoView.unmountAllItems(); } } unmount(host, index, content, item, output); unbindMountItem(item); } if (mMountStats.isLoggingEnabled) { mMountStats.unmountedTimes.add((System.nanoTime() - startTime) / NS_IN_MS); mMountStats.unmountedNames.add(component.getSimpleName()); mMountStats.unmountedCount++; } } @Override public void unbindMountItem(MountItem mountItem) { final LayoutOutput output = getLayoutOutput(mountItem); maybeUnsetViewAttributes(mountItem); unbindAndUnmountLifecycle(mountItem); applyUnbindBinders(output, mountItem); try { getMountData(mountItem) .releaseMountContent( mContext.getAndroidContext(), mountItem, "unmountItem", mRecyclingMode); } catch (LithoMountData.ReleasingReleasedMountContentException e) { throw new RuntimeException(e.getMessage() + " " + getMountItemDebugMessage(mountItem)); } } private void unbindAndUnmountLifecycle(MountItem item) { final LayoutOutput layoutOutput = getLayoutOutput(item); final Component component = layoutOutput.getComponent(); final Object content = item.getContent(); final ComponentContext context = getContextForComponent(item.getRenderTreeNode()); // Call the component's unmount() method. if (item.isBound()) { unbindComponentFromContent(item, component, content); } if (mRecyclingMode != ComponentTree.RecyclingMode.NO_UNMOUNTING) { final LithoLayoutData layoutData = (LithoLayoutData) item.getRenderTreeNode().getLayoutData(); component.unmount(context, content, layoutData.interStagePropsContainer); } } @Override public boolean isRootItem(int position) { final MountItem mountItem = getItemAt(position); if (mountItem == null) { return false; } return mountItem == mIndexToItemMap.get(ROOT_HOST_ID); } @Override public @Nullable MountItem getRootItem() { return mIndexToItemMap != null ? mIndexToItemMap.get(ROOT_HOST_ID) : null; } @Nullable MountItem getItemAt(int i) { assertMainThread(); // TODO simplify when replacing with getContent. if (mIndexToItemMap == null || mLayoutOutputsIds == null) { return null; } if (i >= mLayoutOutputsIds.length) { return null; } return mIndexToItemMap.get(mLayoutOutputsIds[i]); } @Override public Object getContentAt(int i) { final MountItem mountItem = getItemAt(i); if (mountItem == null) { return null; } return mountItem.getContent(); } @Nullable @Override public Object getContentById(long id) { if (mIndexToItemMap == null) { return null; } final MountItem mountItem = mIndexToItemMap.get(id); if (mountItem == null) { return null; } return mountItem.getContent(); } public androidx.collection.LongSparseArray<MountItem> getIndexToItemMap() { return mIndexToItemMap; } public void clearLastMountedTree() { if (mTransitionsExtension != null) { mTransitionsExtension.clearLastMountedTreeId(mTransitionsExtensionState); } mLastMountedComponentTreeId = ComponentTree.INVALID_ID; } private static class PrepareMountStats { private int unmountedCount = 0; private int movedCount = 0; private int unchangedCount = 0; private PrepareMountStats() {} private void reset() { unchangedCount = 0; movedCount = 0; unmountedCount = 0; } } private static class MountStats { private List<String> mountedNames; private List<String> unmountedNames; private List<String> updatedNames; private List<String> visibilityHandlerNames; private List<String> extras; private List<Double> mountTimes; private List<Double> unmountedTimes; private List<Double> updatedTimes; private List<Double> visibilityHandlerTimes; private int mountedCount; private int unmountedCount; private int updatedCount; private int noOpCount; private double visibilityHandlersTotalTime; private boolean isLoggingEnabled; private boolean isInitialized; private void enableLogging() { isLoggingEnabled = true; if (!isInitialized) { isInitialized = true; mountedNames = new ArrayList<>(); unmountedNames = new ArrayList<>(); updatedNames = new ArrayList<>(); visibilityHandlerNames = new ArrayList<>(); extras = new ArrayList<>(); mountTimes = new ArrayList<>(); unmountedTimes = new ArrayList<>(); updatedTimes = new ArrayList<>(); visibilityHandlerTimes = new ArrayList<>(); } } private void reset() { mountedCount = 0; unmountedCount = 0; updatedCount = 0; noOpCount = 0; visibilityHandlersTotalTime = 0; if (isInitialized) { mountedNames.clear(); unmountedNames.clear(); updatedNames.clear(); visibilityHandlerNames.clear(); extras.clear(); mountTimes.clear(); unmountedTimes.clear(); updatedTimes.clear(); visibilityHandlerTimes.clear(); } isLoggingEnabled = false; } } /** * Unbinds all the MountItems currently mounted on this MountState. Unbinding a MountItem means * calling unbind on its {@link Component}. The MountItem is not yet unmounted after unbind is * called and can be re-used in place to re-mount another {@link Component} with the same {@link * Component}. */ void unbind() { assertMainThread(); if (mLayoutOutputsIds == null) { return; } boolean isTracing = ComponentsSystrace.isTracing(); if (isTracing) { ComponentsSystrace.beginSection("MountState.unbind"); } for (int i = 0, size = mLayoutOutputsIds.length; i < size; i++) { MountItem mountItem = getItemAt(i); if (mountItem == null || !mountItem.isBound()) { continue; } unbindComponentFromContent( mountItem, getLayoutOutput(mountItem).getComponent(), mountItem.getContent()); } clearVisibilityItems(); if (mVisibilityExtension != null) { mVisibilityExtension.onUnbind(mVisibilityExtensionState); } if (mTransitionsExtension != null) { mTransitionsExtension.onUnbind(mTransitionsExtensionState); } if (isTracing) { ComponentsSystrace.endSection(); } } @Override public void detach() { assertMainThread(); unbind(); } @Override public void attach() { rebind(); } /** * This is called when the {@link MountItem}s mounted on this {@link MountState} need to be * re-bound with the same component. The common case here is a detach/attach happens on the {@link * LithoView} that owns the MountState. */ void rebind() { assertMainThread(); if (mLayoutOutputsIds == null) { return; } for (int i = 0, size = mLayoutOutputsIds.length; i < size; i++) { final MountItem mountItem = getItemAt(i); if (mountItem == null || mountItem.isBound()) { continue; } final Component component = getLayoutOutput(mountItem).getComponent(); final Object content = mountItem.getContent(); final LithoLayoutData layoutData = (LithoLayoutData) mountItem.getRenderTreeNode().getLayoutData(); bindComponentToContent( mountItem, component, getComponentContext(mountItem), layoutData, content); if (content instanceof View && !(content instanceof ComponentHost) && ((View) content).isLayoutRequested()) { final View view = (View) content; applyBoundsToMountContent( view, view.getLeft(), view.getTop(), view.getRight(), view.getBottom(), true); } } } private boolean isAnimationLocked(RenderTreeNode renderTreeNode) { if (mTransitionsExtension != null) { if (mTransitionsExtensionState == null) { throw new IllegalStateException("Need a state when using the TransitionsExtension."); } return mTransitionsExtensionState.ownsReference(renderTreeNode.getRenderUnit().getId()); } return false; } /** * @return true if this method did all the work that was necessary and there is no other content * that needs mounting/unmounting in this mount step. If false then a full mount step should * take place. */ private boolean performIncrementalMount( LayoutState layoutState, Rect localVisibleRect, boolean processVisibilityOutputs) { if (mPreviousLocalVisibleRect.isEmpty()) { return false; } if (localVisibleRect.left != mPreviousLocalVisibleRect.left || localVisibleRect.right != mPreviousLocalVisibleRect.right) { return false; } final ArrayList<IncrementalMountOutput> layoutOutputTops = layoutState.getOutputsOrderedByTopBounds(); final ArrayList<IncrementalMountOutput> layoutOutputBottoms = layoutState.getOutputsOrderedByBottomBounds(); final int count = layoutState.getMountableOutputCount(); if (localVisibleRect.top >= 0 || mPreviousLocalVisibleRect.top >= 0) { // View is going on/off the top of the screen. Check the bottoms to see if there is anything // that has moved on/off the top of the screen. while (mPreviousBottomsIndex < count && localVisibleRect.top >= layoutOutputBottoms.get(mPreviousBottomsIndex).getBounds().bottom) { final RenderTreeNode node = layoutState.getRenderTreeNode(layoutOutputBottoms.get(mPreviousBottomsIndex)); final long id = node.getRenderUnit().getId(); final int layoutOutputIndex = layoutState.getPositionForId(id); if (!isAnimationLocked(node)) { unmountItem(layoutOutputIndex, mHostsByMarker); } mPreviousBottomsIndex++; } while (mPreviousBottomsIndex > 0 && localVisibleRect.top <= layoutOutputBottoms.get(mPreviousBottomsIndex - 1).getBounds().bottom) { mPreviousBottomsIndex--; final RenderTreeNode node = layoutState.getRenderTreeNode(layoutOutputBottoms.get(mPreviousBottomsIndex)); final LayoutOutput layoutOutput = getLayoutOutput(node); final int layoutOutputIndex = layoutState.getPositionForId(node.getRenderUnit().getId()); if (getItemAt(layoutOutputIndex) == null) { mountLayoutOutput( layoutState.getPositionForId(node.getRenderUnit().getId()), node, layoutOutput, layoutState); mComponentIdsMountedInThisFrame.add(node.getRenderUnit().getId()); } } } final int height = mLithoView.getHeight(); if (localVisibleRect.bottom < height || mPreviousLocalVisibleRect.bottom < height) { // View is going on/off the bottom of the screen. Check the tops to see if there is anything // that has changed. while (mPreviousTopsIndex < count && localVisibleRect.bottom >= layoutOutputTops.get(mPreviousTopsIndex).getBounds().top) { final RenderTreeNode node = layoutState.getRenderTreeNode(layoutOutputTops.get(mPreviousTopsIndex)); final LayoutOutput layoutOutput = getLayoutOutput(node); final int layoutOutputIndex = layoutState.getPositionForId(node.getRenderUnit().getId()); if (getItemAt(layoutOutputIndex) == null) { mountLayoutOutput( layoutState.getPositionForId(node.getRenderUnit().getId()), node, layoutOutput, layoutState); mComponentIdsMountedInThisFrame.add(node.getRenderUnit().getId()); } mPreviousTopsIndex++; } while (mPreviousTopsIndex > 0 && localVisibleRect.bottom < layoutOutputTops.get(mPreviousTopsIndex - 1).getBounds().top) { mPreviousTopsIndex--; final RenderTreeNode node = layoutState.getRenderTreeNode(layoutOutputTops.get(mPreviousTopsIndex)); final long id = node.getRenderUnit().getId(); final int layoutOutputIndex = layoutState.getPositionForId(id); if (!isAnimationLocked(node)) { unmountItem(layoutOutputIndex, mHostsByMarker); } } } for (int i = 0, size = mCanMountIncrementallyMountItems.size(); i < size; i++) { final MountItem mountItem = mCanMountIncrementallyMountItems.valueAt(i); final long layoutOutputId = mCanMountIncrementallyMountItems.keyAt(i); if (!mComponentIdsMountedInThisFrame.contains(layoutOutputId)) { final int layoutOutputPosition = layoutState.getPositionForId(layoutOutputId); if (layoutOutputPosition != -1) { mountItemIncrementally(mountItem, processVisibilityOutputs); } } } mComponentIdsMountedInThisFrame.clear(); return true; } /** * Collect transitions from layout time, mount time and from state updates. * * @param layoutState that is going to be mounted. */ void collectAllTransitions(LayoutState layoutState, ComponentTree componentTree) { assertMainThread(); if (mTransitionsExtension != null) { TransitionsExtension.collectAllTransitions(mTransitionsExtensionState, layoutState); return; } } /** @see LithoViewTestHelper#findTestItems(LithoView, String) */ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) Deque<TestItem> findTestItems(String testKey) { if (mTestItemMap == null) { throw new UnsupportedOperationException( "Trying to access TestItems while " + "ComponentsConfiguration.isEndToEndTestRun is false."); } final Deque<TestItem> items = mTestItemMap.get(testKey); return items == null ? new LinkedList<TestItem>() : items; } /** * For HostComponents, we don't set a scoped context during layout calculation because we don't * need one, as we could never call a state update on it. Instead it's okay to use the context * that is passed to MountState from the LithoView, which is not scoped. */ private ComponentContext getContextForComponent(RenderTreeNode node) { ComponentContext c = getComponentContext(node); return c == null ? mContext : c; } private void bindComponentToContent( final MountItem mountItem, final Component component, final ComponentContext context, final LithoLayoutData layoutData, final Object content) { component.bind( getContextForComponent(mountItem.getRenderTreeNode()), content, layoutData.interStagePropsContainer); mDynamicPropsManager.onBindComponentToContent(component, context, content); mountItem.setIsBound(true); } private void unbindComponentFromContent( MountItem mountItem, Component component, Object content) { mDynamicPropsManager.onUnbindComponent(component, content); RenderTreeNode node = mountItem.getRenderTreeNode(); component.unbind( getContextForComponent(node), content, ((LithoLayoutData) node.getLayoutData()).interStagePropsContainer); mountItem.setIsBound(false); } @VisibleForTesting DynamicPropsManager getDynamicPropsManager() { return mDynamicPropsManager; } }
litho-core/src/main/java/com/facebook/litho/MountState.java
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho; import static androidx.core.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO; import static com.facebook.litho.Component.isHostSpec; import static com.facebook.litho.Component.isMountViewSpec; import static com.facebook.litho.ComponentHostUtils.maybeSetDrawableState; import static com.facebook.litho.FrameworkLogEvents.EVENT_MOUNT; import static com.facebook.litho.FrameworkLogEvents.PARAM_IS_DIRTY; import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_CONTENT; import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_COUNT; import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_EXTRAS; import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_TIME; import static com.facebook.litho.FrameworkLogEvents.PARAM_MOVED_COUNT; import static com.facebook.litho.FrameworkLogEvents.PARAM_NO_OP_COUNT; import static com.facebook.litho.FrameworkLogEvents.PARAM_UNCHANGED_COUNT; import static com.facebook.litho.FrameworkLogEvents.PARAM_UNMOUNTED_CONTENT; import static com.facebook.litho.FrameworkLogEvents.PARAM_UNMOUNTED_COUNT; import static com.facebook.litho.FrameworkLogEvents.PARAM_UNMOUNTED_TIME; import static com.facebook.litho.FrameworkLogEvents.PARAM_UPDATED_CONTENT; import static com.facebook.litho.FrameworkLogEvents.PARAM_UPDATED_COUNT; import static com.facebook.litho.FrameworkLogEvents.PARAM_UPDATED_TIME; import static com.facebook.litho.FrameworkLogEvents.PARAM_VISIBILITY_HANDLER; import static com.facebook.litho.FrameworkLogEvents.PARAM_VISIBILITY_HANDLERS_TOTAL_TIME; import static com.facebook.litho.FrameworkLogEvents.PARAM_VISIBILITY_HANDLER_TIME; import static com.facebook.litho.LayoutOutput.getLayoutOutput; import static com.facebook.litho.LithoMountData.getMountData; import static com.facebook.litho.LithoMountData.isViewClickable; import static com.facebook.litho.LithoMountData.isViewEnabled; import static com.facebook.litho.LithoMountData.isViewFocusable; import static com.facebook.litho.LithoMountData.isViewLongClickable; import static com.facebook.litho.LithoMountData.isViewSelected; import static com.facebook.litho.LithoRenderUnit.getComponentContext; import static com.facebook.litho.ThreadUtils.assertMainThread; import static com.facebook.rendercore.MountState.ROOT_HOST_ID; import android.animation.AnimatorInflater; import android.animation.StateListAnimator; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.TextUtils; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import android.view.ViewOutlineProvider; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import androidx.collection.LongSparseArray; import androidx.core.util.Preconditions; import androidx.core.view.ViewCompat; import com.facebook.infer.annotation.ThreadConfined; import com.facebook.litho.config.ComponentsConfiguration; import com.facebook.litho.stats.LithoStats; import com.facebook.rendercore.ErrorReporter; import com.facebook.rendercore.Host; import com.facebook.rendercore.LogLevel; import com.facebook.rendercore.MountDelegate; import com.facebook.rendercore.MountDelegateTarget; import com.facebook.rendercore.MountItem; import com.facebook.rendercore.RenderCoreExtensionHost; import com.facebook.rendercore.RenderTree; import com.facebook.rendercore.RenderTreeNode; import com.facebook.rendercore.UnmountDelegateExtension; import com.facebook.rendercore.extensions.ExtensionState; import com.facebook.rendercore.extensions.MountExtension; import com.facebook.rendercore.incrementalmount.IncrementalMountOutput; import com.facebook.rendercore.utils.BoundsUtils; import com.facebook.rendercore.visibility.VisibilityItem; import com.facebook.rendercore.visibility.VisibilityMountExtension; import java.util.ArrayList; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; /** * Encapsulates the mounted state of a {@link Component}. Provides APIs to update state by recycling * existing UI elements e.g. {@link Drawable}s. * * @see #mount(LayoutState, Rect, boolean) * @see LithoView * @see LayoutState */ @ThreadConfined(ThreadConfined.UI) class MountState implements MountDelegateTarget { private static final String INVALID_REENTRANT_MOUNTS = "MountState:InvalidReentrantMounts"; private static final double NS_IN_MS = 1000000.0; private static final Rect sTempRect = new Rect(); // Holds the current list of mounted items. // Should always be used within a draw lock. private final LongSparseArray<MountItem> mIndexToItemMap; // Holds a list of MountItems that are currently mounted which can mount incrementally. private final LongSparseArray<MountItem> mCanMountIncrementallyMountItems; // A map from test key to a list of one or more `TestItem`s which is only allocated // and populated during test runs. private final Map<String, Deque<TestItem>> mTestItemMap; // Both these arrays are updated in prepareMount(), thus during mounting they hold the information // about the LayoutState that is being mounted, not mLastMountedLayoutState @Nullable private long[] mLayoutOutputsIds; // True if we are receiving a new LayoutState and we need to completely // refresh the content of the HostComponent. Always set from the main thread. private boolean mIsDirty; // True if MountState is currently performing mount. private boolean mIsMounting; // See #needsRemount() private boolean mNeedsRemount; // Holds the list of known component hosts during a mount pass. private final LongSparseArray<ComponentHost> mHostsByMarker = new LongSparseArray<>(); private final ComponentContext mContext; private final LithoView mLithoView; private final Rect mPreviousLocalVisibleRect = new Rect(); private final PrepareMountStats mPrepareMountStats = new PrepareMountStats(); private final MountStats mMountStats = new MountStats(); private int mPreviousTopsIndex; private int mPreviousBottomsIndex; private int mLastMountedComponentTreeId = ComponentTree.INVALID_ID; private @Nullable LayoutState mLayoutState; private @Nullable LayoutState mLastMountedLayoutState; private int mLastDisappearRangeStart = -1; private int mLastDisappearRangeEnd = -1; private final MountItem mRootHostMountItem; private final @Nullable VisibilityMountExtension mVisibilityExtension; private final @Nullable ExtensionState mVisibilityExtensionState; private final Set<Long> mComponentIdsMountedInThisFrame = new HashSet<>(); private final DynamicPropsManager mDynamicPropsManager = new DynamicPropsManager(); private @Nullable MountDelegate mMountDelegate; private @Nullable UnmountDelegateExtension mUnmountDelegateExtension; private @Nullable TransitionsExtension mTransitionsExtension; private @Nullable ExtensionState mTransitionsExtensionState; private @ComponentTree.RecyclingMode int mRecyclingMode = ComponentTree.RecyclingMode.DEFAULT; public MountState(LithoView view) { mIndexToItemMap = new LongSparseArray<>(); mCanMountIncrementallyMountItems = new LongSparseArray<>(); mContext = view.getComponentContext(); mLithoView = view; mIsDirty = true; mTestItemMap = ComponentsConfiguration.isEndToEndTestRun ? new HashMap<String, Deque<TestItem>>() : null; // The mount item representing the top-level root host (LithoView) which // is always automatically mounted. mRootHostMountItem = LithoMountData.createRootHostMountItem(mLithoView); if (ComponentsConfiguration.enableVisibilityExtension) { mVisibilityExtension = VisibilityMountExtension.getInstance(); mVisibilityExtensionState = mVisibilityExtension.createExtensionState(new MountDelegate(this)); VisibilityMountExtension.setRootHost(mVisibilityExtensionState, mLithoView); } else { mVisibilityExtension = null; mVisibilityExtensionState = null; } // Using Incremental Mount Extension and the Transition Extension here is not allowed. if (ComponentsConfiguration.enableTransitionsExtension) { if (!mLithoView.usingExtensionsWithMountDelegate()) { mTransitionsExtension = TransitionsExtension.getInstance( (AnimationsDebug.ENABLED ? AnimationsDebug.TAG : null)); registerMountDelegateExtension(mTransitionsExtension); mTransitionsExtensionState = getExtensionState(mTransitionsExtension); } } else { mTransitionsExtension = null; mTransitionsExtensionState = null; } } @Override public void registerMountDelegateExtension(MountExtension mountExtension) { if (mMountDelegate == null) { mMountDelegate = new MountDelegate(this); } mMountDelegate.addExtension(mountExtension); } @Override public void unregisterMountDelegateExtension(MountExtension mountExtension) { if (mMountDelegate == null) { return; } mMountDelegate.removeExtension(mountExtension); } /** * To be called whenever the components needs to start the mount process from scratch e.g. when * the component's props or layout change or when the components gets attached to a host. */ void setDirty() { assertMainThread(); mIsDirty = true; mPreviousLocalVisibleRect.setEmpty(); } boolean isDirty() { assertMainThread(); return mIsDirty; } /** * True if we have manually unmounted content (e.g. via unmountAllItems) which means that while we * may not have a new LayoutState, the mounted content does not match what the viewport for the * LithoView may be. */ @Override public boolean needsRemount() { assertMainThread(); return mNeedsRemount; } void setRecyclingMode(@ComponentTree.RecyclingMode int recyclingMode) { this.mRecyclingMode = recyclingMode; } /** * Mount the layoutState on the pre-set HostView. * * @param layoutState a new {@link LayoutState} to mount * @param localVisibleRect If this variable is null, then mount everything, since incremental * mount is not enabled. Otherwise mount only what the rect (in local coordinates) contains * @param processVisibilityOutputs whether to process visibility outputs as part of the mount */ void mount( LayoutState layoutState, @Nullable Rect localVisibleRect, boolean processVisibilityOutputs) { final ComponentTree componentTree = mLithoView.getComponentTree(); final boolean isIncrementalMountEnabled = componentTree.isIncrementalMountEnabled(); final boolean isVisibilityProcessingEnabled = componentTree.isVisibilityProcessingEnabled(); assertMainThread(); if (layoutState == null) { throw new IllegalStateException("Trying to mount a null layoutState"); } if (mVisibilityExtension != null && mIsDirty) { mVisibilityExtension.beforeMount(mVisibilityExtensionState, layoutState, localVisibleRect); } if (mTransitionsExtension != null && mIsDirty) { mTransitionsExtension.beforeMount(mTransitionsExtensionState, layoutState, localVisibleRect); } mLayoutState = layoutState; if (mIsMounting) { ComponentsReporter.emitMessage( ComponentsReporter.LogLevel.FATAL, INVALID_REENTRANT_MOUNTS, "Trying to mount while already mounting! " + getMountItemDebugMessage(mRootHostMountItem)); } mIsMounting = true; final boolean isTracing = ComponentsSystrace.isTracing(); if (isTracing) { String sectionName = isIncrementalMountEnabled ? "incrementalMount" : "mount"; ComponentsSystrace.beginSectionWithArgs(sectionName) .arg("treeId", layoutState.getComponentTreeId()) .arg("component", componentTree.getSimpleName()) .arg("logTag", componentTree.getContext().getLogTag()) .flush(); // We also would like to trace this section attributed with component name // for component share analysis. ComponentsSystrace.beginSection(sectionName + "_" + componentTree.getSimpleName()); } final ComponentsLogger logger = componentTree.getContext().getLogger(); final int componentTreeId = layoutState.getComponentTreeId(); if (componentTreeId != mLastMountedComponentTreeId) { // If we're mounting a new ComponentTree, don't keep around and use the previous LayoutState // since things like transition animations aren't relevant. clearLastMountedLayoutState(); } final PerfEvent mountPerfEvent = logger == null ? null : LogTreePopulator.populatePerfEventFromLogger( componentTree.getContext(), logger, logger.newPerformanceEvent(componentTree.getContext(), EVENT_MOUNT)); if (mIsDirty) { // Prepare the data structure for the new LayoutState and removes mountItems // that are not present anymore if isUpdateMountInPlace is enabled. if (mountPerfEvent != null) { mountPerfEvent.markerPoint("PREPARE_MOUNT_START"); } prepareMount(layoutState, mountPerfEvent); if (mountPerfEvent != null) { mountPerfEvent.markerPoint("PREPARE_MOUNT_END"); } } mMountStats.reset(); if (mountPerfEvent != null && logger.isTracing(mountPerfEvent)) { mMountStats.enableLogging(); } if (!isIncrementalMountEnabled || !performIncrementalMount(layoutState, localVisibleRect, processVisibilityOutputs)) { final MountItem rootMountItem = mIndexToItemMap.get(ROOT_HOST_ID); final Rect absoluteBounds = new Rect(); for (int i = 0, size = layoutState.getMountableOutputCount(); i < size; i++) { final RenderTreeNode node = layoutState.getMountableOutputAt(i); final LayoutOutput layoutOutput = getLayoutOutput(node); final Component component = layoutOutput.getComponent(); if (isTracing) { ComponentsSystrace.beginSection(component.getSimpleName()); } final MountItem currentMountItem = getItemAt(i); final boolean isMounted = currentMountItem != null; final boolean isRoot = currentMountItem != null && currentMountItem == rootMountItem; final boolean isMountable = !isIncrementalMountEnabled || isMountedHostWithChildContent(currentMountItem) || Rect.intersects(localVisibleRect, node.getAbsoluteBounds(absoluteBounds)) || isAnimationLocked(node) || isRoot; if (isMountable && !isMounted) { mountLayoutOutput(i, node, layoutOutput, layoutState); if (isIncrementalMountEnabled) { applyMountBinders(layoutOutput, getItemAt(i), i); } } else if (!isMountable && isMounted) { unmountItem(i, mHostsByMarker); } else if (isMounted) { if (mIsDirty || (isRoot && mNeedsRemount)) { final boolean useUpdateValueFromLayoutOutput = mLastMountedLayoutState != null && mLastMountedLayoutState.getId() == layoutState.getPreviousLayoutStateId(); final long startTime = System.nanoTime(); final boolean itemUpdated = updateMountItemIfNeeded( node, currentMountItem, useUpdateValueFromLayoutOutput, componentTreeId, i); if (mMountStats.isLoggingEnabled) { if (itemUpdated) { mMountStats.updatedNames.add(component.getSimpleName()); mMountStats.updatedTimes.add((System.nanoTime() - startTime) / NS_IN_MS); mMountStats.updatedCount++; } else { mMountStats.noOpCount++; } } } if (isIncrementalMountEnabled && component.hasChildLithoViews()) { mountItemIncrementally(currentMountItem, processVisibilityOutputs); } } if (isTracing) { ComponentsSystrace.endSection(); } } if (isIncrementalMountEnabled) { setupPreviousMountableOutputData(layoutState, localVisibleRect); } } afterMountMaybeUpdateAnimations(); if (isVisibilityProcessingEnabled) { if (isTracing) { ComponentsSystrace.beginSection("processVisibilityOutputs"); } if (mountPerfEvent != null) { mountPerfEvent.markerPoint("EVENT_PROCESS_VISIBILITY_OUTPUTS_START"); } processVisibilityOutputs( layoutState, localVisibleRect, mPreviousLocalVisibleRect, mIsDirty, mountPerfEvent); if (mountPerfEvent != null) { mountPerfEvent.markerPoint("EVENT_PROCESS_VISIBILITY_OUTPUTS_END"); } if (isTracing) { ComponentsSystrace.endSection(); } } final boolean wasDirty = mIsDirty; mIsDirty = false; mNeedsRemount = false; if (localVisibleRect != null) { mPreviousLocalVisibleRect.set(localVisibleRect); } clearLastMountedLayoutState(); mLastMountedComponentTreeId = componentTreeId; mLastMountedLayoutState = layoutState; processTestOutputs(layoutState); if (mountPerfEvent != null) { logMountPerfEvent(logger, mountPerfEvent, wasDirty); } if (isTracing) { ComponentsSystrace.endSection(); ComponentsSystrace.endSection(); } LithoStats.incrementComponentMountCount(); mIsMounting = false; } private void clearLastMountedLayoutState() { mLastMountedLayoutState = null; } private void afterMountMaybeUpdateAnimations() { if (mTransitionsExtension != null && mIsDirty) { mTransitionsExtension.afterMount(mTransitionsExtensionState); } } @Override public void mount(RenderTree renderTree) { final LayoutState layoutState = (LayoutState) renderTree.getRenderTreeData(); mount(layoutState, true); } /** * Mount only. Similar shape to RenderCore's mount. For extras such as incremental mount, * visibility outputs etc register an extension. To do: extract transitions logic from here. */ void mount(LayoutState layoutState, boolean processVisibilityOutputs) { assertMainThread(); if (layoutState == null) { throw new IllegalStateException("Trying to mount a null layoutState"); } mLayoutState = layoutState; if (mIsMounting) { ComponentsReporter.emitMessage( ComponentsReporter.LogLevel.FATAL, INVALID_REENTRANT_MOUNTS, "Trying to mount while already mounting! " + getMountItemDebugMessage(mRootHostMountItem)); } mIsMounting = true; final ComponentTree componentTree = mLithoView.getComponentTree(); final boolean isTracing = ComponentsSystrace.isTracing(); if (isTracing) { ComponentsSystrace.beginSectionWithArgs("mount") .arg("treeId", layoutState.getComponentTreeId()) .arg("component", componentTree.getSimpleName()) .arg("logTag", componentTree.getContext().getLogTag()) .flush(); } final ComponentsLogger logger = componentTree.getContext().getLogger(); final int componentTreeId = layoutState.getComponentTreeId(); if (componentTreeId != mLastMountedComponentTreeId) { // If we're mounting a new ComponentTree, don't keep around and use the previous LayoutState // since things like transition animations aren't relevant. clearLastMountedLayoutState(); } final PerfEvent mountPerfEvent = logger == null ? null : LogTreePopulator.populatePerfEventFromLogger( componentTree.getContext(), logger, logger.newPerformanceEvent(componentTree.getContext(), EVENT_MOUNT)); // Prepare the data structure for the new LayoutState and removes mountItems // that are not present anymore if isUpdateMountInPlace is enabled. if (mountPerfEvent != null) { mountPerfEvent.markerPoint("PREPARE_MOUNT_START"); } prepareMount(layoutState, mountPerfEvent); if (mountPerfEvent != null) { mountPerfEvent.markerPoint("PREPARE_MOUNT_END"); } mMountStats.reset(); if (mountPerfEvent != null && logger.isTracing(mountPerfEvent)) { mMountStats.enableLogging(); } for (int i = 0, size = layoutState.getMountableOutputCount(); i < size; i++) { final RenderTreeNode renderTreeNode = layoutState.getMountableOutputAt(i); final LayoutOutput layoutOutput = getLayoutOutput(renderTreeNode); final Component component = layoutOutput.getComponent(); if (isTracing) { ComponentsSystrace.beginSection(component.getSimpleName()); } final MountItem currentMountItem = getItemAt(i); final boolean isMounted = currentMountItem != null; final boolean isMountable = isMountable(renderTreeNode, i); if (!isMountable) { if (isMounted) { unmountItem(i, mHostsByMarker); } } else if (!isMounted) { mountLayoutOutput(i, renderTreeNode, layoutOutput, layoutState); applyMountBinders(layoutOutput, getItemAt(i), i); } else { final boolean useUpdateValueFromLayoutOutput = mLastMountedLayoutState != null && mLastMountedLayoutState.getId() == layoutState.getPreviousLayoutStateId(); final long startTime = System.nanoTime(); final boolean itemUpdated = updateMountItemIfNeeded( renderTreeNode, currentMountItem, useUpdateValueFromLayoutOutput, componentTreeId, i); if (mMountStats.isLoggingEnabled) { if (itemUpdated) { mMountStats.updatedNames.add(component.getSimpleName()); mMountStats.updatedTimes.add((System.nanoTime() - startTime) / NS_IN_MS); mMountStats.updatedCount++; } else { mMountStats.noOpCount++; } } applyBindBinders(currentMountItem); } if (isTracing) { ComponentsSystrace.endSection(); } } final boolean wasDirty = mIsDirty; mIsDirty = false; mNeedsRemount = false; clearLastMountedLayoutState(); mLastMountedComponentTreeId = componentTreeId; mLastMountedLayoutState = layoutState; if (mountPerfEvent != null) { logMountPerfEvent(logger, mountPerfEvent, wasDirty); } if (isTracing) { ComponentsSystrace.endSection(); } LithoStats.incrementComponentMountCount(); mIsMounting = false; } private void applyMountBinders(LayoutOutput layoutOutput, MountItem mountItem, int position) { if (mTransitionsExtension != null) { mTransitionsExtension.onMountItem( mTransitionsExtensionState, mountItem.getRenderTreeNode().getRenderUnit(), mountItem.getContent(), mountItem.getRenderTreeNode().getLayoutData()); } else if (mMountDelegate != null) { mMountDelegate.onMountItem( mountItem.getRenderTreeNode().getRenderUnit(), mountItem.getContent(), mountItem.getRenderTreeNode().getLayoutData()); } } private void applyBindBinders(MountItem mountItem) { if (mMountDelegate == null) { return; } } private void applyUnbindBinders(LayoutOutput output, MountItem mountItem) { if (mTransitionsExtension != null) { mTransitionsExtension.onUnbindItem( mTransitionsExtensionState, mountItem.getRenderTreeNode().getRenderUnit(), output, mountItem.getRenderTreeNode().getLayoutData()); } else if (mMountDelegate != null) { mMountDelegate.onUnmountItem( mountItem.getRenderTreeNode().getRenderUnit(), output, mountItem.getContent()); } } private boolean isMountable(RenderTreeNode renderTreeNode, int position) { if (mMountDelegate == null) { return true; } final boolean isLockedForMount = mMountDelegate.maybeLockForMount(renderTreeNode, position); return isLockedForMount; } @Override public void notifyMount(long id) { if (mLayoutState == null) { return; } final int position = mLayoutState.getPositionForId(id); if (position < 0 || getItemAt(position) != null) { return; } final RenderTreeNode node = mLayoutState.getMountableOutputAt(position); mountLayoutOutput(position, node, getLayoutOutput(node), mLayoutState); } @Override public void notifyUnmount(long id) { final MountItem item = mIndexToItemMap.get(id); if (item == null || mLayoutState == null) { return; } final int position = mLayoutState.getPositionForId(id); if (position >= 0) { unmountItem(position, mHostsByMarker); } } private void logMountPerfEvent( ComponentsLogger logger, PerfEvent mountPerfEvent, boolean isDirty) { if (!mMountStats.isLoggingEnabled) { logger.cancelPerfEvent(mountPerfEvent); return; } // MOUNT events that don't mount any content are not valuable enough to log at the moment. // We will likely enable them again in the future. T31729233 if (mMountStats.mountedCount == 0 || mMountStats.mountedNames.isEmpty()) { logger.cancelPerfEvent(mountPerfEvent); return; } mountPerfEvent.markerAnnotate(PARAM_MOUNTED_COUNT, mMountStats.mountedCount); mountPerfEvent.markerAnnotate( PARAM_MOUNTED_CONTENT, mMountStats.mountedNames.toArray(new String[0])); mountPerfEvent.markerAnnotate( PARAM_MOUNTED_TIME, mMountStats.mountTimes.toArray(new Double[0])); mountPerfEvent.markerAnnotate(PARAM_UNMOUNTED_COUNT, mMountStats.unmountedCount); mountPerfEvent.markerAnnotate( PARAM_UNMOUNTED_CONTENT, mMountStats.unmountedNames.toArray(new String[0])); mountPerfEvent.markerAnnotate( PARAM_UNMOUNTED_TIME, mMountStats.unmountedTimes.toArray(new Double[0])); mountPerfEvent.markerAnnotate(PARAM_MOUNTED_EXTRAS, mMountStats.extras.toArray(new String[0])); mountPerfEvent.markerAnnotate(PARAM_UPDATED_COUNT, mMountStats.updatedCount); mountPerfEvent.markerAnnotate( PARAM_UPDATED_CONTENT, mMountStats.updatedNames.toArray(new String[0])); mountPerfEvent.markerAnnotate( PARAM_UPDATED_TIME, mMountStats.updatedTimes.toArray(new Double[0])); mountPerfEvent.markerAnnotate( PARAM_VISIBILITY_HANDLERS_TOTAL_TIME, mMountStats.visibilityHandlersTotalTime); mountPerfEvent.markerAnnotate( PARAM_VISIBILITY_HANDLER, mMountStats.visibilityHandlerNames.toArray(new String[0])); mountPerfEvent.markerAnnotate( PARAM_VISIBILITY_HANDLER_TIME, mMountStats.visibilityHandlerTimes.toArray(new Double[0])); mountPerfEvent.markerAnnotate(PARAM_NO_OP_COUNT, mMountStats.noOpCount); mountPerfEvent.markerAnnotate(PARAM_IS_DIRTY, isDirty); logger.logPerfEvent(mountPerfEvent); } void processVisibilityOutputs( LayoutState layoutState, @Nullable Rect localVisibleRect, Rect previousLocalVisibleRect, boolean isDirty, @Nullable PerfEvent mountPerfEvent) { if (mVisibilityExtension == null) { return; } if (isDirty) { mVisibilityExtension.afterMount(mVisibilityExtensionState); } else { mVisibilityExtension.onVisibleBoundsChanged(mVisibilityExtensionState, localVisibleRect); } } @VisibleForTesting Map<String, VisibilityItem> getVisibilityIdToItemMap() { return VisibilityMountExtension.getVisibilityIdToItemMap(mVisibilityExtensionState); } @VisibleForTesting @Override public ArrayList<Host> getHosts() { final ArrayList<Host> hosts = new ArrayList<>(); for (int i = 0, size = mHostsByMarker.size(); i < size; i++) { hosts.add(mHostsByMarker.valueAt(i)); } return hosts; } @Override public int getMountItemCount() { return mIndexToItemMap.size(); } @Override public int getRenderUnitCount() { assertMainThread(); return mLayoutOutputsIds == null ? 0 : mLayoutOutputsIds.length; } @Override public @Nullable MountItem getMountItemAt(int position) { return getItemAt(position); } @Override public void setUnmountDelegateExtension(UnmountDelegateExtension unmountDelegateExtension) { mUnmountDelegateExtension = unmountDelegateExtension; } @Override public void removeUnmountDelegateExtension() { mUnmountDelegateExtension = null; } @Override public @Nullable ExtensionState getExtensionState(MountExtension mountExtension) { if (mountExtension == mVisibilityExtension) { return mVisibilityExtensionState; } return mMountDelegate.getExtensionState(mountExtension); } /** Clears and re-populates the test item map if we are in e2e test mode. */ private void processTestOutputs(LayoutState layoutState) { if (mTestItemMap == null) { return; } mTestItemMap.clear(); for (int i = 0, size = layoutState.getTestOutputCount(); i < size; i++) { final TestOutput testOutput = layoutState.getTestOutputAt(i); final long hostMarker = testOutput.getHostMarker(); final long layoutOutputId = testOutput.getLayoutOutputId(); final MountItem mountItem = layoutOutputId == -1 ? null : mIndexToItemMap.get(layoutOutputId); final TestItem testItem = new TestItem(); testItem.setHost(hostMarker == -1 ? null : mHostsByMarker.get(hostMarker)); testItem.setBounds(testOutput.getBounds()); testItem.setTestKey(testOutput.getTestKey()); testItem.setContent(mountItem == null ? null : mountItem.getContent()); final Deque<TestItem> items = mTestItemMap.get(testOutput.getTestKey()); final Deque<TestItem> updatedItems = items == null ? new LinkedList<TestItem>() : items; updatedItems.add(testItem); mTestItemMap.put(testOutput.getTestKey(), updatedItems); } } private static boolean isMountedHostWithChildContent(@Nullable MountItem mountItem) { if (mountItem == null) { return false; } final Object content = mountItem.getContent(); if (!(content instanceof ComponentHost)) { return false; } final ComponentHost host = (ComponentHost) content; return host.getMountItemCount() > 0; } private void setupPreviousMountableOutputData(LayoutState layoutState, Rect localVisibleRect) { if (localVisibleRect.isEmpty()) { return; } final ArrayList<IncrementalMountOutput> layoutOutputTops = layoutState.getOutputsOrderedByTopBounds(); final ArrayList<IncrementalMountOutput> layoutOutputBottoms = layoutState.getOutputsOrderedByBottomBounds(); final int mountableOutputCount = layoutState.getMountableOutputCount(); mPreviousTopsIndex = layoutState.getMountableOutputCount(); for (int i = 0; i < mountableOutputCount; i++) { if (localVisibleRect.bottom <= layoutOutputTops.get(i).getBounds().top) { mPreviousTopsIndex = i; break; } } mPreviousBottomsIndex = layoutState.getMountableOutputCount(); for (int i = 0; i < mountableOutputCount; i++) { if (localVisibleRect.top < layoutOutputBottoms.get(i).getBounds().bottom) { mPreviousBottomsIndex = i; break; } } } List<LithoView> getChildLithoViewsFromCurrentlyMountedItems() { final ArrayList<LithoView> childLithoViews = new ArrayList<>(); for (int i = 0; i < mIndexToItemMap.size(); i++) { final long layoutOutputId = mIndexToItemMap.keyAt(i); final MountItem mountItem = mIndexToItemMap.get(layoutOutputId); if (mountItem != null && mountItem.getContent() instanceof HasLithoViewChildren) { ((HasLithoViewChildren) mountItem.getContent()).obtainLithoViewChildren(childLithoViews); } } return childLithoViews; } void clearVisibilityItems() { if (mVisibilityExtension != null) { VisibilityMountExtension.clearVisibilityItems(mVisibilityExtensionState); } } private void registerHost(long id, ComponentHost host) { mHostsByMarker.put(id, host); } private static int computeRectArea(Rect rect) { return rect.isEmpty() ? 0 : (rect.width() * rect.height()); } private boolean updateMountItemIfNeeded( RenderTreeNode node, MountItem currentMountItem, boolean useUpdateValueFromLayoutOutput, int componentTreeId, int index) { final LayoutOutput nextLayoutOutput = getLayoutOutput(node); final Component layoutOutputComponent = nextLayoutOutput.getComponent(); final LayoutOutput currentLayoutOutput = getLayoutOutput(currentMountItem); final Component itemComponent = currentLayoutOutput.getComponent(); final Object currentContent = currentMountItem.getContent(); final ComponentHost host = (ComponentHost) currentMountItem.getHost(); final ComponentContext currentContext = getComponentContext(currentMountItem); final ComponentContext nextContext = getComponentContext(node); final LithoLayoutData nextLayoutData = (LithoLayoutData) node.getLayoutData(); final LithoLayoutData currentLayoutData = (LithoLayoutData) currentMountItem.getRenderTreeNode().getLayoutData(); if (layoutOutputComponent == null) { throw new RuntimeException("Trying to update a MountItem with a null Component."); } // 1. Check if the mount item generated from the old component should be updated. final boolean shouldUpdate = shouldUpdateMountItem( nextLayoutOutput, nextLayoutData, nextContext, currentLayoutOutput, currentLayoutData, currentContext, useUpdateValueFromLayoutOutput); final boolean shouldUpdateViewInfo = shouldUpdate || shouldUpdateViewInfo(nextLayoutOutput, currentLayoutOutput); // 2. Reset all the properties like click handler, content description and tags related to // this item if it needs to be updated. the update mount item will re-set the new ones. if (shouldUpdateViewInfo) { maybeUnsetViewAttributes(currentMountItem); } // 3. We will re-bind this later in 7 regardless so let's make sure it's currently unbound. if (currentMountItem.isBound()) { unbindComponentFromContent(currentMountItem, itemComponent, currentMountItem.getContent()); } // 4. Re initialize the MountItem internal state with the new attributes from LayoutOutput currentMountItem.update(node); // 5. If the mount item is not valid for this component update its content and view attributes. if (shouldUpdate) { updateMountedContent( currentMountItem, layoutOutputComponent, nextContext, nextLayoutData, itemComponent, currentContext, currentLayoutData); } if (shouldUpdateViewInfo) { setViewAttributes(currentMountItem); } // 6. Set the mounted content on the Component and call the bind callback. bindComponentToContent( currentMountItem, layoutOutputComponent, nextContext, nextLayoutData, currentContent); // 7. Update the bounds of the mounted content. This needs to be done regardless of whether // the component has been updated or not since the mounted item might might have the same // size and content but a different position. updateBoundsForMountedLayoutOutput(node, nextLayoutOutput, currentMountItem); if (currentMountItem.getContent() instanceof Drawable) { maybeSetDrawableState( host, (Drawable) currentContent, currentLayoutOutput.getFlags(), currentLayoutOutput.getNodeInfo()); } return shouldUpdate; } static boolean shouldUpdateViewInfo( final LayoutOutput nextLayoutOutput, final LayoutOutput currentLayoutOutput) { final ViewNodeInfo nextViewNodeInfo = nextLayoutOutput.getViewNodeInfo(); final ViewNodeInfo currentViewNodeInfo = currentLayoutOutput.getViewNodeInfo(); if ((currentViewNodeInfo == null && nextViewNodeInfo != null) || (currentViewNodeInfo != null && !currentViewNodeInfo.isEquivalentTo(nextViewNodeInfo))) { return true; } final NodeInfo nextNodeInfo = nextLayoutOutput.getNodeInfo(); final NodeInfo currentNodeInfo = currentLayoutOutput.getNodeInfo(); return (currentNodeInfo == null && nextNodeInfo != null) || (currentNodeInfo != null && !currentNodeInfo.isEquivalentTo(nextNodeInfo)); } static boolean shouldUpdateMountItem( final LayoutOutput nextLayoutOutput, final @Nullable LithoLayoutData nextLayoutData, final @Nullable ComponentContext nextContext, final LayoutOutput currentLayoutOutput, final @Nullable LithoLayoutData currentLayoutData, final @Nullable ComponentContext currentContext, final boolean useUpdateValueFromLayoutOutput) { @LayoutOutput.UpdateState final int updateState = nextLayoutOutput.getUpdateState(); final Component currentComponent = currentLayoutOutput.getComponent(); final Component nextComponent = nextLayoutOutput.getComponent(); // If the two components have different sizes and the mounted content depends on the size we // just return true immediately. if (nextComponent.isMountSizeDependent() && !sameSize( Preconditions.checkNotNull(nextLayoutData), Preconditions.checkNotNull(currentLayoutData))) { return true; } if (useUpdateValueFromLayoutOutput) { if (updateState == LayoutOutput.STATE_UPDATED) { // Check for incompatible ReferenceLifecycle. return currentComponent instanceof DrawableComponent && nextComponent instanceof DrawableComponent && shouldUpdate(currentComponent, currentContext, nextComponent, nextContext); } else if (updateState == LayoutOutput.STATE_DIRTY) { return true; } } return shouldUpdate(currentComponent, currentContext, nextComponent, nextContext); } private static boolean shouldUpdate( Component currentComponent, ComponentContext currentScopedContext, Component nextComponent, ComponentContext nextScopedContext) { try { return currentComponent.shouldComponentUpdate( currentScopedContext, currentComponent, nextScopedContext, nextComponent); } catch (Exception e) { ComponentUtils.handle(nextScopedContext, e); return true; } } static boolean sameSize(final LithoLayoutData next, final LithoLayoutData current) { return next.width == current.width && next.height == current.height; } private static void updateBoundsForMountedLayoutOutput( final RenderTreeNode node, final LayoutOutput layoutOutput, final MountItem item) { // MountState should never update the bounds of the top-level host as this // should be done by the ViewGroup containing the LithoView. if (node.getRenderUnit().getId() == ROOT_HOST_ID) { return; } final Rect bounds = node.getBounds(); final boolean forceTraversal = Component.isMountViewSpec(layoutOutput.getComponent()) && ((View) item.getContent()).isLayoutRequested(); applyBoundsToMountContent( item.getContent(), bounds.left, bounds.top, bounds.right, bounds.bottom, forceTraversal /* force */); } /** Prepare the {@link MountState} to mount a new {@link LayoutState}. */ private void prepareMount(LayoutState layoutState, @Nullable PerfEvent perfEvent) { final boolean isTracing = ComponentsSystrace.isTracing(); if (isTracing) { ComponentsSystrace.beginSection("prepareMount"); } final PrepareMountStats stats = unmountOrMoveOldItems(layoutState); if (perfEvent != null) { perfEvent.markerAnnotate(PARAM_UNMOUNTED_COUNT, stats.unmountedCount); perfEvent.markerAnnotate(PARAM_MOVED_COUNT, stats.movedCount); perfEvent.markerAnnotate(PARAM_UNCHANGED_COUNT, stats.unchangedCount); } if (mIndexToItemMap.get(ROOT_HOST_ID) == null || mHostsByMarker.get(ROOT_HOST_ID) == null) { // Mounting always starts with the root host. registerHost(ROOT_HOST_ID, mLithoView); // Root host is implicitly marked as mounted. mIndexToItemMap.put(ROOT_HOST_ID, mRootHostMountItem); } final int outputCount = layoutState.getMountableOutputCount(); if (mLayoutOutputsIds == null || outputCount != mLayoutOutputsIds.length) { mLayoutOutputsIds = new long[outputCount]; } for (int i = 0; i < outputCount; i++) { mLayoutOutputsIds[i] = layoutState.getMountableOutputAt(i).getRenderUnit().getId(); } if (isTracing) { ComponentsSystrace.endSection(); } } /** * Go over all the mounted items from the leaves to the root and unmount only the items that are * not present in the new LayoutOutputs. If an item is still present but in a new position move * the item inside its host. The condition where an item changed host doesn't need any special * treatment here since we mark them as removed and re-added when calculating the new * LayoutOutputs */ private PrepareMountStats unmountOrMoveOldItems(LayoutState newLayoutState) { mPrepareMountStats.reset(); if (mLayoutOutputsIds == null) { return mPrepareMountStats; } // Traversing from the beginning since mLayoutOutputsIds unmounting won't remove entries there // but only from mIndexToItemMap. If an host changes we're going to unmount it and recursively // all its mounted children. for (int i = 0; i < mLayoutOutputsIds.length; i++) { final int newPosition = newLayoutState.getPositionForId(mLayoutOutputsIds[i]); final @Nullable RenderTreeNode newRenderTreeNode = newPosition != -1 ? newLayoutState.getMountableOutputAt(newPosition) : null; final @Nullable LayoutOutput newLayoutOutput = newRenderTreeNode != null ? getLayoutOutput(newRenderTreeNode) : null; final MountItem oldItem = getItemAt(i); final boolean hasUnmountDelegate = mUnmountDelegateExtension != null && oldItem != null ? mUnmountDelegateExtension.shouldDelegateUnmount( mMountDelegate.getUnmountDelegateExtensionState(), oldItem) : false; if (hasUnmountDelegate) { continue; } if (newPosition == -1) { unmountItem(i, mHostsByMarker); mPrepareMountStats.unmountedCount++; } else { final long newHostMarker = i != 0 ? newRenderTreeNode.getParent().getRenderUnit().getId() : -1; if (oldItem == null) { // This was previously unmounted. mPrepareMountStats.unmountedCount++; } else if (oldItem.getHost() != mHostsByMarker.get(newHostMarker)) { // If the id is the same but the parent host is different we simply unmount the item and // re-mount it later. If the item to unmount is a ComponentHost, all the children will be // recursively unmounted. unmountItem(i, mHostsByMarker); mPrepareMountStats.unmountedCount++; } else if (newPosition != i) { // If a MountItem for this id exists and the hostMarker has not changed but its position // in the outputs array has changed we need to update the position in the Host to ensure // the z-ordering. oldItem.getHost().moveItem(oldItem, i, newPosition); mPrepareMountStats.movedCount++; } else { mPrepareMountStats.unchangedCount++; } } } return mPrepareMountStats; } private void updateMountedContent( final MountItem item, final Component newComponent, final ComponentContext newContext, final LithoLayoutData nextLayoutData, final Component previousComponent, final ComponentContext previousContext, final LithoLayoutData currentLayoutData) { if (isHostSpec(newComponent)) { return; } final Object previousContent = item.getContent(); // Call unmount and mount in sequence to make sure all the the resources are correctly // de-allocated. It's possible for previousContent to equal null - when the root is // interactive we create a LayoutOutput without content in order to set up click handling. previousComponent.unmount( previousContext, previousContent, currentLayoutData.interStagePropsContainer); newComponent.mount(newContext, previousContent, nextLayoutData.interStagePropsContainer); } private void mountLayoutOutput( final int index, final RenderTreeNode node, final LayoutOutput layoutOutput, final LayoutState layoutState) { // 1. Resolve the correct host to mount our content to. final long startTime = System.nanoTime(); // parent should never be null final long hostMarker = node.getParent().getRenderUnit().getId(); ComponentHost host = mHostsByMarker.get(hostMarker); if (host == null) { // Host has not yet been mounted - mount it now. final int hostMountIndex = layoutState.getPositionForId(hostMarker); final RenderTreeNode hostNode = layoutState.getMountableOutputAt(hostMountIndex); final LayoutOutput hostLayoutOutput = getLayoutOutput(hostNode); mountLayoutOutput(hostMountIndex, hostNode, hostLayoutOutput, layoutState); host = mHostsByMarker.get(hostMarker); } // 2. Generate the component's mount state (this might also be a ComponentHost View). final Component component = layoutOutput.getComponent(); if (component == null) { throw new RuntimeException("Trying to mount a LayoutOutput with a null Component."); } final Object content = ComponentsPools.acquireMountContent( mContext.getAndroidContext(), component, mRecyclingMode); final ComponentContext context = getContextForComponent(node); final LithoLayoutData layoutData = (LithoLayoutData) node.getLayoutData(); component.mount(context, content, layoutData.interStagePropsContainer); // 3. If it's a ComponentHost, add the mounted View to the list of Hosts. if (isHostSpec(component)) { ComponentHost componentHost = (ComponentHost) content; registerHost(node.getRenderUnit().getId(), componentHost); } // 4. Mount the content into the selected host. final MountItem item = mountContent(index, component, content, host, node, layoutOutput); // 5. Notify the component that mounting has completed bindComponentToContent(item, component, context, layoutData, content); // 6. Apply the bounds to the Mount content now. It's important to do so after bind as calling // bind might have triggered a layout request within a View. final Rect bounds = node.getBounds(); applyBoundsToMountContent( item.getContent(), bounds.left, bounds.top, bounds.right, bounds.bottom, true /* force */); // 6. Update the mount stats if (mMountStats.isLoggingEnabled) { mMountStats.mountTimes.add((System.nanoTime() - startTime) / NS_IN_MS); mMountStats.mountedNames.add(component.getSimpleName()); mMountStats.mountedCount++; final ComponentContext scopedContext = getComponentContext(node); mMountStats.extras.add( LogTreePopulator.getAnnotationBundleFromLogger(scopedContext, context.getLogger())); } } // The content might be null because it's the LayoutSpec for the root host // (the very first LayoutOutput). private MountItem mountContent( int index, Component component, Object content, ComponentHost host, RenderTreeNode node, LayoutOutput layoutOutput) { final MountItem item = new MountItem(node, host, content); item.setMountData(new LithoMountData(content)); // Create and keep a MountItem even for the layoutSpec with null content // that sets the root host interactions. mIndexToItemMap.put(mLayoutOutputsIds[index], item); if (component.hasChildLithoViews()) { mCanMountIncrementallyMountItems.put(mLayoutOutputsIds[index], item); } mount(host, index, content, item, node); setViewAttributes(item); return item; } private static void mount( final ComponentHost host, final int index, final Object content, final MountItem item, final RenderTreeNode node) { host.mount(index, item, node.getBounds()); } private static void unmount( final ComponentHost host, final int index, final Object content, final MountItem item, final LayoutOutput output) { host.unmount(index, item); } private static void applyBoundsToMountContent( Object content, int left, int top, int right, int bottom, boolean force) { assertMainThread(); BoundsUtils.applyBoundsToMountContent(left, top, right, bottom, null, content, force); } private static void setViewAttributes(MountItem item) { setViewAttributes(item.getContent(), getLayoutOutput(item)); } static void setViewAttributes(Object content, LayoutOutput output) { final Component component = output.getComponent(); if (!isMountViewSpec(component)) { return; } final View view = (View) content; final NodeInfo nodeInfo = output.getNodeInfo(); if (nodeInfo != null) { setClickHandler(nodeInfo.getClickHandler(), view); setLongClickHandler(nodeInfo.getLongClickHandler(), view); setFocusChangeHandler(nodeInfo.getFocusChangeHandler(), view); setTouchHandler(nodeInfo.getTouchHandler(), view); setInterceptTouchHandler(nodeInfo.getInterceptTouchHandler(), view); setAccessibilityDelegate(view, nodeInfo); setViewTag(view, nodeInfo.getViewTag()); setViewTags(view, nodeInfo.getViewTags()); setShadowElevation(view, nodeInfo.getShadowElevation()); setOutlineProvider(view, nodeInfo.getOutlineProvider()); setClipToOutline(view, nodeInfo.getClipToOutline()); setClipChildren(view, nodeInfo); setContentDescription(view, nodeInfo.getContentDescription()); setFocusable(view, nodeInfo.getFocusState()); setClickable(view, nodeInfo.getClickableState()); setEnabled(view, nodeInfo.getEnabledState()); setSelected(view, nodeInfo.getSelectedState()); setScale(view, nodeInfo); setAlpha(view, nodeInfo); setRotation(view, nodeInfo); setRotationX(view, nodeInfo); setRotationY(view, nodeInfo); setTransitionName(view, nodeInfo.getTransitionName()); } setImportantForAccessibility(view, output.getImportantForAccessibility()); final ViewNodeInfo viewNodeInfo = output.getViewNodeInfo(); if (viewNodeInfo != null) { final boolean isHostSpec = isHostSpec(component); setViewLayerType(view, viewNodeInfo); setViewStateListAnimator(view, viewNodeInfo); if (LayoutOutput.areDrawableOutputsDisabled(output.getFlags())) { setViewBackground(view, viewNodeInfo); setViewForeground(view, viewNodeInfo); // when background outputs are disabled, they are wrapped by a ComponentHost. // A background can set the padding of a view, but ComponentHost should not have // any padding because the layout calculation has already accounted for padding by // translating the bounds of its children. if (isHostSpec) { view.setPadding(0, 0, 0, 0); } } if (!isHostSpec) { // Set view background, if applicable. Do this before padding // as it otherwise overrides the padding. setViewBackground(view, viewNodeInfo); setViewPadding(view, viewNodeInfo); setViewForeground(view, viewNodeInfo); setViewLayoutDirection(view, viewNodeInfo); } } } private static void setViewLayerType(final View view, final ViewNodeInfo info) { final int type = info.getLayerType(); if (type != LayerType.LAYER_TYPE_NOT_SET) { view.setLayerType(info.getLayerType(), info.getLayoutPaint()); } } private static void unsetViewLayerType(final View view, final int mountFlags) { int type = LithoMountData.getOriginalLayerType(mountFlags); if (type != LayerType.LAYER_TYPE_NOT_SET) { view.setLayerType(type, null); } } private static void maybeUnsetViewAttributes(MountItem item) { final LayoutOutput output = getLayoutOutput(item); final int flags = getMountData(item).getDefaultAttributeValuesFlags(); unsetViewAttributes(item.getContent(), output, flags); } static void unsetViewAttributes( final Object content, final LayoutOutput output, final int mountFlags) { final Component component = output.getComponent(); final boolean isHostView = isHostSpec(component); if (!isMountViewSpec(component)) { return; } final View view = (View) content; final NodeInfo nodeInfo = output.getNodeInfo(); if (nodeInfo != null) { if (nodeInfo.getClickHandler() != null) { unsetClickHandler(view); } if (nodeInfo.getLongClickHandler() != null) { unsetLongClickHandler(view); } if (nodeInfo.getFocusChangeHandler() != null) { unsetFocusChangeHandler(view); } if (nodeInfo.getTouchHandler() != null) { unsetTouchHandler(view); } if (nodeInfo.getInterceptTouchHandler() != null) { unsetInterceptTouchEventHandler(view); } unsetViewTag(view); unsetViewTags(view, nodeInfo.getViewTags()); unsetShadowElevation(view, nodeInfo.getShadowElevation()); unsetOutlineProvider(view, nodeInfo.getOutlineProvider()); unsetClipToOutline(view, nodeInfo.getClipToOutline()); unsetClipChildren(view, nodeInfo.getClipChildren()); if (!TextUtils.isEmpty(nodeInfo.getContentDescription())) { unsetContentDescription(view); } unsetScale(view, nodeInfo); unsetAlpha(view, nodeInfo); unsetRotation(view, nodeInfo); unsetRotationX(view, nodeInfo); unsetRotationY(view, nodeInfo); } view.setClickable(isViewClickable(mountFlags)); view.setLongClickable(isViewLongClickable(mountFlags)); unsetFocusable(view, mountFlags); unsetEnabled(view, mountFlags); unsetSelected(view, mountFlags); if (output.getImportantForAccessibility() != IMPORTANT_FOR_ACCESSIBILITY_AUTO) { unsetImportantForAccessibility(view); } unsetAccessibilityDelegate(view); final ViewNodeInfo viewNodeInfo = output.getViewNodeInfo(); if (viewNodeInfo != null) { unsetViewStateListAnimator(view, viewNodeInfo); // Host view doesn't set its own padding, but gets absolute positions for inner content from // Yoga. Also bg/fg is used as separate drawables instead of using View's bg/fg attribute. if (LayoutOutput.areDrawableOutputsDisabled(output.getFlags())) { unsetViewBackground(view, viewNodeInfo); unsetViewForeground(view, viewNodeInfo); } if (!isHostView) { unsetViewPadding(view, output, viewNodeInfo); unsetViewBackground(view, viewNodeInfo); unsetViewForeground(view, viewNodeInfo); unsetViewLayoutDirection(view); } } unsetViewLayerType(view, mountFlags); } /** * Store a {@link NodeInfo} as a tag in {@code view}. {@link LithoView} contains the logic for * setting/unsetting it whenever accessibility is enabled/disabled * * <p>For non {@link ComponentHost}s this is only done if any {@link EventHandler}s for * accessibility events have been implemented, we want to preserve the original behaviour since * {@code view} might have had a default delegate. */ private static void setAccessibilityDelegate(View view, NodeInfo nodeInfo) { if (!(view instanceof ComponentHost) && !nodeInfo.needsAccessibilityDelegate()) { return; } view.setTag(R.id.component_node_info, nodeInfo); } private static void unsetAccessibilityDelegate(View view) { if (!(view instanceof ComponentHost) && view.getTag(R.id.component_node_info) == null) { return; } view.setTag(R.id.component_node_info, null); if (!(view instanceof ComponentHost)) { ViewCompat.setAccessibilityDelegate(view, null); } } /** * Installs the click listeners that will dispatch the click handler defined in the component's * props. Unconditionally set the clickable flag on the view. */ private static void setClickHandler(@Nullable EventHandler<ClickEvent> clickHandler, View view) { if (clickHandler == null) { return; } ComponentClickListener listener = getComponentClickListener(view); if (listener == null) { listener = new ComponentClickListener(); setComponentClickListener(view, listener); } listener.setEventHandler(clickHandler); view.setClickable(true); } private static void unsetClickHandler(View view) { final ComponentClickListener listener = getComponentClickListener(view); if (listener != null) { listener.setEventHandler(null); } } @Nullable static ComponentClickListener getComponentClickListener(View v) { if (v instanceof ComponentHost) { return ((ComponentHost) v).getComponentClickListener(); } else { return (ComponentClickListener) v.getTag(R.id.component_click_listener); } } static void setComponentClickListener(View v, ComponentClickListener listener) { if (v instanceof ComponentHost) { ((ComponentHost) v).setComponentClickListener(listener); } else { v.setOnClickListener(listener); v.setTag(R.id.component_click_listener, listener); } } /** * Installs the long click listeners that will dispatch the click handler defined in the * component's props. Unconditionally set the clickable flag on the view. */ private static void setLongClickHandler( @Nullable EventHandler<LongClickEvent> longClickHandler, View view) { if (longClickHandler != null) { ComponentLongClickListener listener = getComponentLongClickListener(view); if (listener == null) { listener = new ComponentLongClickListener(); setComponentLongClickListener(view, listener); } listener.setEventHandler(longClickHandler); view.setLongClickable(true); } } private static void unsetLongClickHandler(View view) { final ComponentLongClickListener listener = getComponentLongClickListener(view); if (listener != null) { listener.setEventHandler(null); } } @Nullable static ComponentLongClickListener getComponentLongClickListener(View v) { if (v instanceof ComponentHost) { return ((ComponentHost) v).getComponentLongClickListener(); } else { return (ComponentLongClickListener) v.getTag(R.id.component_long_click_listener); } } static void setComponentLongClickListener(View v, ComponentLongClickListener listener) { if (v instanceof ComponentHost) { ((ComponentHost) v).setComponentLongClickListener(listener); } else { v.setOnLongClickListener(listener); v.setTag(R.id.component_long_click_listener, listener); } } /** * Installs the on focus change listeners that will dispatch the click handler defined in the * component's props. Unconditionally set the clickable flag on the view. */ private static void setFocusChangeHandler( @Nullable EventHandler<FocusChangedEvent> focusChangeHandler, View view) { if (focusChangeHandler == null) { return; } ComponentFocusChangeListener listener = getComponentFocusChangeListener(view); if (listener == null) { listener = new ComponentFocusChangeListener(); setComponentFocusChangeListener(view, listener); } listener.setEventHandler(focusChangeHandler); } private static void unsetFocusChangeHandler(View view) { final ComponentFocusChangeListener listener = getComponentFocusChangeListener(view); if (listener != null) { listener.setEventHandler(null); } } static ComponentFocusChangeListener getComponentFocusChangeListener(View v) { if (v instanceof ComponentHost) { return ((ComponentHost) v).getComponentFocusChangeListener(); } else { return (ComponentFocusChangeListener) v.getTag(R.id.component_focus_change_listener); } } static void setComponentFocusChangeListener(View v, ComponentFocusChangeListener listener) { if (v instanceof ComponentHost) { ((ComponentHost) v).setComponentFocusChangeListener(listener); } else { v.setOnFocusChangeListener(listener); v.setTag(R.id.component_focus_change_listener, listener); } } /** * Installs the touch listeners that will dispatch the touch handler defined in the component's * props. */ private static void setTouchHandler(@Nullable EventHandler<TouchEvent> touchHandler, View view) { if (touchHandler != null) { ComponentTouchListener listener = getComponentTouchListener(view); if (listener == null) { listener = new ComponentTouchListener(); setComponentTouchListener(view, listener); } listener.setEventHandler(touchHandler); } } private static void unsetTouchHandler(View view) { final ComponentTouchListener listener = getComponentTouchListener(view); if (listener != null) { listener.setEventHandler(null); } } /** Sets the intercept touch handler defined in the component's props. */ private static void setInterceptTouchHandler( @Nullable EventHandler<InterceptTouchEvent> interceptTouchHandler, View view) { if (interceptTouchHandler == null) { return; } if (view instanceof ComponentHost) { ((ComponentHost) view).setInterceptTouchEventHandler(interceptTouchHandler); } } private static void unsetInterceptTouchEventHandler(View view) { if (view instanceof ComponentHost) { ((ComponentHost) view).setInterceptTouchEventHandler(null); } } @Nullable static ComponentTouchListener getComponentTouchListener(View v) { if (v instanceof ComponentHost) { return ((ComponentHost) v).getComponentTouchListener(); } else { return (ComponentTouchListener) v.getTag(R.id.component_touch_listener); } } static void setComponentTouchListener(View v, ComponentTouchListener listener) { if (v instanceof ComponentHost) { ((ComponentHost) v).setComponentTouchListener(listener); } else { v.setOnTouchListener(listener); v.setTag(R.id.component_touch_listener, listener); } } private static void setViewTag(View view, @Nullable Object viewTag) { view.setTag(viewTag); } private static void setViewTags(View view, @Nullable SparseArray<Object> viewTags) { if (viewTags == null) { return; } if (view instanceof ComponentHost) { final ComponentHost host = (ComponentHost) view; host.setViewTags(viewTags); } else { for (int i = 0, size = viewTags.size(); i < size; i++) { view.setTag(viewTags.keyAt(i), viewTags.valueAt(i)); } } } private static void unsetViewTag(View view) { view.setTag(null); } private static void unsetViewTags(View view, @Nullable SparseArray<Object> viewTags) { if (view instanceof ComponentHost) { final ComponentHost host = (ComponentHost) view; host.setViewTags(null); } else { if (viewTags != null) { for (int i = 0, size = viewTags.size(); i < size; i++) { view.setTag(viewTags.keyAt(i), null); } } } } private static void setShadowElevation(View view, float shadowElevation) { if (shadowElevation != 0) { ViewCompat.setElevation(view, shadowElevation); } } private static void unsetShadowElevation(View view, float shadowElevation) { if (shadowElevation != 0) { ViewCompat.setElevation(view, 0); } } private static void setOutlineProvider(View view, @Nullable ViewOutlineProvider outlineProvider) { if (outlineProvider != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { view.setOutlineProvider(outlineProvider); } } private static void unsetOutlineProvider( View view, @Nullable ViewOutlineProvider outlineProvider) { if (outlineProvider != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { view.setOutlineProvider(ViewOutlineProvider.BACKGROUND); } } private static void setClipToOutline(View view, boolean clipToOutline) { if (clipToOutline && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { view.setClipToOutline(clipToOutline); } } private static void unsetClipToOutline(View view, boolean clipToOutline) { if (clipToOutline && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { view.setClipToOutline(false); } } private static void setClipChildren(View view, NodeInfo nodeInfo) { if (nodeInfo.isClipChildrenSet() && view instanceof ViewGroup) { ((ViewGroup) view).setClipChildren(nodeInfo.getClipChildren()); } } private static void unsetClipChildren(View view, boolean clipChildren) { if (!clipChildren && view instanceof ViewGroup) { // Default value for clipChildren is 'true'. // If this ViewGroup had clipChildren set to 'false' before mounting we would reset this // property here on recycling. ((ViewGroup) view).setClipChildren(true); } } private static void setContentDescription(View view, @Nullable CharSequence contentDescription) { if (TextUtils.isEmpty(contentDescription)) { return; } view.setContentDescription(contentDescription); } private static void unsetContentDescription(View view) { view.setContentDescription(null); } private static void setImportantForAccessibility(View view, int importantForAccessibility) { if (importantForAccessibility == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { return; } ViewCompat.setImportantForAccessibility(view, importantForAccessibility); } private static void unsetImportantForAccessibility(View view) { ViewCompat.setImportantForAccessibility(view, IMPORTANT_FOR_ACCESSIBILITY_AUTO); } private static void setFocusable(View view, @NodeInfo.FocusState int focusState) { if (focusState == NodeInfo.FOCUS_SET_TRUE) { view.setFocusable(true); } else if (focusState == NodeInfo.FOCUS_SET_FALSE) { view.setFocusable(false); } } private static void unsetFocusable(View view, int flags) { view.setFocusable(isViewFocusable(flags)); } private static void setTransitionName(View view, @Nullable String transitionName) { ViewCompat.setTransitionName(view, transitionName); } private static void setClickable(View view, @NodeInfo.FocusState int clickableState) { if (clickableState == NodeInfo.CLICKABLE_SET_TRUE) { view.setClickable(true); } else if (clickableState == NodeInfo.CLICKABLE_SET_FALSE) { view.setClickable(false); } } private static void setEnabled(View view, @NodeInfo.EnabledState int enabledState) { if (enabledState == NodeInfo.ENABLED_SET_TRUE) { view.setEnabled(true); } else if (enabledState == NodeInfo.ENABLED_SET_FALSE) { view.setEnabled(false); } } private static void unsetEnabled(View view, int flags) { view.setEnabled(isViewEnabled(flags)); } private static void setSelected(View view, @NodeInfo.SelectedState int selectedState) { if (selectedState == NodeInfo.SELECTED_SET_TRUE) { view.setSelected(true); } else if (selectedState == NodeInfo.SELECTED_SET_FALSE) { view.setSelected(false); } } private static void unsetSelected(View view, int flags) { view.setSelected(isViewSelected(flags)); } private static void setScale(View view, NodeInfo nodeInfo) { if (nodeInfo.isScaleSet()) { final float scale = nodeInfo.getScale(); view.setScaleX(scale); view.setScaleY(scale); } } private static void unsetScale(View view, NodeInfo nodeInfo) { if (nodeInfo.isScaleSet()) { if (view.getScaleX() != 1) { view.setScaleX(1); } if (view.getScaleY() != 1) { view.setScaleY(1); } } } private static void setAlpha(View view, NodeInfo nodeInfo) { if (nodeInfo.isAlphaSet()) { view.setAlpha(nodeInfo.getAlpha()); } } private static void unsetAlpha(View view, NodeInfo nodeInfo) { if (nodeInfo.isAlphaSet() && view.getAlpha() != 1) { view.setAlpha(1); } } private static void setRotation(View view, NodeInfo nodeInfo) { if (nodeInfo.isRotationSet()) { view.setRotation(nodeInfo.getRotation()); } } private static void unsetRotation(View view, NodeInfo nodeInfo) { if (nodeInfo.isRotationSet() && view.getRotation() != 0) { view.setRotation(0); } } private static void setRotationX(View view, NodeInfo nodeInfo) { if (nodeInfo.isRotationXSet()) { view.setRotationX(nodeInfo.getRotationX()); } } private static void unsetRotationX(View view, NodeInfo nodeInfo) { if (nodeInfo.isRotationXSet() && view.getRotationX() != 0) { view.setRotationX(0); } } private static void setRotationY(View view, NodeInfo nodeInfo) { if (nodeInfo.isRotationYSet()) { view.setRotationY(nodeInfo.getRotationY()); } } private static void unsetRotationY(View view, NodeInfo nodeInfo) { if (nodeInfo.isRotationYSet() && view.getRotationY() != 0) { view.setRotationY(0); } } private static void setViewPadding(View view, ViewNodeInfo viewNodeInfo) { if (!viewNodeInfo.hasPadding()) { return; } view.setPadding( viewNodeInfo.getPaddingLeft(), viewNodeInfo.getPaddingTop(), viewNodeInfo.getPaddingRight(), viewNodeInfo.getPaddingBottom()); } private static void unsetViewPadding(View view, LayoutOutput output, ViewNodeInfo viewNodeInfo) { if (!viewNodeInfo.hasPadding()) { return; } try { view.setPadding(0, 0, 0, 0); } catch (NullPointerException e) { // T53931759 Gathering extra info around this NPE ErrorReporter.getInstance() .report( LogLevel.ERROR, "LITHO:NPE:UNSET_PADDING", "From component: " + output.getComponent().getSimpleName(), e, 0, null); } } private static void setViewBackground(View view, ViewNodeInfo viewNodeInfo) { final Drawable background = viewNodeInfo.getBackground(); if (background != null) { setBackgroundCompat(view, background); } } private static void unsetViewBackground(View view, ViewNodeInfo viewNodeInfo) { final Drawable background = viewNodeInfo.getBackground(); if (background != null) { setBackgroundCompat(view, null); } } @SuppressWarnings("deprecation") private static void setBackgroundCompat(View view, Drawable drawable) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { view.setBackgroundDrawable(drawable); } else { view.setBackground(drawable); } } private static void setViewForeground(View view, ViewNodeInfo viewNodeInfo) { final Drawable foreground = viewNodeInfo.getForeground(); if (foreground != null) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { throw new IllegalStateException( "MountState has a ViewNodeInfo with foreground however " + "the current Android version doesn't support foreground on Views"); } view.setForeground(foreground); } } private static void unsetViewForeground(View view, ViewNodeInfo viewNodeInfo) { final Drawable foreground = viewNodeInfo.getForeground(); if (foreground != null) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { throw new IllegalStateException( "MountState has a ViewNodeInfo with foreground however " + "the current Android version doesn't support foreground on Views"); } view.setForeground(null); } } private static void setViewLayoutDirection(View view, ViewNodeInfo viewNodeInfo) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { return; } final int viewLayoutDirection; switch (viewNodeInfo.getLayoutDirection()) { case LTR: viewLayoutDirection = View.LAYOUT_DIRECTION_LTR; break; case RTL: viewLayoutDirection = View.LAYOUT_DIRECTION_RTL; break; default: viewLayoutDirection = View.LAYOUT_DIRECTION_INHERIT; } view.setLayoutDirection(viewLayoutDirection); } private static void unsetViewLayoutDirection(View view) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { return; } view.setLayoutDirection(View.LAYOUT_DIRECTION_INHERIT); } private static void setViewStateListAnimator(View view, ViewNodeInfo viewNodeInfo) { StateListAnimator stateListAnimator = viewNodeInfo.getStateListAnimator(); final int stateListAnimatorRes = viewNodeInfo.getStateListAnimatorRes(); if (stateListAnimator == null && stateListAnimatorRes == 0) { return; } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { throw new IllegalStateException( "MountState has a ViewNodeInfo with stateListAnimator, " + "however the current Android version doesn't support stateListAnimator on Views"); } if (stateListAnimator == null) { stateListAnimator = AnimatorInflater.loadStateListAnimator(view.getContext(), stateListAnimatorRes); } view.setStateListAnimator(stateListAnimator); } private static void unsetViewStateListAnimator(View view, ViewNodeInfo viewNodeInfo) { if (viewNodeInfo.getStateListAnimator() == null && viewNodeInfo.getStateListAnimatorRes() == 0) { return; } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { throw new IllegalStateException( "MountState has a ViewNodeInfo with stateListAnimator, " + "however the current Android version doesn't support stateListAnimator on Views"); } view.setStateListAnimator(null); } private static void mountItemIncrementally(MountItem item, boolean processVisibilityOutputs) { final Component component = getLayoutOutput(item).getComponent(); if (!isMountViewSpec(component)) { return; } // We can't just use the bounds of the View since we need the bounds relative to the // hosting LithoView (which is what the localVisibleRect is measured relative to). final View view = (View) item.getContent(); mountViewIncrementally(view, processVisibilityOutputs); } private static void mountViewIncrementally(View view, boolean processVisibilityOutputs) { assertMainThread(); if (view instanceof LithoView) { final LithoView lithoView = (LithoView) view; if (lithoView.isIncrementalMountEnabled()) { if (!processVisibilityOutputs) { lithoView.notifyVisibleBoundsChanged( new Rect(0, 0, view.getWidth(), view.getHeight()), false); } else { lithoView.notifyVisibleBoundsChanged(); } } } else if (view instanceof RenderCoreExtensionHost) { ((RenderCoreExtensionHost) view).notifyVisibleBoundsChanged(); } else if (view instanceof ViewGroup) { final ViewGroup viewGroup = (ViewGroup) view; for (int i = 0; i < viewGroup.getChildCount(); i++) { final View childView = viewGroup.getChildAt(i); mountViewIncrementally(childView, processVisibilityOutputs); } } } private String getMountItemDebugMessage(MountItem item) { final int index = mIndexToItemMap.indexOfValue(item); long id = -1; int layoutOutputIndex = -1; if (index > -1) { id = mIndexToItemMap.keyAt(index); for (int i = 0; i < mLayoutOutputsIds.length; i++) { if (id == mLayoutOutputsIds[i]) { layoutOutputIndex = i; break; } } } final ComponentTree componentTree = mLithoView.getComponentTree(); final String rootComponent = componentTree == null ? "<null_component_tree>" : componentTree.getRoot().getSimpleName(); return "rootComponent=" + rootComponent + ", index=" + layoutOutputIndex + ", mapIndex=" + index + ", id=" + id + ", disappearRange=[" + mLastDisappearRangeStart + "," + mLastDisappearRangeEnd + "], contentType=" + (item.getContent() != null ? item.getContent().getClass() : "<null_content>") + ", component=" + getLayoutOutput(item).getComponent().getSimpleName() + ", host=" + (item.getHost() != null ? item.getHost().getClass() : "<null_host>") + ", isRootHost=" + (mHostsByMarker.get(ROOT_HOST_ID) == item.getHost()); } @Override public void unmountAllItems() { assertMainThread(); if (mLayoutOutputsIds == null) { return; } for (int i = mLayoutOutputsIds.length - 1; i >= 0; i--) { unmountItem(i, mHostsByMarker); } mPreviousLocalVisibleRect.setEmpty(); mNeedsRemount = true; if (mMountDelegate != null) { mMountDelegate.releaseAllAcquiredReferences(); } if (mVisibilityExtension != null) { mVisibilityExtension.onUnmount(mVisibilityExtensionState); } if (mTransitionsExtension != null) { mTransitionsExtension.onUnmount(mTransitionsExtensionState); } clearLastMountedTree(); clearVisibilityItems(); } private void unmountItem(int index, LongSparseArray<ComponentHost> hostsByMarker) { final MountItem item = getItemAt(index); final long startTime = System.nanoTime(); // Already has been unmounted. if (item == null) { return; } // The root host item should never be unmounted as it's a reference // to the top-level LithoView. if (mLayoutOutputsIds[index] == ROOT_HOST_ID) { maybeUnsetViewAttributes(item); return; } final long layoutOutputId = mLayoutOutputsIds[index]; mIndexToItemMap.remove(layoutOutputId); final Object content = item.getContent(); final boolean hasUnmountDelegate = mUnmountDelegateExtension != null && mUnmountDelegateExtension.shouldDelegateUnmount( mMountDelegate.getUnmountDelegateExtensionState(), item); // Recursively unmount mounted children items. // This is the case when mountDiffing is enabled and unmountOrMoveOldItems() has a matching // sub tree. However, traversing the tree bottom-up, it needs to unmount a node holding that // sub tree, that will still have mounted items. (Different sequence number on LayoutOutput id) if ((content instanceof ComponentHost) && !(content instanceof LithoView)) { final ComponentHost host = (ComponentHost) content; // Concurrently remove items therefore traverse backwards. for (int i = host.getMountItemCount() - 1; i >= 0; i--) { final MountItem mountItem = host.getMountItemAt(i); if (mIndexToItemMap.indexOfValue(mountItem) == -1) { final LayoutOutput output = getLayoutOutput(mountItem); final Component component = output.getComponent(); ComponentsReporter.emitMessage( ComponentsReporter.LogLevel.ERROR, "UnmountItem:ChildNotFound", "Child of mount item not found in MountSate mIndexToItemMap" + ", child_component: " + component.getSimpleName()); } final long childLayoutOutputId = mIndexToItemMap.keyAt(mIndexToItemMap.indexOfValue(mountItem)); for (int mountIndex = mLayoutOutputsIds.length - 1; mountIndex >= 0; mountIndex--) { if (mLayoutOutputsIds[mountIndex] == childLayoutOutputId) { unmountItem(mountIndex, hostsByMarker); break; } } } if (!hasUnmountDelegate && host.getMountItemCount() > 0) { final LayoutOutput output = getLayoutOutput(item); final Component component = output.getComponent(); ComponentsReporter.emitMessage( ComponentsReporter.LogLevel.ERROR, "UnmountItem:ChildsNotUnmounted", "Recursively unmounting items from a ComponentHost, left some items behind maybe because not tracked by its MountState" + ", component: " + component.getSimpleName()); throw new IllegalStateException( "Recursively unmounting items from a ComponentHost, left" + " some items behind maybe because not tracked by its MountState"); } } final ComponentHost host = (ComponentHost) item.getHost(); final LayoutOutput output = getLayoutOutput(item); final Component component = output.getComponent(); if (component.hasChildLithoViews()) { mCanMountIncrementallyMountItems.delete(mLayoutOutputsIds[index]); } if (isHostSpec(component)) { final ComponentHost componentHost = (ComponentHost) content; hostsByMarker.removeAt(hostsByMarker.indexOfValue(componentHost)); } if (hasUnmountDelegate) { mUnmountDelegateExtension.unmount( mMountDelegate.getUnmountDelegateExtensionState(), item, host); } else { /* * The mounted content might contain other LithoViews which are not reachable from * this MountState. If that content contains other LithoViews, we need to unmount them as well, * so that their contents are recycled and reused next time. */ if (content instanceof HasLithoViewChildren) { final ArrayList<LithoView> lithoViews = new ArrayList<>(); ((HasLithoViewChildren) content).obtainLithoViewChildren(lithoViews); for (int i = lithoViews.size() - 1; i >= 0; i--) { final LithoView lithoView = lithoViews.get(i); lithoView.unmountAllItems(); } } unmount(host, index, content, item, output); unbindMountItem(item); } if (mMountStats.isLoggingEnabled) { mMountStats.unmountedTimes.add((System.nanoTime() - startTime) / NS_IN_MS); mMountStats.unmountedNames.add(component.getSimpleName()); mMountStats.unmountedCount++; } } @Override public void unbindMountItem(MountItem mountItem) { final LayoutOutput output = getLayoutOutput(mountItem); maybeUnsetViewAttributes(mountItem); unbindAndUnmountLifecycle(mountItem); applyUnbindBinders(output, mountItem); try { getMountData(mountItem) .releaseMountContent( mContext.getAndroidContext(), mountItem, "unmountItem", mRecyclingMode); } catch (LithoMountData.ReleasingReleasedMountContentException e) { throw new RuntimeException(e.getMessage() + " " + getMountItemDebugMessage(mountItem)); } } private void unbindAndUnmountLifecycle(MountItem item) { final LayoutOutput layoutOutput = getLayoutOutput(item); final Component component = layoutOutput.getComponent(); final Object content = item.getContent(); final ComponentContext context = getContextForComponent(item.getRenderTreeNode()); // Call the component's unmount() method. if (item.isBound()) { unbindComponentFromContent(item, component, content); } if (mRecyclingMode != ComponentTree.RecyclingMode.NO_UNMOUNTING) { final LithoLayoutData layoutData = (LithoLayoutData) item.getRenderTreeNode().getLayoutData(); component.unmount(context, content, layoutData.interStagePropsContainer); } } @Override public boolean isRootItem(int position) { final MountItem mountItem = getItemAt(position); if (mountItem == null) { return false; } return mountItem == mIndexToItemMap.get(ROOT_HOST_ID); } @Override public @Nullable MountItem getRootItem() { return mIndexToItemMap != null ? mIndexToItemMap.get(ROOT_HOST_ID) : null; } @Nullable MountItem getItemAt(int i) { assertMainThread(); // TODO simplify when replacing with getContent. if (mIndexToItemMap == null || mLayoutOutputsIds == null) { return null; } if (i >= mLayoutOutputsIds.length) { return null; } return mIndexToItemMap.get(mLayoutOutputsIds[i]); } @Override public Object getContentAt(int i) { final MountItem mountItem = getItemAt(i); if (mountItem == null) { return null; } return mountItem.getContent(); } @Nullable @Override public Object getContentById(long id) { if (mIndexToItemMap == null) { return null; } final MountItem mountItem = mIndexToItemMap.get(id); if (mountItem == null) { return null; } return mountItem.getContent(); } public androidx.collection.LongSparseArray<MountItem> getIndexToItemMap() { return mIndexToItemMap; } public void clearLastMountedTree() { if (mTransitionsExtension != null) { mTransitionsExtension.clearLastMountedTreeId(mTransitionsExtensionState); } mLastMountedComponentTreeId = ComponentTree.INVALID_ID; } private static class PrepareMountStats { private int unmountedCount = 0; private int movedCount = 0; private int unchangedCount = 0; private PrepareMountStats() {} private void reset() { unchangedCount = 0; movedCount = 0; unmountedCount = 0; } } private static class MountStats { private List<String> mountedNames; private List<String> unmountedNames; private List<String> updatedNames; private List<String> visibilityHandlerNames; private List<String> extras; private List<Double> mountTimes; private List<Double> unmountedTimes; private List<Double> updatedTimes; private List<Double> visibilityHandlerTimes; private int mountedCount; private int unmountedCount; private int updatedCount; private int noOpCount; private double visibilityHandlersTotalTime; private boolean isLoggingEnabled; private boolean isInitialized; private void enableLogging() { isLoggingEnabled = true; if (!isInitialized) { isInitialized = true; mountedNames = new ArrayList<>(); unmountedNames = new ArrayList<>(); updatedNames = new ArrayList<>(); visibilityHandlerNames = new ArrayList<>(); extras = new ArrayList<>(); mountTimes = new ArrayList<>(); unmountedTimes = new ArrayList<>(); updatedTimes = new ArrayList<>(); visibilityHandlerTimes = new ArrayList<>(); } } private void reset() { mountedCount = 0; unmountedCount = 0; updatedCount = 0; noOpCount = 0; visibilityHandlersTotalTime = 0; if (isInitialized) { mountedNames.clear(); unmountedNames.clear(); updatedNames.clear(); visibilityHandlerNames.clear(); extras.clear(); mountTimes.clear(); unmountedTimes.clear(); updatedTimes.clear(); visibilityHandlerTimes.clear(); } isLoggingEnabled = false; } } /** * Unbinds all the MountItems currently mounted on this MountState. Unbinding a MountItem means * calling unbind on its {@link Component}. The MountItem is not yet unmounted after unbind is * called and can be re-used in place to re-mount another {@link Component} with the same {@link * Component}. */ void unbind() { assertMainThread(); if (mLayoutOutputsIds == null) { return; } boolean isTracing = ComponentsSystrace.isTracing(); if (isTracing) { ComponentsSystrace.beginSection("MountState.unbind"); } for (int i = 0, size = mLayoutOutputsIds.length; i < size; i++) { MountItem mountItem = getItemAt(i); if (mountItem == null || !mountItem.isBound()) { continue; } unbindComponentFromContent( mountItem, getLayoutOutput(mountItem).getComponent(), mountItem.getContent()); } clearVisibilityItems(); if (mVisibilityExtension != null) { mVisibilityExtension.onUnbind(mVisibilityExtensionState); } if (mTransitionsExtension != null) { mTransitionsExtension.onUnbind(mTransitionsExtensionState); } if (isTracing) { ComponentsSystrace.endSection(); } } @Override public void detach() { assertMainThread(); unbind(); } @Override public void attach() { rebind(); } /** * This is called when the {@link MountItem}s mounted on this {@link MountState} need to be * re-bound with the same component. The common case here is a detach/attach happens on the {@link * LithoView} that owns the MountState. */ void rebind() { assertMainThread(); if (mLayoutOutputsIds == null) { return; } for (int i = 0, size = mLayoutOutputsIds.length; i < size; i++) { final MountItem mountItem = getItemAt(i); if (mountItem == null || mountItem.isBound()) { continue; } final Component component = getLayoutOutput(mountItem).getComponent(); final Object content = mountItem.getContent(); final LithoLayoutData layoutData = (LithoLayoutData) mountItem.getRenderTreeNode().getLayoutData(); bindComponentToContent( mountItem, component, getComponentContext(mountItem), layoutData, content); if (content instanceof View && !(content instanceof ComponentHost) && ((View) content).isLayoutRequested()) { final View view = (View) content; applyBoundsToMountContent( view, view.getLeft(), view.getTop(), view.getRight(), view.getBottom(), true); } } } private boolean isAnimationLocked(RenderTreeNode renderTreeNode) { if (mTransitionsExtension != null) { if (mTransitionsExtensionState == null) { throw new IllegalStateException("Need a state when using the TransitionsExtension."); } return mTransitionsExtensionState.ownsReference(renderTreeNode.getRenderUnit().getId()); } return false; } /** * @return true if this method did all the work that was necessary and there is no other content * that needs mounting/unmounting in this mount step. If false then a full mount step should * take place. */ private boolean performIncrementalMount( LayoutState layoutState, Rect localVisibleRect, boolean processVisibilityOutputs) { if (mPreviousLocalVisibleRect.isEmpty()) { return false; } if (localVisibleRect.left != mPreviousLocalVisibleRect.left || localVisibleRect.right != mPreviousLocalVisibleRect.right) { return false; } final ArrayList<IncrementalMountOutput> layoutOutputTops = layoutState.getOutputsOrderedByTopBounds(); final ArrayList<IncrementalMountOutput> layoutOutputBottoms = layoutState.getOutputsOrderedByBottomBounds(); final int count = layoutState.getMountableOutputCount(); if (localVisibleRect.top >= 0 || mPreviousLocalVisibleRect.top >= 0) { // View is going on/off the top of the screen. Check the bottoms to see if there is anything // that has moved on/off the top of the screen. while (mPreviousBottomsIndex < count && localVisibleRect.top >= layoutOutputBottoms.get(mPreviousBottomsIndex).getBounds().bottom) { final RenderTreeNode node = layoutState.getRenderTreeNode(layoutOutputBottoms.get(mPreviousBottomsIndex)); final long id = node.getRenderUnit().getId(); final int layoutOutputIndex = layoutState.getPositionForId(id); if (!isAnimationLocked(node)) { unmountItem(layoutOutputIndex, mHostsByMarker); } mPreviousBottomsIndex++; } while (mPreviousBottomsIndex > 0 && localVisibleRect.top <= layoutOutputBottoms.get(mPreviousBottomsIndex - 1).getBounds().bottom) { mPreviousBottomsIndex--; final RenderTreeNode node = layoutState.getRenderTreeNode(layoutOutputBottoms.get(mPreviousBottomsIndex)); final LayoutOutput layoutOutput = getLayoutOutput(node); final int layoutOutputIndex = layoutState.getPositionForId(node.getRenderUnit().getId()); if (getItemAt(layoutOutputIndex) == null) { mountLayoutOutput( layoutState.getPositionForId(node.getRenderUnit().getId()), node, layoutOutput, layoutState); mComponentIdsMountedInThisFrame.add(node.getRenderUnit().getId()); } } } final int height = mLithoView.getHeight(); if (localVisibleRect.bottom < height || mPreviousLocalVisibleRect.bottom < height) { // View is going on/off the bottom of the screen. Check the tops to see if there is anything // that has changed. while (mPreviousTopsIndex < count && localVisibleRect.bottom >= layoutOutputTops.get(mPreviousTopsIndex).getBounds().top) { final RenderTreeNode node = layoutState.getRenderTreeNode(layoutOutputTops.get(mPreviousTopsIndex)); final LayoutOutput layoutOutput = getLayoutOutput(node); final int layoutOutputIndex = layoutState.getPositionForId(node.getRenderUnit().getId()); if (getItemAt(layoutOutputIndex) == null) { mountLayoutOutput( layoutState.getPositionForId(node.getRenderUnit().getId()), node, layoutOutput, layoutState); mComponentIdsMountedInThisFrame.add(node.getRenderUnit().getId()); } mPreviousTopsIndex++; } while (mPreviousTopsIndex > 0 && localVisibleRect.bottom < layoutOutputTops.get(mPreviousTopsIndex - 1).getBounds().top) { mPreviousTopsIndex--; final RenderTreeNode node = layoutState.getRenderTreeNode(layoutOutputTops.get(mPreviousTopsIndex)); final long id = node.getRenderUnit().getId(); final int layoutOutputIndex = layoutState.getPositionForId(id); if (!isAnimationLocked(node)) { unmountItem(layoutOutputIndex, mHostsByMarker); } } } for (int i = 0, size = mCanMountIncrementallyMountItems.size(); i < size; i++) { final MountItem mountItem = mCanMountIncrementallyMountItems.valueAt(i); final long layoutOutputId = mCanMountIncrementallyMountItems.keyAt(i); if (!mComponentIdsMountedInThisFrame.contains(layoutOutputId)) { final int layoutOutputPosition = layoutState.getPositionForId(layoutOutputId); if (layoutOutputPosition != -1) { mountItemIncrementally(mountItem, processVisibilityOutputs); } } } mComponentIdsMountedInThisFrame.clear(); return true; } /** * Collect transitions from layout time, mount time and from state updates. * * @param layoutState that is going to be mounted. */ void collectAllTransitions(LayoutState layoutState, ComponentTree componentTree) { assertMainThread(); if (mTransitionsExtension != null) { TransitionsExtension.collectAllTransitions(mTransitionsExtensionState, layoutState); return; } } /** @see LithoViewTestHelper#findTestItems(LithoView, String) */ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) Deque<TestItem> findTestItems(String testKey) { if (mTestItemMap == null) { throw new UnsupportedOperationException( "Trying to access TestItems while " + "ComponentsConfiguration.isEndToEndTestRun is false."); } final Deque<TestItem> items = mTestItemMap.get(testKey); return items == null ? new LinkedList<TestItem>() : items; } /** * For HostComponents, we don't set a scoped context during layout calculation because we don't * need one, as we could never call a state update on it. Instead it's okay to use the context * that is passed to MountState from the LithoView, which is not scoped. */ private ComponentContext getContextForComponent(RenderTreeNode node) { ComponentContext c = getComponentContext(node); return c == null ? mContext : c; } private void bindComponentToContent( final MountItem mountItem, final Component component, final ComponentContext context, final LithoLayoutData layoutData, final Object content) { component.bind( getContextForComponent(mountItem.getRenderTreeNode()), content, layoutData.interStagePropsContainer); mDynamicPropsManager.onBindComponentToContent(component, context, content); mountItem.setIsBound(true); } private void unbindComponentFromContent( MountItem mountItem, Component component, Object content) { mDynamicPropsManager.onUnbindComponent(component, content); RenderTreeNode node = mountItem.getRenderTreeNode(); component.unbind( getContextForComponent(node), content, ((LithoLayoutData) node.getLayoutData()).interStagePropsContainer); mountItem.setIsBound(false); } @VisibleForTesting DynamicPropsManager getDynamicPropsManager() { return mDynamicPropsManager; } }
Don't process visibility for dirty mounts if it's disabled Summary: we check `processVisibilityOutputs` for incremental mount and not process visibility, but we don't check it for dirty mounts. Differential Revision: D32205872 fbshipit-source-id: edb246a76238f992592293b6e4999a5dc656ec9b
litho-core/src/main/java/com/facebook/litho/MountState.java
Don't process visibility for dirty mounts if it's disabled
<ide><path>itho-core/src/main/java/com/facebook/litho/MountState.java <ide> LayoutState layoutState, @Nullable Rect localVisibleRect, boolean processVisibilityOutputs) { <ide> final ComponentTree componentTree = mLithoView.getComponentTree(); <ide> final boolean isIncrementalMountEnabled = componentTree.isIncrementalMountEnabled(); <del> final boolean isVisibilityProcessingEnabled = componentTree.isVisibilityProcessingEnabled(); <add> final boolean isVisibilityProcessingEnabled = <add> componentTree.isVisibilityProcessingEnabled() && processVisibilityOutputs; <ide> <ide> assertMainThread(); <ide>
Java
bsd-3-clause
c856d378dd6f34ffd56f67d9e6c62ff9d2ba4eed
0
Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo
package org.caleydo.view.parcoords; import static org.caleydo.view.parcoords.PCRenderStyle.ANGLUAR_LINE_WIDTH; import static org.caleydo.view.parcoords.PCRenderStyle.ANGULAR_COLOR; import static org.caleydo.view.parcoords.PCRenderStyle.ANGULAR_POLYGON_COLOR; import static org.caleydo.view.parcoords.PCRenderStyle.AXIS_MARKER_WIDTH; import static org.caleydo.view.parcoords.PCRenderStyle.AXIS_Z; import static org.caleydo.view.parcoords.PCRenderStyle.LABEL_Z; import static org.caleydo.view.parcoords.PCRenderStyle.NAN_Y_OFFSET; import static org.caleydo.view.parcoords.PCRenderStyle.NUMBER_AXIS_MARKERS; import static org.caleydo.view.parcoords.PCRenderStyle.X_AXIS_COLOR; import static org.caleydo.view.parcoords.PCRenderStyle.X_AXIS_LINE_WIDTH; import static org.caleydo.view.parcoords.PCRenderStyle.Y_AXIS_COLOR; import static org.caleydo.view.parcoords.PCRenderStyle.Y_AXIS_LINE_WIDTH; import static org.caleydo.view.parcoords.PCRenderStyle.Y_AXIS_LOW; import static org.caleydo.view.parcoords.PCRenderStyle.Y_AXIS_MOUSE_OVER_LINE_WIDTH; import static org.caleydo.view.parcoords.PCRenderStyle.Y_AXIS_SELECTED_LINE_WIDTH; import gleem.linalg.Rotf; import gleem.linalg.Vec3f; import java.awt.Point; import java.awt.Rectangle; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.management.InvalidAttributeValueException; import javax.media.opengl.GL; import org.caleydo.core.command.ECommandType; import org.caleydo.core.command.view.opengl.CmdCreateView; import org.caleydo.core.data.collection.INominalStorage; import org.caleydo.core.data.collection.INumericalStorage; import org.caleydo.core.data.collection.ISet; import org.caleydo.core.data.collection.IStorage; import org.caleydo.core.data.collection.storage.EDataRepresentation; import org.caleydo.core.data.mapping.EIDCategory; import org.caleydo.core.data.mapping.EIDType; import org.caleydo.core.data.selection.ContentVAType; import org.caleydo.core.data.selection.ESelectionCommandType; import org.caleydo.core.data.selection.EVAOperation; import org.caleydo.core.data.selection.SelectedElementRep; import org.caleydo.core.data.selection.SelectionCommand; import org.caleydo.core.data.selection.SelectionType; import org.caleydo.core.data.selection.StorageVAType; import org.caleydo.core.data.selection.delta.ContentVADelta; import org.caleydo.core.data.selection.delta.ISelectionDelta; import org.caleydo.core.data.selection.delta.SelectionDelta; import org.caleydo.core.data.selection.delta.StorageVADelta; import org.caleydo.core.data.selection.delta.VADeltaItem; import org.caleydo.core.manager.datadomain.EDataFilterLevel; import org.caleydo.core.manager.event.data.BookmarkEvent; import org.caleydo.core.manager.event.data.ReplaceContentVAInUseCaseEvent; import org.caleydo.core.manager.event.view.ResetAllViewsEvent; import org.caleydo.core.manager.event.view.infoarea.InfoAreaUpdateEvent; import org.caleydo.core.manager.event.view.storagebased.AngularBrushingEvent; import org.caleydo.core.manager.event.view.storagebased.ApplyCurrentSelectionToVirtualArrayEvent; import org.caleydo.core.manager.event.view.storagebased.BookmarkButtonEvent; import org.caleydo.core.manager.event.view.storagebased.ContentVAUpdateEvent; import org.caleydo.core.manager.event.view.storagebased.ResetAxisSpacingEvent; import org.caleydo.core.manager.event.view.storagebased.ResetParallelCoordinatesEvent; import org.caleydo.core.manager.event.view.storagebased.SelectionUpdateEvent; import org.caleydo.core.manager.event.view.storagebased.StorageVAUpdateEvent; import org.caleydo.core.manager.event.view.storagebased.UpdateViewEvent; import org.caleydo.core.manager.event.view.storagebased.UseRandomSamplingEvent; import org.caleydo.core.manager.id.EManagedObjectType; import org.caleydo.core.manager.picking.EPickingMode; import org.caleydo.core.manager.picking.EPickingType; import org.caleydo.core.manager.picking.Pick; import org.caleydo.core.manager.view.StandardTransformer; import org.caleydo.core.serialize.ASerializedView; import org.caleydo.core.util.format.Formatter; import org.caleydo.core.util.preferences.PreferenceConstants; import org.caleydo.core.view.opengl.camera.EProjectionMode; import org.caleydo.core.view.opengl.camera.IViewFrustum; import org.caleydo.core.view.opengl.canvas.AGLView; import org.caleydo.core.view.opengl.canvas.AStorageBasedView; import org.caleydo.core.view.opengl.canvas.EDetailLevel; import org.caleydo.core.view.opengl.canvas.GLCaleydoCanvas; import org.caleydo.core.view.opengl.canvas.listener.ResetViewListener; import org.caleydo.core.view.opengl.canvas.remote.IGLRemoteRenderingView; import org.caleydo.core.view.opengl.mouse.GLMouseListener; import org.caleydo.core.view.opengl.renderstyle.GeneralRenderStyle; import org.caleydo.core.view.opengl.util.GLCoordinateUtils; import org.caleydo.core.view.opengl.util.overlay.contextmenu.container.ContentContextMenuItemContainer; import org.caleydo.core.view.opengl.util.overlay.contextmenu.container.ExperimentContextMenuItemContainer; import org.caleydo.core.view.opengl.util.overlay.infoarea.GLInfoAreaManager; import org.caleydo.core.view.opengl.util.texture.EIconTextures; import org.caleydo.view.bookmarking.GLBookmarkManager; import org.caleydo.view.parcoords.PCRenderStyle.PolyLineState; import org.caleydo.view.parcoords.listener.AngularBrushingListener; import org.caleydo.view.parcoords.listener.ApplyCurrentSelectionToVirtualArrayListener; import org.caleydo.view.parcoords.listener.BookmarkButtonListener; import org.caleydo.view.parcoords.listener.ResetAxisSpacingListener; import org.caleydo.view.parcoords.listener.UseRandomSamplingListener; import org.eclipse.jface.dialogs.MessageDialog; /** * This class is responsible for rendering the parallel coordinates * * @author Alexander Lex (responsible for PC) * @author Marc Streit */ public class GLParallelCoordinates extends AStorageBasedView implements IGLRemoteRenderingView { public final static String VIEW_ID = "org.caleydo.view.parcoords"; private EPickingType draggedObject; /** * Hashes a gate id, which is made up of an axis id + the last three digits * a gate counter (per axis) to a pair of values which make up the upper and * lower gate tip */ private HashMap<Integer, AGate> hashGates; /** * Hash of blocking gates */ private HashMap<Integer, ArrayList<Integer>> hashIsGateBlocking; /** * HashMap for the gates that are used to remove selections across all axes, * when the set is homogeneous */ private HashMap<Integer, Gate> hashMasterGates; /** * Gate counter used for unique ID retrieval for gates. It is shared between * regular and master gates */ private int iGateCounter = 0; /** * HashMap that has flags for all the axes that have NAN */ private HashMap<Integer, Boolean> hashExcludeNAN; private HashMap<Integer, ArrayList<Integer>> hashIsNANBlocking; private ArrayList<ArrayList<Integer>> alIsAngleBlocking; private ArrayList<Float> alAxisSpacing; private int iDraggedGateNumber = 0; private float fXDefaultTranslation = 0; private float fXTranslation = 0; private float fYTranslation = 0; private float fXTargetTranslation = 0; private boolean bIsTranslationActive = false; private boolean bAngularBrushingSelectPolyline = false; private boolean bIsAngularBrushingActive = false; private boolean bIsAngularBrushingFirstTime = false; private boolean bIsAngularDraggingActive = false; private boolean bIsGateDraggingFirstTime = false; private boolean bIsDraggingActive = false; private boolean hasFilterChanged = false; private boolean bWasAxisMoved = false; private boolean bWasAxisDraggedFirstTime = true; private float fAxisDraggingOffset; private int iMovedAxisPosition = -1; private Vec3f vecAngularBrushingPoint; private float fDefaultAngle = (float) Math.PI / 6; private float fCurrentAngle = 0; // private boolean bIsLineSelected = false; private int iSelectedLineID = -1; private Pick linePick; private SelectedElementRep elementRep; // private int iPolylineVAID = 0; // private int iAxisVAID = 0; protected PCRenderStyle renderStyle; private int displayEveryNthPolyline = 1; EIconTextures dropTexture = EIconTextures.DROP_NORMAL; int iChangeDropOnAxisNumber = -1; GLBookmarkManager glBookmarks; boolean bShowSelectionHeatMap = false; private GLInfoAreaManager infoAreaManager; /** Utility object for coordinate transformation and projection */ protected StandardTransformer selectionTransformer; // listeners private ApplyCurrentSelectionToVirtualArrayListener applyCurrentSelectionToVirtualArrayListener; private ResetAxisSpacingListener resetAxisSpacingListener; private BookmarkButtonListener bookmarkListener; private ResetViewListener resetViewListener; private UseRandomSamplingListener useRandomSamplingListener; private AngularBrushingListener angularBrushingListener; private org.eclipse.swt.graphics.Point upperLeftScreenPos = new org.eclipse.swt.graphics.Point( 0, 0); /** * FIXME: remove after data flipper video */ private boolean renderConnectionsLeft = true; /** * Constructor. */ public GLParallelCoordinates(GLCaleydoCanvas glCanvas, final String sLabel, final IViewFrustum viewFrustum) { super(glCanvas, sLabel, viewFrustum); viewType = GLParallelCoordinates.VIEW_ID; renderStyle = new PCRenderStyle(this, viewFrustum); super.renderStyle = this.renderStyle; alIsAngleBlocking = new ArrayList<ArrayList<Integer>>(); alIsAngleBlocking.add(new ArrayList<Integer>()); alAxisSpacing = new ArrayList<Float>(); iNumberOfRandomElements = generalManager.getPreferenceStore().getInt( PreferenceConstants.PC_NUM_RANDOM_SAMPLING_POINT); // glSelectionHeatMap = // ((ViewManager)generalManager.getViewGLCanvasManager()).getSelectionHeatMap(); icon = EIconTextures.PAR_COORDS_ICON; } @Override public void initLocal(final GL gl) { iGLDisplayListIndexLocal = gl.glGenLists(1); iGLDisplayListToCall = iGLDisplayListIndexLocal; // glSelectionHeatMap.addSets(alSets); // glSelectionHeatMap.initRemote(gl, getID(), // glMouseListener, // remoteRenderingGLCanvas); createSelectionHeatMap(gl); infoAreaManager = new GLInfoAreaManager(); infoAreaManager.initInfoInPlace(viewFrustum); selectionTransformer = new StandardTransformer(iUniqueID); init(gl); } @Override public void initRemote(final GL gl, final AGLView glParentView, final GLMouseListener glMouseListener, GLInfoAreaManager infoAreaManager) { bShowSelectionHeatMap = false; this.glMouseListener = glMouseListener; this.infoAreaManager = infoAreaManager; iGLDisplayListIndexRemote = gl.glGenLists(1); iGLDisplayListToCall = iGLDisplayListIndexRemote; selectionTransformer = new StandardTransformer(iUniqueID); init(gl); // toggleRenderContext(); } @Override public void init(final GL gl) { // FIXME: Alex, is it save to call this here? initData(); fXDefaultTranslation = renderStyle.getXSpacing(); fYTranslation = renderStyle.getBottomSpacing(); } @Override public void initData() { super.initData(); initGates(); resetAxisSpacing(); } @Override public void displayLocal(final GL gl) { if (glBookmarks != null) glBookmarks.processEvents(); if (set == null) return; if (bIsTranslationActive) { doTranslation(); } pickingManager.handlePicking(this, gl); if (bIsDisplayListDirtyLocal) { handleUnselection(); buildDisplayList(gl, iGLDisplayListIndexLocal); bIsDisplayListDirtyLocal = false; } iGLDisplayListToCall = iGLDisplayListIndexLocal; checkForHits(gl); display(gl); // ConnectedElementRepresentationManager cerm = // GeneralManager.get().getViewGLCanvasManager().getConnectedElementRepresentationManager(); // cerm.doViewRelatedTransformation(gl, selectionTransformer); if (eBusyModeState != EBusyModeState.OFF) { renderBusyMode(gl); } } @Override public void displayRemote(final GL gl) { if (set == null) return; if (bIsTranslationActive) { doTranslation(); } handleUnselection(); if (bIsDisplayListDirtyRemote) { buildDisplayList(gl, iGLDisplayListIndexRemote); bIsDisplayListDirtyRemote = false; } iGLDisplayListToCall = iGLDisplayListIndexRemote; display(gl); checkForHits(gl); } @Override public void display(final GL gl) { gl.glEnable(GL.GL_BLEND); if (bShowSelectionHeatMap) { gl.glTranslatef(viewFrustum.getRight() - glBookmarks.getViewFrustum().getWidth(), 0, 0.002f); // Render memo pad background IViewFrustum sHMFrustum = glBookmarks.getViewFrustum(); sHMFrustum.setTop(viewFrustum.getTop()); sHMFrustum.setBottom(viewFrustum.getBottom()); gl.glColor4fv(GeneralRenderStyle.PANEL_BACKGROUN_COLOR, 0); gl.glLineWidth(1); gl.glBegin(GL.GL_POLYGON); gl.glVertex3f(0, 0, 0); gl.glVertex3f(glBookmarks.getViewFrustum().getWidth(), 0, 0); gl.glVertex3f(glBookmarks.getViewFrustum().getWidth(), glBookmarks .getViewFrustum().getHeight(), 0); gl.glVertex3f(0, glBookmarks.getViewFrustum().getHeight(), 0); gl.glEnd(); int iPickingID = pickingManager.getPickingID(iUniqueID, EPickingType.PCS_VIEW_SELECTION, glBookmarks.getID()); gl.glPushName(iPickingID); glBookmarks.displayRemote(gl); gl.glPopName(); gl.glTranslatef(-viewFrustum.getRight() + glBookmarks.getViewFrustum().getWidth(), 0, -0.002f); } if (generalManager.getTrackDataProvider().isTrackModeActive()) handleTrackInput(gl); // TODO another display list // clipToFrustum(gl); gl.glTranslatef(fXDefaultTranslation + fXTranslation, fYTranslation, 0.0f); if (bIsDraggingActive) { handleGateDragging(gl); } if (bWasAxisMoved) { adjustAxisSpacing(gl); if (glMouseListener.wasMouseReleased()) { bWasAxisMoved = false; } } gl.glCallList(iGLDisplayListToCall); if (bIsAngularBrushingActive && iSelectedLineID != -1) { handleAngularBrushing(gl); } gl.glTranslatef(-fXDefaultTranslation - fXTranslation, -fYTranslation, 0.0f); if (!isRenderedRemote()) contextMenu.render(gl, this); } private void createSelectionHeatMap(GL gl) { // Create selection panel CmdCreateView cmdCreateGLView = (CmdCreateView) generalManager .getCommandManager().createCommandByType(ECommandType.CREATE_GL_VIEW); cmdCreateGLView.setViewID("org.caleydo.view.bookmarking"); cmdCreateGLView.setAttributes(EProjectionMode.ORTHOGRAPHIC, 0, 0.8f, viewFrustum.getBottom(), viewFrustum.getTop(), -20, 20, -1); cmdCreateGLView.setDataDomainType(dataDomain.getDataDomainType()); cmdCreateGLView.doCommand(); glBookmarks = (GLBookmarkManager) cmdCreateGLView.getCreatedObject(); glBookmarks.setRemoteRenderingGLView(this); glBookmarks.setDataDomain(dataDomain); glBookmarks.initData(); // FIXME: remoteRenderingGLCanvas is null, conceptual error glBookmarks.initRemote(gl, this, glMouseListener, null); } public void triggerAngularBrushing() { bAngularBrushingSelectPolyline = true; setDisplayListDirty(); } @Override public void renderContext(boolean bRenderOnlyContext) { this.bRenderOnlyContext = bRenderOnlyContext; if (bRenderOnlyContext) { contentVA = dataDomain.getContentVA(ContentVAType.CONTENT_CONTEXT); } else { contentVA = dataDomain.getContentVA(ContentVAType.CONTENT); } contentSelectionManager.setVA(contentVA); initContentVariables(); // initGates(); clearAllSelections(); setDisplayListDirty(); } /** * Reset all selections and deselections */ @Override public void clearAllSelections() { initGates(); contentSelectionManager.clearSelections(); storageSelectionManager.clearSelections(); // isEnabled = false; bIsAngularBrushingActive = false; for (ArrayList<Integer> alCurrent : alIsAngleBlocking) { alCurrent.clear(); } for (ArrayList<Integer> alCurrent : hashIsGateBlocking.values()) { alCurrent.clear(); } setDisplayListDirty(); connectedElementRepresentationManager.clear(EIDType.EXPRESSION_INDEX); if (glBookmarks != null) { glBookmarks.clearAllSelections(); } } /** * Sends a bookmark event containing all elements which are currently * visible in the pcs, if the number of elements is less than 20. If it's * more than 20 an error message is displayed. */ public void bookmarkElements() { ContentVADelta delta = contentSelectionManager.getBroadcastVADelta(); if (delta.size() > 20) { getParentGLCanvas().getParentComposite().getDisplay() .asyncExec(new Runnable() { @Override public void run() { MessageDialog .openError(getParentGLCanvas().getParentComposite() .getShell(), "Bookmark Limit", "Can not bookmark more than 20 elements - reduce polylines to less than 20 first"); return; } }); return; } if (!isRenderedRemote()) { bShowSelectionHeatMap = true; BookmarkEvent<Integer> bookmarkEvent = new BookmarkEvent<Integer>( EIDType.EXPRESSION_INDEX); for (VADeltaItem item : delta.getAllItems()) { bookmarkEvent.addBookmark(item.getPrimaryID()); } eventPublisher.triggerEvent(bookmarkEvent); resetAxisSpacing(); setDisplayListDirty(); } } public void saveSelection() { // polylineSelectionManager.moveType(SelectionType.DESELECTED, // SelectionType.REMOVE); contentSelectionManager.removeElements(SelectionType.DESELECTED); clearAllSelections(); setDisplayListDirty(); contentVA.setGroupList(null); // todo this doesn't work for turned stuff ReplaceContentVAInUseCaseEvent event = new ReplaceContentVAInUseCaseEvent( dataDomain.getDataDomainType(), contentVAType, contentVA); event.setDataDomainType(dataDomain.getDataDomainType()); event.setSender(this); eventPublisher.triggerEvent(event); } /** * Initializes the array lists that contain the data. Must be run at program * start, every time you exchange axis and polylines and every time you * change storages or selections * */ @Override protected void initLists() { if (bRenderOnlyContext) contentVAType = ContentVAType.CONTENT_CONTEXT; else contentVAType = ContentVAType.CONTENT; contentVA = dataDomain.getContentVA(contentVAType); storageVA = dataDomain.getStorageVA(storageVAType); initContentVariables(); contentSelectionManager.setVA(contentVA); storageSelectionManager.setVA(storageVA); initGates(); } /** * Build mapping between polyline/axis and storage/content for virtual * arrays and selection managers */ private void initContentVariables() { // EIDType contentDataType; // EIDType storageDataType; // if // (dataDomain.getDataDomainType().equals("org.caleydo.datadomain.genetic")) // { // contentDataType = EIDType.EXPRESSION_INDEX; // storageDataType = EIDType.EXPERIMENT_INDEX; // } else if (dataDomain.getDataDomainType().equals( // "org.caleydo.datadomain.clinical") // || dataDomain.getDataDomainType() // .equals("org.caleydo.datadomain.generic")) { // contentDataType = EIDType.EXPERIMENT; // storageDataType = EIDType.EXPERIMENT_INDEX; // // } else { // throw new IllegalStateException("Unsupported data domain (" + // dataDomain // + ") for parallel coordinates"); // } } /** * Initialize the gates. The gate heights are saved in two lists, which * contain the rendering height of the gate */ private void initGates() { hashGates = new HashMap<Integer, AGate>(); hashIsGateBlocking = new HashMap<Integer, ArrayList<Integer>>(); if (set.isSetHomogeneous()) { hashMasterGates = new HashMap<Integer, Gate>(); } hashExcludeNAN = new HashMap<Integer, Boolean>(); hashIsNANBlocking = new HashMap<Integer, ArrayList<Integer>>(); } /** * Build polyline display list. Renders coordinate system, polylines and * gates, by calling the render methods * * @param gl * GL context * @param iGLDisplayListIndex * the index of the display list */ private void buildDisplayList(final GL gl, int iGLDisplayListIndex) { gl.glNewList(iGLDisplayListIndex, GL.GL_COMPILE); if (contentVA.size() == 0) { gl.glTranslatef(-fXDefaultTranslation - fXTranslation, -fYTranslation, 0.0f); renderSymbol(gl, EIconTextures.PAR_COORDS_SYMBOL, 2); gl.glTranslatef(+fXDefaultTranslation + fXTranslation, fYTranslation, 0.0f); } else { if (set.isSetHomogeneous()) { renderMasterGate(gl); } renderCoordinateSystem(gl); for (SelectionType selectionType : contentSelectionManager .getSelectionTypes()) { if (selectionType.isVisible()) { if (selectionType == SelectionType.NORMAL) renderNormalPolylines(gl, selectionType); else renderSelectedPolylines(gl, selectionType); } } renderGates(gl); } gl.glEndList(); } /** * Polyline rendering method. All polylines that are contained in the * polylineSelectionManager and are of the selection type specified in * renderMode * * FIXME this needs to be changed to iterate over the virtual array, * considering the deselected elements * * @param gl * the GL context * @param renderMode * the type of selection in the selection manager to render */ @SuppressWarnings("unchecked") private void renderNormalPolylines(GL gl, SelectionType selectionType) { int nrVisibleLines; nrVisibleLines = contentVA.size() - contentSelectionManager.getNumberOfElements(SelectionType.DESELECTED); displayEveryNthPolyline = (contentVA.size() - contentSelectionManager .getNumberOfElements(SelectionType.DESELECTED)) / iNumberOfRandomElements; if (displayEveryNthPolyline == 0) { displayEveryNthPolyline = 1; } PolyLineState renderState = renderStyle.getPolyLineState(selectionType, nrVisibleLines / displayEveryNthPolyline); // this loop executes once per polyline for (int contentIndex = 0; contentIndex < contentVA.size(); contentIndex += displayEveryNthPolyline) { int contentID = contentVA.get(contentIndex); if (!contentSelectionManager.checkStatus(SelectionType.DESELECTED, contentID)) renderSingleLine(gl, contentID, selectionType, renderState, false); } } private void renderSelectedPolylines(GL gl, SelectionType selectionType) { int nrVisibleLines = contentSelectionManager.getNumberOfElements(selectionType); Iterable<Integer> lines = contentSelectionManager.getElements(selectionType); PolyLineState renderState = renderStyle.getPolyLineState(selectionType, nrVisibleLines / displayEveryNthPolyline); for (Integer contentID : lines) { renderSingleLine(gl, contentID, selectionType, renderState, true); } } private void renderSingleLine(GL gl, Integer polyLineID, SelectionType selectionType, PolyLineState renderState, boolean bRenderingSelection) { // Integer polyLineID = lines.; // if (contentSelectionManager.checkStatus(SelectionType.DESELECTED, // polyLineID)) // continue; gl.glColor4fv(renderState.color, 0); gl.glLineWidth(renderState.lineWidth); if ((selectionType == SelectionType.SELECTION || selectionType == SelectionType.MOUSE_OVER) && detailLevel == EDetailLevel.HIGH) { bRenderingSelection = true; } else bRenderingSelection = false; // if (bUseRandomSampling // && (selectionType == SelectionType.DESELECTED || selectionType == // SelectionType.NORMAL)) { // if (polyLineID % displayEveryNthPolyline != 0) { // continue; // // if(!alUseInRandomSampling.get(contentVA.indexOf(iPolyLineID))) // // continue; // } // } if (selectionType != SelectionType.DESELECTED) { gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.POLYLINE_SELECTION, polyLineID)); } if (!bRenderingSelection) { gl.glBegin(GL.GL_LINE_STRIP); } IStorage currentStorage = null; float fPreviousXValue = 0; float fPreviousYValue = 0; float fCurrentXValue = 0; float fCurrentYValue = 0; // this loop executes once per axis for (int iVertexCount = 0; iVertexCount < storageVA.size(); iVertexCount++) { int iStorageIndex = 0; currentStorage = set.get(storageVA.get(iVertexCount)); iStorageIndex = polyLineID; fCurrentXValue = alAxisSpacing.get(iVertexCount); fCurrentYValue = currentStorage.getFloat(EDataRepresentation.NORMALIZED, iStorageIndex); if (Float.isNaN(fCurrentYValue)) { fCurrentYValue = NAN_Y_OFFSET / renderStyle.getAxisHeight(); } if (iVertexCount != 0) { if (bRenderingSelection) { gl.glBegin(GL.GL_LINES); } gl.glVertex3f(fPreviousXValue, fPreviousYValue * renderStyle.getAxisHeight(), renderState.zDepth); gl.glVertex3f(fCurrentXValue, fCurrentYValue * renderStyle.getAxisHeight(), renderState.zDepth); if (bRenderingSelection) { gl.glEnd(); } } if (bRenderingSelection) { String sRawValue; if (currentStorage instanceof INumericalStorage) { sRawValue = Formatter.formatNumber(currentStorage.getFloat( EDataRepresentation.RAW, iStorageIndex)); } else if (currentStorage instanceof INominalStorage) { sRawValue = ((INominalStorage<String>) currentStorage) .getRaw(iStorageIndex); } else throw new IllegalStateException("Unknown Storage Type"); renderBoxedYValues(gl, fCurrentXValue, fCurrentYValue * renderStyle.getAxisHeight(), sRawValue, selectionType); } fPreviousXValue = fCurrentXValue; fPreviousYValue = fCurrentYValue; } if (!bRenderingSelection) { gl.glEnd(); } if (selectionType != SelectionType.DESELECTED) { gl.glPopName(); } } /** * Render the coordinate system of the parallel coordinates, including the * axis captions and axis-specific buttons * * @param gl * the gl context * @param iNumberAxis */ private void renderCoordinateSystem(GL gl) { textRenderer.setColor(0, 0, 0, 1); int iNumberAxis = storageVA.size(); // draw X-Axis gl.glColor4fv(X_AXIS_COLOR, 0); gl.glLineWidth(X_AXIS_LINE_WIDTH); gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.X_AXIS_SELECTION, 1)); gl.glBegin(GL.GL_LINES); gl.glVertex3f(renderStyle.getXAxisStart(), 0.0f, 0.0f); gl.glVertex3f(renderStyle.getXAxisEnd(), 0.0f, 0.0f); gl.glEnd(); gl.glPopName(); // draw all Y-Axis Set<Integer> selectedSet = storageSelectionManager .getElements(SelectionType.SELECTION); Set<Integer> mouseOverSet = storageSelectionManager .getElements(SelectionType.MOUSE_OVER); int iCount = 0; while (iCount < iNumberAxis) { float fXPosition = alAxisSpacing.get(iCount); if (selectedSet.contains(storageVA.get(iCount))) { gl.glColor4fv(SelectionType.SELECTION.getColor(), 0); gl.glLineWidth(Y_AXIS_SELECTED_LINE_WIDTH); gl.glEnable(GL.GL_LINE_STIPPLE); gl.glLineStipple(2, (short) 0xAAAA); } else if (mouseOverSet.contains(storageVA.get(iCount))) { gl.glColor4fv(SelectionType.MOUSE_OVER.getColor(), 0); gl.glLineWidth(Y_AXIS_MOUSE_OVER_LINE_WIDTH); gl.glEnable(GL.GL_LINE_STIPPLE); gl.glLineStipple(2, (short) 0xAAAA); } else { gl.glColor4fv(Y_AXIS_COLOR, 0); gl.glLineWidth(Y_AXIS_LINE_WIDTH); } gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.Y_AXIS_SELECTION, storageVA.get(iCount))); gl.glBegin(GL.GL_LINES); gl.glVertex3f(fXPosition, Y_AXIS_LOW, AXIS_Z); gl.glVertex3f(fXPosition, renderStyle.getAxisHeight(), AXIS_Z); // Top marker gl.glVertex3f(fXPosition - AXIS_MARKER_WIDTH, renderStyle.getAxisHeight(), AXIS_Z); gl.glVertex3f(fXPosition + AXIS_MARKER_WIDTH, renderStyle.getAxisHeight(), AXIS_Z); gl.glEnd(); gl.glDisable(GL.GL_LINE_STIPPLE); if (detailLevel != EDetailLevel.HIGH || !renderStyle.isEnoughSpaceForText(iNumberAxis)) { // pop the picking id here when we don't want to include the // axis label gl.glPopName(); } if (detailLevel == EDetailLevel.HIGH) { // NaN Button float fXButtonOrigin = alAxisSpacing.get(iCount); Vec3f lowerLeftCorner = new Vec3f(fXButtonOrigin - 0.03f, PCRenderStyle.NAN_Y_OFFSET - 0.03f, PCRenderStyle.NAN_Z); Vec3f lowerRightCorner = new Vec3f(fXButtonOrigin + 0.03f, PCRenderStyle.NAN_Y_OFFSET - 0.03f, PCRenderStyle.NAN_Z); Vec3f upperRightCorner = new Vec3f(fXButtonOrigin + 0.03f, PCRenderStyle.NAN_Y_OFFSET + 0.03f, PCRenderStyle.NAN_Z); Vec3f upperLeftCorner = new Vec3f(fXButtonOrigin - 0.03f, PCRenderStyle.NAN_Y_OFFSET + 0.03f, PCRenderStyle.NAN_Z); Vec3f scalingPivot = new Vec3f(fXButtonOrigin, PCRenderStyle.NAN_Y_OFFSET, PCRenderStyle.NAN_Z); int iPickingID = pickingManager.getPickingID(iUniqueID, EPickingType.REMOVE_NAN, storageVA.get(iCount)); gl.glPushName(iPickingID); textureManager.renderGUITexture(gl, EIconTextures.NAN, lowerLeftCorner, lowerRightCorner, upperRightCorner, upperLeftCorner, scalingPivot, 1, 1, 1, 1, 100); gl.glPopName(); // markers on axis float fMarkerSpacing = renderStyle.getAxisHeight() / (NUMBER_AXIS_MARKERS + 1); for (int iInnerCount = 1; iInnerCount <= NUMBER_AXIS_MARKERS; iInnerCount++) { float fCurrentHeight = fMarkerSpacing * iInnerCount; if (iCount == 0) { if (set.isSetHomogeneous()) { float fNumber = (float) set .getRawForNormalized(fCurrentHeight / renderStyle.getAxisHeight()); Rectangle2D bounds = textRenderer.getScaledBounds(gl, Formatter.formatNumber(fNumber), renderStyle.getSmallFontScalingFactor(), PCRenderStyle.MIN_NUMBER_TEXT_SIZE); float fWidth = (float) bounds.getWidth(); float fHeightHalf = (float) bounds.getHeight() / 3.0f; renderNumber(gl, Formatter.formatNumber(fNumber), fXPosition - fWidth - AXIS_MARKER_WIDTH, fCurrentHeight - fHeightHalf); } else { // TODO: storage based access } } gl.glColor3fv(Y_AXIS_COLOR, 0); gl.glBegin(GL.GL_LINES); gl.glVertex3f(fXPosition - AXIS_MARKER_WIDTH, fCurrentHeight, AXIS_Z); gl.glVertex3f(fXPosition + AXIS_MARKER_WIDTH, fCurrentHeight, AXIS_Z); gl.glEnd(); } String sAxisLabel = null; // switch (eAxisDataType) { // // TODO not very generic here // // case EXPRESSION_INDEX: // // FIXME: Due to new mapping system, a mapping involving // // expression index can return a // // Set of // // values, depending on the IDType that has been // // specified when loading expression // // data. // // Possibly a different handling of the Set is required. // Set<String> setGeneSymbols = idMappingManager.getIDAsSet( // EIDType.EXPRESSION_INDEX, EIDType.GENE_SYMBOL, // axisVA.get(iCount)); // // if ((setGeneSymbols != null && !setGeneSymbols.isEmpty())) { // sAxisLabel = (String) setGeneSymbols.toArray()[0]; // } // if (sAxisLabel == null) // sAxisLabel = "Unknown Gene"; // break; // // case EXPERIMENT: // default: // if (bRenderStorageHorizontally) { // sAxisLabel = "TODO: gene labels for axis"; // } else sAxisLabel = set.get(storageVA.get(iCount)).getLabel(); // break; // } gl.glPushAttrib(GL.GL_CURRENT_BIT | GL.GL_LINE_BIT); gl.glTranslatef( fXPosition, renderStyle.getAxisHeight() + renderStyle.getAxisCaptionSpacing(), 0); gl.glRotatef(25, 0, 0, 1); textRenderer.begin3DRendering(); float fScaling = renderStyle.getSmallFontScalingFactor(); if (isRenderedRemote()) fScaling *= 1.5f; textRenderer.draw3D(gl, sAxisLabel, 0, 0, 0, fScaling, PCRenderStyle.MIN_AXIS_LABEL_TEXT_SIZE); textRenderer.end3DRendering(); gl.glRotatef(-25, 0, 0, 1); gl.glTranslatef(-fXPosition, -(renderStyle.getAxisHeight() + renderStyle .getAxisCaptionSpacing()), 0); if (set.isSetHomogeneous()) { // textRenderer.begin3DRendering(); // // // render values on top and bottom of axis // // // top // String text = getDecimalFormat().format(set.getMax()); // textRenderer.draw3D(text, fXPosition + 2 * // AXIS_MARKER_WIDTH, renderStyle // .getAxisHeight(), 0, // renderStyle.getSmallFontScalingFactor()); // // // bottom // text = getDecimalFormat().format(set.getMin()); // textRenderer.draw3D(text, fXPosition + 2 * // AXIS_MARKER_WIDTH, 0, 0, // renderStyle.getSmallFontScalingFactor()); // textRenderer.end3DRendering(); } else { // TODO } gl.glPopAttrib(); // render Buttons iPickingID = -1; float fYDropOrigin = -PCRenderStyle.AXIS_BUTTONS_Y_OFFSET; gl.glBlendFunc(GL.GL_ONE, GL.GL_ONE_MINUS_SRC_ALPHA); // the gate add button float fYGateAddOrigin = renderStyle.getAxisHeight(); iPickingID = pickingManager.getPickingID(iUniqueID, EPickingType.ADD_GATE, storageVA.get(iCount)); lowerLeftCorner.set(fXButtonOrigin - 0.03f, fYGateAddOrigin, AXIS_Z); lowerRightCorner.set(fXButtonOrigin + 0.03f, fYGateAddOrigin, AXIS_Z); upperRightCorner.set(fXButtonOrigin + 0.03f, fYGateAddOrigin + 0.12f, AXIS_Z); upperLeftCorner.set(fXButtonOrigin - 0.03f, fYGateAddOrigin + 0.12f, AXIS_Z); scalingPivot.set(fXButtonOrigin, fYGateAddOrigin, AXIS_Z); gl.glPushName(iPickingID); textureManager.renderGUITexture(gl, EIconTextures.ADD_GATE, lowerLeftCorner, lowerRightCorner, upperRightCorner, upperLeftCorner, scalingPivot, 1, 1, 1, 1, 100); gl.glPopName(); if (selectedSet.contains(storageVA.get(iCount)) || mouseOverSet.contains(storageVA.get(iCount))) { lowerLeftCorner.set(fXButtonOrigin - 0.15f, fYDropOrigin - 0.3f, AXIS_Z + 0.005f); lowerRightCorner.set(fXButtonOrigin + 0.15f, fYDropOrigin - 0.3f, AXIS_Z + 0.005f); upperRightCorner.set(fXButtonOrigin + 0.15f, fYDropOrigin, AXIS_Z + 0.005f); upperLeftCorner.set(fXButtonOrigin - 0.15f, fYDropOrigin, AXIS_Z + 0.005f); scalingPivot.set(fXButtonOrigin, fYDropOrigin, AXIS_Z + 0.005f); // the mouse over drop if (iChangeDropOnAxisNumber == iCount) { // tempTexture = textureManager.getIconTexture(gl, // dropTexture); textureManager.renderGUITexture(gl, dropTexture, lowerLeftCorner, lowerRightCorner, upperRightCorner, upperLeftCorner, scalingPivot, 1, 1, 1, 1, 80); if (!bWasAxisMoved) { dropTexture = EIconTextures.DROP_NORMAL; } } else { textureManager.renderGUITexture(gl, EIconTextures.DROP_NORMAL, lowerLeftCorner, lowerRightCorner, upperRightCorner, upperLeftCorner, scalingPivot, 1, 1, 1, 1, 80); } iPickingID = pickingManager.getPickingID(iUniqueID, EPickingType.MOVE_AXIS, iCount); gl.glColor4f(0, 0, 0, 0f); gl.glPushName(iPickingID); gl.glBegin(GL.GL_TRIANGLES); gl.glVertex3f(fXButtonOrigin, fYDropOrigin, AXIS_Z + 0.01f); gl.glVertex3f(fXButtonOrigin + 0.08f, fYDropOrigin - 0.3f, AXIS_Z + 0.01f); gl.glVertex3f(fXButtonOrigin - 0.08f, fYDropOrigin - 0.3f, AXIS_Z + 0.01f); gl.glEnd(); gl.glPopName(); iPickingID = pickingManager.getPickingID(iUniqueID, EPickingType.DUPLICATE_AXIS, iCount); // gl.glColor4f(0, 1, 0, 0.5f); gl.glPushName(iPickingID); gl.glBegin(GL.GL_TRIANGLES); gl.glVertex3f(fXButtonOrigin, fYDropOrigin, AXIS_Z + 0.01f); gl.glVertex3f(fXButtonOrigin - 0.08f, fYDropOrigin - 0.21f, AXIS_Z + 0.01f); gl.glVertex3f(fXButtonOrigin - 0.23f, fYDropOrigin - 0.21f, AXIS_Z + 0.01f); gl.glEnd(); gl.glPopName(); iPickingID = pickingManager.getPickingID(iUniqueID, EPickingType.REMOVE_AXIS, iCount); // gl.glColor4f(0, 0, 1, 0.5f); gl.glPushName(iPickingID); gl.glBegin(GL.GL_TRIANGLES); gl.glVertex3f(fXButtonOrigin, fYDropOrigin, AXIS_Z + 0.01f); gl.glVertex3f(fXButtonOrigin + 0.08f, fYDropOrigin - 0.21f, AXIS_Z + 0.01f); gl.glVertex3f(fXButtonOrigin + 0.23f, fYDropOrigin - 0.21f, AXIS_Z + 0.01f); gl.glEnd(); gl.glPopName(); } else { iPickingID = pickingManager.getPickingID(iUniqueID, EPickingType.MOVE_AXIS, iCount); gl.glPushAttrib(GL.GL_CURRENT_BIT | GL.GL_LINE_BIT); gl.glPushName(iPickingID); lowerLeftCorner.set(fXButtonOrigin - 0.05f, fYDropOrigin - 0.2f, AXIS_Z); lowerRightCorner.set(fXButtonOrigin + 0.05f, fYDropOrigin - 0.2f, AXIS_Z); upperRightCorner.set(fXButtonOrigin + 0.05f, fYDropOrigin, AXIS_Z); upperLeftCorner.set(fXButtonOrigin - 0.05f, fYDropOrigin, AXIS_Z); scalingPivot.set(fXButtonOrigin, fYDropOrigin, AXIS_Z); textureManager.renderGUITexture(gl, EIconTextures.SMALL_DROP, lowerLeftCorner, lowerRightCorner, upperRightCorner, upperLeftCorner, scalingPivot, 1, 1, 1, 1, 80); gl.glPopName(); gl.glPopAttrib(); } gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); gl.glPopName(); } iCount++; } } /** * Render the gates and update the fArGateHeights for the * selection/unselection * * @param gl * @param iNumberAxis */ private void renderGates(GL gl) { if (detailLevel != EDetailLevel.HIGH) return; for (Integer iGateID : hashGates.keySet()) { // Gate ID / 1000 is axis ID AGate gate = hashGates.get(iGateID); int iAxisID = gate.getAxisID(); // Pair<Float, Float> gate = hashGates.get(iGateID); // TODO for all indices ArrayList<Integer> iAlAxisIndex = storageVA.indicesOf(iAxisID); for (int iAxisIndex : iAlAxisIndex) { float fCurrentPosition = alAxisSpacing.get(iAxisIndex); gate.setCurrentPosition(fCurrentPosition); // String label = set.get(iAxisID).getLabel(); gate.draw(gl, pickingManager, textureManager, textRenderer, iUniqueID); // renderSingleGate(gl, gate, iAxisID, iGateID, // fCurrentPosition); } } } private void renderMasterGate(GL gl) { if (detailLevel != EDetailLevel.HIGH) return; gl.glColor4f(0, 0, 0, 1f); gl.glLineWidth(PCRenderStyle.Y_AXIS_LINE_WIDTH); // gl.glPushName(iPickingID); float fXOrigin = -0.25f; gl.glBegin(GL.GL_LINES); gl.glVertex3f(fXOrigin, 0, AXIS_Z); gl.glVertex3f(fXOrigin, renderStyle.getAxisHeight(), AXIS_Z); gl.glVertex3f(fXOrigin - AXIS_MARKER_WIDTH, 0, AXIS_Z); gl.glVertex3f(fXOrigin + AXIS_MARKER_WIDTH, 0, AXIS_Z); gl.glVertex3f(fXOrigin - AXIS_MARKER_WIDTH, renderStyle.getAxisHeight(), AXIS_Z); gl.glVertex3f(fXOrigin + AXIS_MARKER_WIDTH, renderStyle.getAxisHeight(), AXIS_Z); gl.glEnd(); gl.glBlendFunc(GL.GL_ONE, GL.GL_ONE_MINUS_SRC_ALPHA); // the gate add button float fYGateAddOrigin = renderStyle.getAxisHeight(); int iPickingID = pickingManager.getPickingID(iUniqueID, EPickingType.ADD_MASTER_GATE, 1); gl.glPushName(iPickingID); Vec3f lowerLeftCorner = new Vec3f(fXOrigin - 0.05f, fYGateAddOrigin, AXIS_Z); Vec3f lowerRightCorner = new Vec3f(fXOrigin + 0.05f, fYGateAddOrigin, AXIS_Z); Vec3f upperRightCorner = new Vec3f(fXOrigin + 0.05f, fYGateAddOrigin + 0.2f, AXIS_Z); Vec3f upperLeftCorner = new Vec3f(fXOrigin - 0.05f, fYGateAddOrigin + 0.2f, AXIS_Z); Vec3f scalingPivot = new Vec3f(fXOrigin, fYGateAddOrigin, AXIS_Z); textureManager.renderGUITexture(gl, EIconTextures.ADD_GATE, lowerLeftCorner, lowerRightCorner, upperRightCorner, upperLeftCorner, scalingPivot, 1, 1, 1, 1, 100); gl.glPopName(); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); for (Integer iGateID : hashMasterGates.keySet()) { Gate gate = hashMasterGates.get(iGateID); Float fBottom = gate.getBottom(); Float fTop = gate.getTop(); gl.glColor4fv(PCRenderStyle.GATE_BODY_COLOR, 0); gl.glBegin(GL.GL_POLYGON); gl.glVertex3f(fXOrigin, fBottom, 0); gl.glVertex3f(viewFrustum.getWidth() - 1, fBottom, 0); gl.glVertex3f(viewFrustum.getWidth() - 1, fTop, 0); // TODO eurovis hacke // gl.glVertex3f(viewFrustum.getWidth(), fBottom, 0); // gl.glVertex3f(viewFrustum.getWidth(), fTop, 0); // gl.glVertex3f(fXOrigin - 0.05f, fTop, 0); gl.glEnd(); gate.setCurrentPosition(fXOrigin); gate.draw(gl, pickingManager, textureManager, textRenderer, iUniqueID); // renderSingleGate(gl, gate, -1, iGateID, fXOrigin); } // gl.glPopName(); } /** * Render the captions on the axis * * @param gl * @param fXOrigin * @param fYOrigin * @param renderMode */ private void renderBoxedYValues(GL gl, float fXOrigin, float fYOrigin, String sRawValue, SelectionType renderMode) { float fScaling = renderStyle.getSmallFontScalingFactor(); if (isRenderedRemote()) fScaling *= 1.5f; // don't render values that are below the y axis if (fYOrigin < 0) return; gl.glPushAttrib(GL.GL_CURRENT_BIT | GL.GL_LINE_BIT); gl.glLineWidth(Y_AXIS_LINE_WIDTH); gl.glColor4fv(Y_AXIS_COLOR, 0); Rectangle2D tempRectangle = textRenderer.getScaledBounds(gl, sRawValue, fScaling, PCRenderStyle.MIN_NUMBER_TEXT_SIZE); float fSmallSpacing = renderStyle.getVerySmallSpacing(); float fBackPlaneWidth = (float) tempRectangle.getWidth(); float fBackPlaneHeight = (float) tempRectangle.getHeight(); float fXTextOrigin = fXOrigin + 2 * AXIS_MARKER_WIDTH; float fYTextOrigin = fYOrigin; gl.glColor4f(1f, 1f, 1f, 0.8f); gl.glBegin(GL.GL_POLYGON); gl.glVertex3f(fXTextOrigin - fSmallSpacing, fYTextOrigin - fSmallSpacing, LABEL_Z); gl.glVertex3f(fXTextOrigin + fBackPlaneWidth, fYTextOrigin - fSmallSpacing, LABEL_Z); gl.glVertex3f(fXTextOrigin + fBackPlaneWidth, fYTextOrigin + fBackPlaneHeight, LABEL_Z); gl.glVertex3f(fXTextOrigin - fSmallSpacing, fYTextOrigin + fBackPlaneHeight, LABEL_Z); gl.glEnd(); renderNumber(gl, sRawValue, fXTextOrigin, fYTextOrigin); gl.glPopAttrib(); } private void renderNumber(GL gl, String sRawValue, float fXOrigin, float fYOrigin) { textRenderer.begin3DRendering(); // String text = ""; // if (Float.isNaN(fRawValue)) // text = "NaN"; // else // text = getDecimalFormat().format(fRawValue); float fScaling = renderStyle.getSmallFontScalingFactor(); if (isRenderedRemote()) fScaling *= 1.5f; textRenderer.draw3D(gl, sRawValue, fXOrigin, fYOrigin, PCRenderStyle.TEXT_ON_LABEL_Z, fScaling, PCRenderStyle.MIN_NUMBER_TEXT_SIZE); textRenderer.end3DRendering(); } /** * Renders the gates and updates their values * * @param gl */ private void handleGateDragging(GL gl) { hasFilterChanged = true; // bIsDisplayListDirtyLocal = true; // bIsDisplayListDirtyRemote = true; Point currentPoint = glMouseListener.getPickedPoint(); float[] fArTargetWorldCoordinates = GLCoordinateUtils .convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x, currentPoint.y); // todo only valid for one gate AGate gate = null; gate = hashGates.get(iDraggedGateNumber); if (gate == null) { gate = hashMasterGates.get(iDraggedGateNumber); if (gate == null) return; } gate.handleDragging(gl, fArTargetWorldCoordinates[0], fArTargetWorldCoordinates[1], draggedObject, bIsGateDraggingFirstTime); bIsGateDraggingFirstTime = false; bIsDisplayListDirtyLocal = true; bIsDisplayListDirtyRemote = true; InfoAreaUpdateEvent event = new InfoAreaUpdateEvent(); event.setDataDomainType(dataDomain.getDataDomainType()); event.setSender(this); event.setInfo(getShortInfoLocal()); eventPublisher.triggerEvent(event); if (glMouseListener.wasMouseReleased()) { bIsDraggingActive = false; } } /** * Unselect all lines that are deselected with the gates * * @param iChangeDropOnAxisNumber */ // TODO revise private void handleGateUnselection() { float fCurrentValue = -1; for (Integer iGateID : hashGates.keySet()) { ArrayList<Integer> alCurrentGateBlocks = hashIsGateBlocking.get(iGateID); if (alCurrentGateBlocks == null) return; alCurrentGateBlocks.clear(); AGate gate = hashGates.get(iGateID); int iAxisID = gate.getAxisID(); if (iAxisID == -1) continue; for (int iPolylineIndex : contentVA) { EDataRepresentation usedDataRepresentation = EDataRepresentation.RAW; if (!set.isSetHomogeneous()) usedDataRepresentation = EDataRepresentation.NORMALIZED; fCurrentValue = set.get(iAxisID).getFloat(usedDataRepresentation, iPolylineIndex); if (Float.isNaN(fCurrentValue)) { continue; } if (fCurrentValue <= gate.getUpperValue() && fCurrentValue >= gate.getLowerValue()) { alCurrentGateBlocks.add(iPolylineIndex); } } } } private void handleNANUnselection() { float fCurrentValue = 0; hashIsNANBlocking.clear(); for (Integer iAxisID : hashExcludeNAN.keySet()) { ArrayList<Integer> alDeselectedLines = new ArrayList<Integer>(); for (int iPolylineIndex : contentVA) { fCurrentValue = set.get(iAxisID).getFloat(EDataRepresentation.NORMALIZED, iPolylineIndex); if (Float.isNaN(fCurrentValue)) { alDeselectedLines.add(iPolylineIndex); } } hashIsNANBlocking.put(iAxisID, alDeselectedLines); } } private void handleMasterGateUnselection() { float fCurrentValue = -1; for (Integer iGateID : hashMasterGates.keySet()) { ArrayList<Integer> alCurrentGateBlocks = hashIsGateBlocking.get(iGateID); if (alCurrentGateBlocks == null) return; alCurrentGateBlocks.clear(); Gate gate = hashMasterGates.get(iGateID); for (int iPolylineIndex : contentVA) { boolean bIsBlocking = true; for (int iAxisIndex : storageVA) { fCurrentValue = set.get(iAxisIndex).getFloat(EDataRepresentation.RAW, iPolylineIndex); if (Float.isNaN(fCurrentValue)) { continue; } if (fCurrentValue <= gate.getUpperValue() && fCurrentValue >= gate.getLowerValue()) { bIsBlocking = true; } else { bIsBlocking = false; break; } } if (bIsBlocking) { alCurrentGateBlocks.add(iPolylineIndex); } } } } @Override protected void reactOnExternalSelection(boolean scrollToSelection) { handleUnselection(); resetAxisSpacing(); } @Override protected void reactOnContentVAChanges(ContentVADelta delta) { contentSelectionManager.setVADelta(delta); } @Override protected void reactOnStorageVAChanges(StorageVADelta delta) { for (VADeltaItem item : delta) { if (item.getType() == EVAOperation.REMOVE) { int iElement = storageVA.get(item.getIndex()); // resetAxisSpacing(); if (storageVA.containsElement(iElement) == 1) { removeGate(iElement); } } else if (item.getType() == EVAOperation.REMOVE_ELEMENT) { removeGate(item.getPrimaryID()); } } storageSelectionManager.setVADelta(delta); resetAxisSpacing(); } /** removes a gate based on an axis id **/ private void removeGate(int axisID) { Iterator<Integer> gateIterator = hashGates.keySet().iterator(); while (gateIterator.hasNext()) { int gateID = gateIterator.next(); if (hashGates.get(gateID).getAxisID() == axisID) { gateIterator.remove(); hashIsGateBlocking.remove(gateID); } } } /** * TODO: revise this, not very performance friendly, especially the clearing * of the DESELECTED */ private void handleUnselection() { if (!hasFilterChanged) return; handleGateUnselection(); handleNANUnselection(); if (set.isSetHomogeneous()) handleMasterGateUnselection(); // HashMap<Integer, Boolean> hashDeselectedPolylines = new // HashMap<Integer, Boolean>(); contentSelectionManager.clearSelection(SelectionType.DESELECTED); for (ArrayList<Integer> alCurrent : hashIsGateBlocking.values()) { contentSelectionManager.addToType(SelectionType.DESELECTED, alCurrent); // for (Integer iCurrent : alCurrent) // { // hashDeselectedPolylines.put(iCurrent, null); // } } for (ArrayList<Integer> alCurrent : alIsAngleBlocking) { contentSelectionManager.addToType(SelectionType.DESELECTED, alCurrent); // for (Integer iCurrent : alCurrent) // { // hashDeselectedPolylines.put(iCurrent, null); // } } for (ArrayList<Integer> alCurrent : hashIsNANBlocking.values()) { contentSelectionManager.addToType(SelectionType.DESELECTED, alCurrent); // for (Integer iCurrent : alCurrent) // { // hashDeselectedPolylines.put(iCurrent, null); // } } if (bIsDraggingActive || bIsAngularBrushingActive) { // triggerSelectionUpdate(); } // for (int iCurrent : hashDeselectedPolylines.keySet()) // { // polylineSelectionManager.addToType(SelectionType.DESELECTED, // alCurrent); // polylineSelectionManager.addToType(SelectionType.DESELECTED, // iCurrent); // } } private void triggerSelectionUpdate() { SelectionUpdateEvent selectionUpdateEvent = new SelectionUpdateEvent(); selectionUpdateEvent.setDataDomainType(dataDomain.getDataDomainType()); selectionUpdateEvent.setSelectionDelta(contentSelectionManager.getDelta()); selectionUpdateEvent.setSender(this); eventPublisher.triggerEvent(selectionUpdateEvent); // send out a major update which tells the hhm to update its textures UpdateViewEvent updateView = new UpdateViewEvent(); updateView.setSender(this); eventPublisher.triggerEvent(updateView); } @Override protected void handlePickingEvents(final EPickingType ePickingType, final EPickingMode ePickingMode, final int iExternalID, final Pick pick) { if (detailLevel == EDetailLevel.VERY_LOW || bIsDraggingActive || bWasAxisMoved) { return; } SelectionType selectionType; switch (ePickingType) { case PCS_VIEW_SELECTION: break; case POLYLINE_SELECTION: switch (ePickingMode) { case CLICKED: selectionType = SelectionType.SELECTION; if (bAngularBrushingSelectPolyline) { bAngularBrushingSelectPolyline = false; bIsAngularBrushingActive = true; iSelectedLineID = iExternalID; linePick = pick; bIsAngularBrushingFirstTime = true; } break; case MOUSE_OVER: selectionType = SelectionType.MOUSE_OVER; break; case RIGHT_CLICKED: selectionType = SelectionType.SELECTION; // Prevent handling of non genetic data in context menu if (!dataDomain.getDataDomainType().equals( "org.caleydo.datadomain.genetic")) break; ContentContextMenuItemContainer geneContextMenuItemContainer = new ContentContextMenuItemContainer(); geneContextMenuItemContainer.setID(EIDType.EXPRESSION_INDEX, iExternalID); contextMenu.addItemContanier(geneContextMenuItemContainer); if (!isRenderedRemote()) { contextMenu.setLocation(pick.getPickedPoint(), getParentGLCanvas() .getWidth(), getParentGLCanvas().getHeight()); contextMenu.setMasterGLView(this); } break; default: return; } if (contentSelectionManager.checkStatus(selectionType, iExternalID)) { break; } connectedElementRepresentationManager.clear(contentSelectionManager .getIDType()); contentSelectionManager.clearSelection(selectionType); // TODO: Integrate multi spotting support again // if (ePolylineDataType == EIDType.EXPRESSION_INDEX) { // // Resolve multiple spotting on chip and add all to the // // selection manager. // Integer iRefSeqID = // idMappingManager.getID(EMappingType.EXPRESSION_INDEX_2_REFSEQ_MRNA_INT, // iExternalID); // if (iRefSeqID == null) { // pickingManager.flushHits(iUniqueID, ePickingType); // return; // } // int iConnectionID = // generalManager.getIDManager().createID(EManagedObjectType.CONNECTION); // for (Object iExpressionIndex : idMappingManager.getMultiID( // EMappingType.REFSEQ_MRNA_INT_2_EXPRESSION_INDEX, iRefSeqID)) // { // polylineSelectionManager.addToType(SelectionType, (Integer) // iExpressionIndex); // polylineSelectionManager.addConnectionID(iConnectionID, // (Integer) iExpressionIndex); // } // } // else { contentSelectionManager.addToType(selectionType, iExternalID); contentSelectionManager.addConnectionID(generalManager.getIDManager() .createID(EManagedObjectType.CONNECTION), iExternalID); // } // if (ePolylineDataType == EIDType.EXPRESSION_INDEX && // !bAngularBrushingSelectPolyline) { if (!bAngularBrushingSelectPolyline) { // // // SelectionCommand command = new SelectionCommand( // ESelectionCommandType.CLEAR, selectionType); // sendSelectionCommandEvent(EIDType.EXPRESSION_INDEX, command); ISelectionDelta selectionDelta = contentSelectionManager.getDelta(); handleConnectedElementRep(selectionDelta); SelectionUpdateEvent event = new SelectionUpdateEvent(); event.setSender(this); event.setDataDomainType(dataDomain.getDataDomainType()); event.setSelectionDelta((SelectionDelta) selectionDelta); event.setInfo(getShortInfoLocal()); eventPublisher.triggerEvent(event); } setDisplayListDirty(); break; case X_AXIS_SELECTION: break; case Y_AXIS_SELECTION: switch (ePickingMode) { case CLICKED: selectionType = SelectionType.SELECTION; break; case MOUSE_OVER: selectionType = SelectionType.MOUSE_OVER; break; case RIGHT_CLICKED: selectionType = SelectionType.SELECTION; if (!isRenderedRemote()) { contextMenu.setLocation(pick.getPickedPoint(), getParentGLCanvas() .getWidth(), getParentGLCanvas().getHeight()); contextMenu.setMasterGLView(this); } ExperimentContextMenuItemContainer experimentContextMenuItemContainer = new ExperimentContextMenuItemContainer(); experimentContextMenuItemContainer.setID(iExternalID); contextMenu.addItemContanier(experimentContextMenuItemContainer); default: return; } storageSelectionManager.clearSelection(selectionType); storageSelectionManager.addToType(selectionType, iExternalID); storageSelectionManager.addConnectionID(generalManager.getIDManager() .createID(EManagedObjectType.CONNECTION), iExternalID); connectedElementRepresentationManager.clear(storageSelectionManager .getIDType()); // triggerSelectionUpdate(EMediatorType.SELECTION_MEDIATOR, // axisSelectionManager // .getDelta(), null); // SelectionCommand command = new SelectionCommand( // ESelectionCommandType.CLEAR, selectionType); // sendSelectionCommandEvent(eAxisDataType, command); ISelectionDelta selectionDelta = storageSelectionManager.getDelta(); if (storageSelectionManager.getIDType() == EIDType.EXPERIMENT_INDEX) { handleConnectedElementRep(selectionDelta); } SelectionUpdateEvent event = new SelectionUpdateEvent(); event.setSender(this); event.setDataDomainType(dataDomain.getDataDomainType()); event.setSelectionDelta((SelectionDelta) selectionDelta); eventPublisher.triggerEvent(event); setDisplayListDirty(); break; case GATE_TIP_SELECTION: switch (ePickingMode) { case MOUSE_OVER: iDraggedGateNumber = iExternalID; draggedObject = EPickingType.GATE_TIP_SELECTION; setDisplayListDirty(); break; case CLICKED: bIsDraggingActive = true; draggedObject = EPickingType.GATE_TIP_SELECTION; iDraggedGateNumber = iExternalID; break; // case DRAGGED: // bIsDraggingActive = true; // draggedObject = EPickingType.GATE_TIP_SELECTION; // iDraggedGateNumber = iExternalID; // break; } break; case GATE_BOTTOM_SELECTION: switch (ePickingMode) { case MOUSE_OVER: iDraggedGateNumber = iExternalID; draggedObject = EPickingType.GATE_BOTTOM_SELECTION; setDisplayListDirty(); break; case CLICKED: bIsDraggingActive = true; draggedObject = EPickingType.GATE_BOTTOM_SELECTION; iDraggedGateNumber = iExternalID; break; } break; case GATE_BODY_SELECTION: switch (ePickingMode) { case MOUSE_OVER: iDraggedGateNumber = iExternalID; draggedObject = EPickingType.GATE_BODY_SELECTION; setDisplayListDirty(); break; case CLICKED: bIsDraggingActive = true; bIsGateDraggingFirstTime = true; draggedObject = EPickingType.GATE_BODY_SELECTION; iDraggedGateNumber = iExternalID; break; } break; case PC_ICON_SELECTION: switch (ePickingMode) { case CLICKED: break; } break; case REMOVE_AXIS: switch (ePickingMode) { case MOUSE_OVER: dropTexture = EIconTextures.DROP_DELETE; iChangeDropOnAxisNumber = iExternalID; break; case CLICKED: if (storageVA.containsElement(storageVA.get(iExternalID)) == 1) { removeGate(storageVA.get(iExternalID)); } storageVA.remove(iExternalID); storageSelectionManager.remove(iExternalID, false); StorageVADelta vaDelta = new StorageVADelta(StorageVAType.STORAGE, EIDType.EXPERIMENT_INDEX); vaDelta.add(VADeltaItem.remove(iExternalID)); sendStorageVAUpdateEvent(vaDelta); setDisplayListDirty(); resetAxisSpacing(); break; } break; case MOVE_AXIS: switch (ePickingMode) { case CLICKED: bWasAxisMoved = true; bWasAxisDraggedFirstTime = true; iMovedAxisPosition = iExternalID; setDisplayListDirty(); case MOUSE_OVER: dropTexture = EIconTextures.DROP_MOVE; iChangeDropOnAxisNumber = iExternalID; setDisplayListDirty(); break; } break; case DUPLICATE_AXIS: switch (ePickingMode) { case MOUSE_OVER: dropTexture = EIconTextures.DROP_DUPLICATE; iChangeDropOnAxisNumber = iExternalID; break; case CLICKED: if (iExternalID >= 0) { storageVA.copy(iExternalID); StorageVADelta vaDelta = new StorageVADelta(StorageVAType.STORAGE, EIDType.EXPERIMENT_INDEX); vaDelta.add(VADeltaItem.copy(iExternalID)); sendStorageVAUpdateEvent(vaDelta); setDisplayListDirty(); // resetSelections(); // initGates(); resetAxisSpacing(); break; } } break; case ADD_GATE: switch (ePickingMode) { case CLICKED: hasFilterChanged = true; AGate gate; if (set.isSetHomogeneous()) { gate = new Gate(++iGateCounter, iExternalID, (float) set.getRawForNormalized(0), (float) set.getRawForNormalized(0.5f), set, renderStyle); } else { gate = new NominalGate(++iGateCounter, iExternalID, 0, 0.5f, set, renderStyle); } hashGates.put(this.iGateCounter, gate); hashIsGateBlocking.put(this.iGateCounter, new ArrayList<Integer>()); handleUnselection(); triggerSelectionUpdate(); setDisplayListDirty(); break; } break; case ADD_MASTER_GATE: switch (ePickingMode) { case CLICKED: hasFilterChanged = true; Gate gate = new Gate(++iGateCounter, -1, (float) set.getRawForNormalized(0), (float) set.getRawForNormalized(0.5f), set, renderStyle); gate.setMasterGate(true); hashMasterGates.put(iGateCounter, gate); hashIsGateBlocking.put(iGateCounter, new ArrayList<Integer>()); handleUnselection(); triggerSelectionUpdate(); setDisplayListDirty(); break; } break; case REMOVE_GATE: switch (ePickingMode) { case CLICKED: hasFilterChanged = true; // either the gate belongs to the normal or to the master gates if (hashGates.remove(iExternalID) == null) hashMasterGates.remove(iExternalID); hashIsGateBlocking.remove(iExternalID); handleUnselection(); triggerSelectionUpdate(); setDisplayListDirty(); break; } break; case ANGULAR_UPPER: switch (ePickingMode) { case CLICKED: bIsAngularDraggingActive = true; case DRAGGED: bIsAngularDraggingActive = true; } break; case ANGULAR_LOWER: switch (ePickingMode) { case CLICKED: bIsAngularDraggingActive = true; case DRAGGED: bIsAngularDraggingActive = true; } break; case REMOVE_NAN: switch (ePickingMode) { case CLICKED: hasFilterChanged = true; if (hashExcludeNAN.containsKey(iExternalID)) { hashExcludeNAN.remove(iExternalID); } else { hashExcludeNAN.put(iExternalID, null); } setDisplayListDirty(); break; } break; } } private void sendContentVAUpdateEvent(ContentVADelta delta) { ContentVAUpdateEvent virtualArrayUpdateEvent = new ContentVAUpdateEvent(); virtualArrayUpdateEvent.setSender(this); virtualArrayUpdateEvent.setDataDomainType(dataDomain.getDataDomainType()); virtualArrayUpdateEvent.setVirtualArrayDelta(delta); virtualArrayUpdateEvent.setInfo(getShortInfoLocal()); eventPublisher.triggerEvent(virtualArrayUpdateEvent); } private void sendStorageVAUpdateEvent(StorageVADelta delta) { StorageVAUpdateEvent virtualArrayUpdateEvent = new StorageVAUpdateEvent(); virtualArrayUpdateEvent.setSender(this); virtualArrayUpdateEvent.setDataDomainType(dataDomain.getDataDomainType()); virtualArrayUpdateEvent.setVirtualArrayDelta(delta); virtualArrayUpdateEvent.setInfo(getShortInfoLocal()); eventPublisher.triggerEvent(virtualArrayUpdateEvent); } @Override protected ArrayList<SelectedElementRep> createElementRep(EIDType idType, int iStorageIndex) throws InvalidAttributeValueException { ArrayList<SelectedElementRep> alElementReps = new ArrayList<SelectedElementRep>(); float x = 0; float y = 0; if (idType == EIDType.EXPERIMENT_INDEX && dataDomain.getDataDomainType() .equals("org.caleydo.datadomain.genetic")) { int axisCount = storageVA.indexOf(iStorageIndex); // for (int iAxisID : storageVA) { x = axisCount * renderStyle.getAxisSpacing(storageVA.size()); axisCount++; x = x + renderStyle.getXSpacing(); y = renderStyle.getBottomSpacing(); // y =set.get(storageVA.get(storageVA.size() - 1)).getFloat( // EDataRepresentation.NORMALIZED, iAxisID); alElementReps.add(new SelectedElementRep(idType, iUniqueID, x, y, 0.0f)); // } // } // else if (idType == EIDType.EXPERIMENT_INDEX // && dataDomain.getDataDomainType().equals( // "org.caleydo.datadomain.clinical")) { // System.out.println("wu"); // alElementReps.add(new SelectedElementRep(idType, iUniqueID, 0, 0, // 0.0f)); } else { // if (eAxisDataType == EIDType.EXPERIMENT_RECORD) // fXValue = viewFrustum.getRight() - 0.2f; // else // fXValue = viewFrustum.getRight() - 0.4f; // if (renderConnectionsLeft) { // x = x + renderStyle.getXSpacing(); // y = // set.get(storageVA.get(0)).getFloat(EDataRepresentation.NORMALIZED, // iStorageIndex); // } else { // if (eAxisDataType == EIDType.EXPERIMENT_RECORD) // fXValue = viewFrustum.getRight() - 0.2f; // else x = viewFrustum.getLeft() + renderStyle.getXSpacing(); y = set.get(storageVA.get(0)).getFloat( EDataRepresentation.NORMALIZED, iStorageIndex); // } // // get the value on the leftmost axis // fYValue = // set.get(storageVA.get(0)).getFloat(EDataRepresentation.NORMALIZED, // iStorageIndex); if (Float.isNaN(y)) { y = NAN_Y_OFFSET * renderStyle.getAxisHeight() + renderStyle.getBottomSpacing(); } else { y = y * renderStyle.getAxisHeight() + renderStyle.getBottomSpacing(); } alElementReps.add(new SelectedElementRep(idType, iUniqueID, x, y, 0.0f)); } return alElementReps; } @Override public String getShortInfo() { String message; int iNumLines = contentVA.size(); if (displayEveryNthPolyline == 1) { message = "Parallel Coordinates - " + iNumLines + " " + dataDomain.getContentLabel(false, true) + " / " + storageVA.size() + " experiments"; } else { message = "Parallel Coordinates - a sample of " + iNumLines / displayEveryNthPolyline + " out of " + iNumLines + " " + dataDomain.getContentLabel(false, true) + " / \n " + storageVA.size() + " experiments"; } return message; } @Override public String getDetailedInfo() { StringBuffer sInfoText = new StringBuffer(); sInfoText.append("<b>Type:</b> Parallel Coordinates\n"); sInfoText.append(contentVA.size() + dataDomain.getContentLabel(false, true) + " as polylines and " + storageVA.size() + " experiments as axis.\n"); if (bRenderOnlyContext) { sInfoText .append("Showing only genes which occur in one of the other views in focus\n"); } else { if (bUseRandomSampling) { sInfoText.append("Random sampling active, sample size: " + iNumberOfRandomElements + "\n"); } else { sInfoText.append("Random sampling inactive\n"); } if (dataFilterLevel == EDataFilterLevel.COMPLETE) { sInfoText.append("Showing all " + dataDomain.getContentLabel(false, true) + " in the dataset\n"); } else if (dataFilterLevel == EDataFilterLevel.ONLY_MAPPING) { sInfoText.append("Showing all " + dataDomain.getContentLabel(false, true) + " that have a known DAVID ID mapping\n"); } else if (dataFilterLevel == EDataFilterLevel.ONLY_CONTEXT) { sInfoText .append("Showing all genes that are contained in any of the KEGG or Biocarta Pathways\n"); } } return sInfoText.toString(); } /** * Re-position a view centered on a element, specified by the element ID * * @param iElementID * the ID of the element that should be in the center */ // TODO private void doTranslation() { float fDelta = 0; if (fXTargetTranslation < fXTranslation - 0.3) { fDelta = -0.3f; } else if (fXTargetTranslation > fXTranslation + 0.3) { fDelta = 0.3f; } else { fDelta = fXTargetTranslation - fXTranslation; bIsTranslationActive = false; } if (elementRep != null) { ArrayList<Vec3f> alPoints = elementRep.getPoints(); for (Vec3f currentPoint : alPoints) { currentPoint.setX(currentPoint.x() + fDelta); } } fXTranslation += fDelta; } // TODO private void handleAngularBrushing(final GL gl) { hasFilterChanged = true; if (bIsAngularBrushingFirstTime) { fCurrentAngle = fDefaultAngle; Point currentPoint = linePick.getPickedPoint(); float[] fArPoint = GLCoordinateUtils .convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x, currentPoint.y); vecAngularBrushingPoint = new Vec3f(fArPoint[0], fArPoint[1], 0.01f); bIsAngularBrushingFirstTime = false; } alIsAngleBlocking.get(0).clear(); int iPosition = 0; for (int iCount = 0; iCount < alAxisSpacing.size() - 1; iCount++) { if (vecAngularBrushingPoint.x() > alAxisSpacing.get(iCount) && vecAngularBrushingPoint.x() < alAxisSpacing.get(iCount + 1)) { iPosition = iCount; } } int iAxisLeftIndex; int iAxisRightIndex; iAxisLeftIndex = storageVA.get(iPosition); iAxisRightIndex = storageVA.get(iPosition + 1); Vec3f vecLeftPoint = new Vec3f(0, 0, 0); Vec3f vecRightPoint = new Vec3f(0, 0, 0); vecLeftPoint.setY(set.get(iAxisLeftIndex).getFloat( EDataRepresentation.NORMALIZED, iSelectedLineID) * renderStyle.getAxisHeight()); vecRightPoint.setY(set.get(iAxisRightIndex).getFloat( EDataRepresentation.NORMALIZED, iSelectedLineID) * renderStyle.getAxisHeight()); vecLeftPoint.setX(alAxisSpacing.get(iPosition)); vecRightPoint.setX(alAxisSpacing.get(iPosition + 1)); Vec3f vecDirectional = vecRightPoint.minus(vecLeftPoint); float fLength = vecDirectional.length(); vecDirectional.normalize(); Vec3f vecTriangleOrigin = vecLeftPoint.addScaled(fLength / 4, vecDirectional); Vec3f vecTriangleLimit = vecLeftPoint.addScaled(fLength / 4 * 3, vecDirectional); Rotf rotf = new Rotf(); Vec3f vecCenterLine = vecTriangleLimit.minus(vecTriangleOrigin); float fLegLength = vecCenterLine.length(); if (bIsAngularDraggingActive) { Point pickedPoint = glMouseListener.getPickedPoint(); float fArPoint[] = GLCoordinateUtils .convertWindowCoordinatesToWorldCoordinates(gl, pickedPoint.x, pickedPoint.y); Vec3f vecPickedPoint = new Vec3f(fArPoint[0], fArPoint[1], 0.01f); Vec3f vecTempLine = vecPickedPoint.minus(vecTriangleOrigin); fCurrentAngle = getAngle(vecTempLine, vecCenterLine); bIsDisplayListDirtyLocal = true; bIsDisplayListDirtyRemote = true; } rotf.set(new Vec3f(0, 0, 1), fCurrentAngle); Vec3f vecUpperPoint = rotf.rotateVector(vecCenterLine); rotf.set(new Vec3f(0, 0, 1), -fCurrentAngle); Vec3f vecLowerPoint = rotf.rotateVector(vecCenterLine); vecUpperPoint.add(vecTriangleOrigin); vecLowerPoint.add(vecTriangleOrigin); gl.glColor4fv(ANGULAR_COLOR, 0); gl.glLineWidth(ANGLUAR_LINE_WIDTH); gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.ANGULAR_UPPER, iPosition)); gl.glBegin(GL.GL_LINES); gl.glVertex3f(vecTriangleOrigin.x(), vecTriangleOrigin.y(), vecTriangleOrigin.z() + 0.02f); gl.glVertex3f(vecUpperPoint.x(), vecUpperPoint.y(), vecUpperPoint.z() + 0.02f); gl.glEnd(); gl.glPopName(); gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.ANGULAR_UPPER, iPosition)); gl.glBegin(GL.GL_LINES); gl.glVertex3f(vecTriangleOrigin.x(), vecTriangleOrigin.y(), vecTriangleOrigin.z() + 0.02f); gl.glVertex3f(vecLowerPoint.x(), vecLowerPoint.y(), vecLowerPoint.z() + 0.02f); gl.glEnd(); gl.glPopName(); // draw angle polygon gl.glColor4fv(ANGULAR_POLYGON_COLOR, 0); // gl.glColor4f(1, 0, 0, 0.5f); gl.glBegin(GL.GL_POLYGON); rotf.set(new Vec3f(0, 0, 1), -fCurrentAngle / 10); Vec3f tempVector = vecCenterLine.copy(); gl.glVertex3f(vecTriangleOrigin.x(), vecTriangleOrigin.y(), vecTriangleOrigin.z() + 0.02f); for (int iCount = 0; iCount <= 10; iCount++) { Vec3f vecPoint = tempVector.copy(); vecPoint.normalize(); vecPoint.scale(fLegLength); gl.glVertex3f(vecTriangleOrigin.x() + vecPoint.x(), vecTriangleOrigin.y() + vecPoint.y(), vecTriangleOrigin.z() + vecPoint.z() + 0.02f); tempVector = rotf.rotateVector(tempVector); } gl.glEnd(); gl.glBegin(GL.GL_POLYGON); rotf.set(new Vec3f(0, 0, 1), fCurrentAngle / 10); tempVector = vecCenterLine.copy(); gl.glVertex3f(vecTriangleOrigin.x(), vecTriangleOrigin.y(), vecTriangleOrigin.z() + 0.02f); for (int iCount = 0; iCount <= 10; iCount++) { Vec3f vecPoint = tempVector.copy(); vecPoint.normalize(); vecPoint.scale(fLegLength); gl.glVertex3f(vecTriangleOrigin.x() + vecPoint.x(), vecTriangleOrigin.y() + vecPoint.y(), vecTriangleOrigin.z() + vecPoint.z() + 0.02f); tempVector = rotf.rotateVector(tempVector); } // gl.glVertex3f(vecUpperPoint.x(), vecUpperPoint.y(), vecUpperPoint.z() // + 0.02f); gl.glEnd(); // check selection for (Integer iCurrent : contentVA) { vecLeftPoint.setY(set.get(iAxisLeftIndex).getFloat( EDataRepresentation.NORMALIZED, iCurrent) * renderStyle.getAxisHeight()); vecRightPoint.setY(set.get(iAxisRightIndex).getFloat( EDataRepresentation.NORMALIZED, iCurrent) * renderStyle.getAxisHeight()); vecLeftPoint.setX(alAxisSpacing.get(iPosition)); vecRightPoint.setX(alAxisSpacing.get(iPosition + 1)); // Vec3f vecCompareLine = vecLeftPoint.minus(vecRightPoint); Vec3f vecCompareLine = vecRightPoint.minus(vecLeftPoint); float fCompareAngle = getAngle(vecCompareLine, vecCenterLine); if (fCompareAngle > fCurrentAngle || fCompareAngle < -fCurrentAngle) // !(fCompareAngle < fAngle && fCompareAngle < -fAngle)) { // contentSelectionManager.addToType(EViewInternalSelectionType // .DESELECTED, iCurrent); alIsAngleBlocking.get(0).add(iCurrent); } // else // { // // TODO combinations // //contentSelectionManager.addToType(EViewInternalSelectionType. // NORMAL, iCurrent); // } } if (glMouseListener.wasMouseReleased()) { bIsAngularDraggingActive = false; // bIsAngularBrushingActive = false; } } private float getAngle(final Vec3f vecOne, final Vec3f vecTwo) { Vec3f vecNewOne = vecOne.copy(); Vec3f vecNewTwo = vecTwo.copy(); vecNewOne.normalize(); vecNewTwo.normalize(); float fTmp = vecNewOne.dot(vecNewTwo); return (float) Math.acos(fTmp); } private void adjustAxisSpacing(GL gl) { Point currentPoint = glMouseListener.getPickedPoint(); float[] fArTargetWorldCoordinates = GLCoordinateUtils .convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x, currentPoint.y); float fWidth = fArTargetWorldCoordinates[0] - fXTranslation - fXDefaultTranslation; if (bWasAxisDraggedFirstTime) { // adjust from the actually clicked point to the center of the axis fAxisDraggingOffset = fWidth - alAxisSpacing.get(iMovedAxisPosition); bWasAxisDraggedFirstTime = false; } fWidth -= fAxisDraggingOffset; if (fWidth < renderStyle.getXAxisStart()) { fWidth = renderStyle.getXAxisStart(); } if (fWidth > renderStyle.getXAxisEnd()) { fWidth = renderStyle.getXAxisEnd(); } int iSwitchAxisWithThis = -1; for (int iCount = 0; iCount < alAxisSpacing.size(); iCount++) { if (iMovedAxisPosition > iCount && fWidth < alAxisSpacing.get(iCount)) { iSwitchAxisWithThis = iCount; break; } if (iMovedAxisPosition < iCount && fWidth > alAxisSpacing.get(iCount)) { iSwitchAxisWithThis = iCount; } } if (iSwitchAxisWithThis != -1) { storageVA.move(iMovedAxisPosition, iSwitchAxisWithThis); alAxisSpacing.remove(iMovedAxisPosition); alAxisSpacing.add(iSwitchAxisWithThis, fWidth); StorageVADelta vaDelta = new StorageVADelta(storageVAType, EIDType.EXPERIMENT_INDEX); vaDelta.add(VADeltaItem.move(iMovedAxisPosition, iSwitchAxisWithThis)); sendStorageVAUpdateEvent(vaDelta); iMovedAxisPosition = iSwitchAxisWithThis; } else { alAxisSpacing.set(iMovedAxisPosition, fWidth); } setDisplayListDirty(); } private void handleTrackInput(final GL gl) { // TODO: very performance intensive - better solution needed (only in // reshape)! getParentGLCanvas().getParentComposite().getDisplay().asyncExec(new Runnable() { @Override public void run() { upperLeftScreenPos = getParentGLCanvas().getParentComposite().toDisplay( 1, 1); } }); Rectangle screenRect = getParentGLCanvas().getBounds(); float[] fArTrackPos = generalManager.getTrackDataProvider().getEyeTrackData(); fArTrackPos[0] -= upperLeftScreenPos.x; fArTrackPos[1] -= upperLeftScreenPos.y; // GLHelperFunctions.drawPointAt(gl, new Vec3f(fArTrackPos[0] / // screenRect.width * 8f, // (1f - fArTrackPos[1] / screenRect.height) * 8f * fAspectRatio, // 0.01f)); float fTrackX = (generalManager.getTrackDataProvider().getEyeTrackData()[0]) / screenRect.width; fTrackX *= renderStyle.getWidthOfCoordinateSystem(); int iAxisNumber = 0; for (int iCount = 0; iCount < alAxisSpacing.size() - 1; iCount++) { if (alAxisSpacing.get(iCount) < fTrackX && alAxisSpacing.get(iCount + 1) > fTrackX) { if (fTrackX - alAxisSpacing.get(iCount) < alAxisSpacing.get(iCount) - fTrackX) { iAxisNumber = iCount; } else { iAxisNumber = iCount + 1; } break; } } int iNumberOfAxis = storageVA.size(); float fOriginalAxisSpacing = renderStyle.getAxisSpacing(iNumberOfAxis); float fFocusAxisSpacing = fOriginalAxisSpacing * 2; float fReducedSpacing = (renderStyle.getWidthOfCoordinateSystem() - 2 * fFocusAxisSpacing) / (iNumberOfAxis - 3); float fCurrentX = 0; alAxisSpacing.clear(); for (int iCount = 0; iCount < iNumberOfAxis; iCount++) { alAxisSpacing.add(fCurrentX); if (iCount + 1 == iAxisNumber || iCount == iAxisNumber) { fCurrentX += fFocusAxisSpacing; } else { fCurrentX += fReducedSpacing; } } setDisplayListDirty(); } // private void focusOnAreaWii() { // if (!generalManager.isWiiModeActive()) // return; // // WiiRemote wii = generalManager.getWiiRemote(); // // float fXWiiPosition = wii.getCurrentSmoothHeadPosition()[0] + 1f; // // // we assume that this is far right, and -fMax is far left // float fMaxX = 2; // // if (fXWiiPosition > fMaxX) { // fXWiiPosition = fMaxX; // } // else if (fXWiiPosition < -fMaxX) { // fXWiiPosition = -fMaxX; // } // // // now we normalize to 0 to 1 // fXWiiPosition = (fXWiiPosition + fMaxX) / (2 * fMaxX); // // fXWiiPosition *= renderStyle.getWidthOfCoordinateSystem(); // int iAxisNumber = 0; // for (int iCount = 0; iCount < alAxisSpacing.size() - 1; iCount++) { // if (alAxisSpacing.get(iCount) < fXWiiPosition && alAxisSpacing.get(iCount // + 1) > fXWiiPosition) { // if (fXWiiPosition - alAxisSpacing.get(iCount) < alAxisSpacing.get(iCount) // - fXWiiPosition) { // iAxisNumber = iCount; // } // else { // iAxisNumber = iCount + 1; // } // // break; // } // } // // int iNumberOfAxis = axisVA.size(); // // float fOriginalAxisSpacing = renderStyle.getAxisSpacing(iNumberOfAxis); // // float fFocusAxisSpacing = 2 * fOriginalAxisSpacing; // // float fReducedSpacing = // (renderStyle.getWidthOfCoordinateSystem() - 2 * fFocusAxisSpacing) / // (iNumberOfAxis - 3); // // float fCurrentX = 0; // alAxisSpacing.clear(); // for (int iCount = 0; iCount < iNumberOfAxis; iCount++) { // alAxisSpacing.add(fCurrentX); // if (iCount + 1 == iAxisNumber || iCount == iAxisNumber) { // fCurrentX += fFocusAxisSpacing; // } // else { // fCurrentX += fReducedSpacing; // } // } // // setDisplayListDirty(); // } public void resetAxisSpacing() { alAxisSpacing.clear(); int iNumAxis = storageVA.size(); float fInitAxisSpacing = renderStyle.getAxisSpacing(iNumAxis); for (int iCount = 0; iCount < iNumAxis; iCount++) { alAxisSpacing.add(fInitAxisSpacing * iCount); } setDisplayListDirty(); } @Override public ASerializedView getSerializableRepresentation() { SerializedParallelCoordinatesView serializedForm = new SerializedParallelCoordinatesView( dataDomain.getDataDomainType()); serializedForm.setViewID(this.getID()); return serializedForm; } @Override public void handleUpdateView() { setDisplayListDirty(); } @Override public void destroy() { selectionTransformer.destroy(); super.destroy(); } @Override public void registerEventListeners() { super.registerEventListeners(); applyCurrentSelectionToVirtualArrayListener = new ApplyCurrentSelectionToVirtualArrayListener(); applyCurrentSelectionToVirtualArrayListener.setHandler(this); eventPublisher.addListener(ApplyCurrentSelectionToVirtualArrayEvent.class, applyCurrentSelectionToVirtualArrayListener); resetAxisSpacingListener = new ResetAxisSpacingListener(); resetAxisSpacingListener.setHandler(this); eventPublisher.addListener(ResetAxisSpacingEvent.class, resetAxisSpacingListener); bookmarkListener = new BookmarkButtonListener(); bookmarkListener.setHandler(this); eventPublisher.addListener(BookmarkButtonEvent.class, bookmarkListener); resetViewListener = new ResetViewListener(); resetViewListener.setHandler(this); eventPublisher.addListener(ResetAllViewsEvent.class, resetViewListener); // second event for same listener eventPublisher .addListener(ResetParallelCoordinatesEvent.class, resetViewListener); useRandomSamplingListener = new UseRandomSamplingListener(); useRandomSamplingListener.setHandler(this); eventPublisher.addListener(UseRandomSamplingEvent.class, useRandomSamplingListener); angularBrushingListener = new AngularBrushingListener(); angularBrushingListener.setHandler(this); eventPublisher.addListener(AngularBrushingEvent.class, angularBrushingListener); } @Override public void unregisterEventListeners() { super.unregisterEventListeners(); if (applyCurrentSelectionToVirtualArrayListener != null) { eventPublisher.removeListener(applyCurrentSelectionToVirtualArrayListener); applyCurrentSelectionToVirtualArrayListener = null; } if (resetAxisSpacingListener != null) { eventPublisher.removeListener(resetAxisSpacingListener); resetAxisSpacingListener = null; } if (bookmarkListener != null) { eventPublisher.removeListener(bookmarkListener); bookmarkListener = null; } if (resetViewListener != null) { eventPublisher.removeListener(resetViewListener); resetViewListener = null; } if (angularBrushingListener != null) { eventPublisher.removeListener(angularBrushingListener); angularBrushingListener = null; } } @Override public void handleSelectionCommand(EIDCategory category, SelectionCommand selectionCommand) { if (category == contentSelectionManager.getIDType().getCategory()) contentSelectionManager.executeSelectionCommand(selectionCommand); else if (category == storageSelectionManager.getIDType().getCategory()) storageSelectionManager.executeSelectionCommand(selectionCommand); else return; setDisplayListDirty(); } @Override public String toString() { int iNumElements = (contentSelectionManager.getNumberOfElements() - contentSelectionManager .getNumberOfElements(SelectionType.DESELECTED)); String renderMode = "standalone"; if (isRenderedRemote()) renderMode = "remote"; return ("PCs, " + renderMode + ", " + iNumElements + " elements" + " Axis DT: " + storageSelectionManager.getIDType() + " Polyline DT:" + contentSelectionManager .getIDType()); } @Override public List<AGLView> getRemoteRenderedViews() { return new ArrayList<AGLView>(); } public void setRenderConnectionState(boolean renderConnectionssLeft) { this.renderConnectionsLeft = renderConnectionssLeft; } public ISet getSet() { return set; } }
org.caleydo.view.parcoords/src/org/caleydo/view/parcoords/GLParallelCoordinates.java
package org.caleydo.view.parcoords; import static org.caleydo.view.parcoords.PCRenderStyle.ANGLUAR_LINE_WIDTH; import static org.caleydo.view.parcoords.PCRenderStyle.ANGULAR_COLOR; import static org.caleydo.view.parcoords.PCRenderStyle.ANGULAR_POLYGON_COLOR; import static org.caleydo.view.parcoords.PCRenderStyle.AXIS_MARKER_WIDTH; import static org.caleydo.view.parcoords.PCRenderStyle.AXIS_Z; import static org.caleydo.view.parcoords.PCRenderStyle.LABEL_Z; import static org.caleydo.view.parcoords.PCRenderStyle.NAN_Y_OFFSET; import static org.caleydo.view.parcoords.PCRenderStyle.NUMBER_AXIS_MARKERS; import static org.caleydo.view.parcoords.PCRenderStyle.X_AXIS_COLOR; import static org.caleydo.view.parcoords.PCRenderStyle.X_AXIS_LINE_WIDTH; import static org.caleydo.view.parcoords.PCRenderStyle.Y_AXIS_COLOR; import static org.caleydo.view.parcoords.PCRenderStyle.Y_AXIS_LINE_WIDTH; import static org.caleydo.view.parcoords.PCRenderStyle.Y_AXIS_LOW; import static org.caleydo.view.parcoords.PCRenderStyle.Y_AXIS_MOUSE_OVER_LINE_WIDTH; import static org.caleydo.view.parcoords.PCRenderStyle.Y_AXIS_SELECTED_LINE_WIDTH; import gleem.linalg.Rotf; import gleem.linalg.Vec3f; import java.awt.Point; import java.awt.Rectangle; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.management.InvalidAttributeValueException; import javax.media.opengl.GL; import org.caleydo.core.command.ECommandType; import org.caleydo.core.command.view.opengl.CmdCreateView; import org.caleydo.core.data.collection.INominalStorage; import org.caleydo.core.data.collection.INumericalStorage; import org.caleydo.core.data.collection.ISet; import org.caleydo.core.data.collection.IStorage; import org.caleydo.core.data.collection.storage.EDataRepresentation; import org.caleydo.core.data.mapping.EIDCategory; import org.caleydo.core.data.mapping.EIDType; import org.caleydo.core.data.selection.ContentVAType; import org.caleydo.core.data.selection.ESelectionCommandType; import org.caleydo.core.data.selection.EVAOperation; import org.caleydo.core.data.selection.SelectedElementRep; import org.caleydo.core.data.selection.SelectionCommand; import org.caleydo.core.data.selection.SelectionType; import org.caleydo.core.data.selection.StorageVAType; import org.caleydo.core.data.selection.delta.ContentVADelta; import org.caleydo.core.data.selection.delta.ISelectionDelta; import org.caleydo.core.data.selection.delta.SelectionDelta; import org.caleydo.core.data.selection.delta.StorageVADelta; import org.caleydo.core.data.selection.delta.VADeltaItem; import org.caleydo.core.manager.datadomain.EDataFilterLevel; import org.caleydo.core.manager.event.data.BookmarkEvent; import org.caleydo.core.manager.event.data.ReplaceContentVAInUseCaseEvent; import org.caleydo.core.manager.event.view.ResetAllViewsEvent; import org.caleydo.core.manager.event.view.infoarea.InfoAreaUpdateEvent; import org.caleydo.core.manager.event.view.storagebased.AngularBrushingEvent; import org.caleydo.core.manager.event.view.storagebased.ApplyCurrentSelectionToVirtualArrayEvent; import org.caleydo.core.manager.event.view.storagebased.BookmarkButtonEvent; import org.caleydo.core.manager.event.view.storagebased.ContentVAUpdateEvent; import org.caleydo.core.manager.event.view.storagebased.ResetAxisSpacingEvent; import org.caleydo.core.manager.event.view.storagebased.ResetParallelCoordinatesEvent; import org.caleydo.core.manager.event.view.storagebased.SelectionUpdateEvent; import org.caleydo.core.manager.event.view.storagebased.StorageVAUpdateEvent; import org.caleydo.core.manager.event.view.storagebased.UpdateViewEvent; import org.caleydo.core.manager.event.view.storagebased.UseRandomSamplingEvent; import org.caleydo.core.manager.id.EManagedObjectType; import org.caleydo.core.manager.picking.EPickingMode; import org.caleydo.core.manager.picking.EPickingType; import org.caleydo.core.manager.picking.Pick; import org.caleydo.core.manager.view.StandardTransformer; import org.caleydo.core.serialize.ASerializedView; import org.caleydo.core.util.format.Formatter; import org.caleydo.core.util.preferences.PreferenceConstants; import org.caleydo.core.view.opengl.camera.EProjectionMode; import org.caleydo.core.view.opengl.camera.IViewFrustum; import org.caleydo.core.view.opengl.canvas.AGLView; import org.caleydo.core.view.opengl.canvas.AStorageBasedView; import org.caleydo.core.view.opengl.canvas.EDetailLevel; import org.caleydo.core.view.opengl.canvas.GLCaleydoCanvas; import org.caleydo.core.view.opengl.canvas.listener.ResetViewListener; import org.caleydo.core.view.opengl.canvas.remote.IGLRemoteRenderingView; import org.caleydo.core.view.opengl.mouse.GLMouseListener; import org.caleydo.core.view.opengl.renderstyle.GeneralRenderStyle; import org.caleydo.core.view.opengl.util.GLCoordinateUtils; import org.caleydo.core.view.opengl.util.overlay.contextmenu.container.ContentContextMenuItemContainer; import org.caleydo.core.view.opengl.util.overlay.contextmenu.container.ExperimentContextMenuItemContainer; import org.caleydo.core.view.opengl.util.overlay.infoarea.GLInfoAreaManager; import org.caleydo.core.view.opengl.util.texture.EIconTextures; import org.caleydo.view.bookmarking.GLBookmarkManager; import org.caleydo.view.parcoords.PCRenderStyle.PolyLineState; import org.caleydo.view.parcoords.listener.AngularBrushingListener; import org.caleydo.view.parcoords.listener.ApplyCurrentSelectionToVirtualArrayListener; import org.caleydo.view.parcoords.listener.BookmarkButtonListener; import org.caleydo.view.parcoords.listener.ResetAxisSpacingListener; import org.caleydo.view.parcoords.listener.UseRandomSamplingListener; import org.eclipse.jface.dialogs.MessageDialog; /** * This class is responsible for rendering the parallel coordinates * * @author Alexander Lex (responsible for PC) * @author Marc Streit */ public class GLParallelCoordinates extends AStorageBasedView implements IGLRemoteRenderingView { public final static String VIEW_ID = "org.caleydo.view.parcoords"; private EPickingType draggedObject; /** * Hashes a gate id, which is made up of an axis id + the last three digits * a gate counter (per axis) to a pair of values which make up the upper and * lower gate tip */ private HashMap<Integer, AGate> hashGates; /** * Hash of blocking gates */ private HashMap<Integer, ArrayList<Integer>> hashIsGateBlocking; /** * HashMap for the gates that are used to remove selections across all axes, * when the set is homogeneous */ private HashMap<Integer, Gate> hashMasterGates; /** * Gate counter used for unique ID retrieval for gates. It is shared between * regular and master gates */ private int iGateCounter = 0; /** * HashMap that has flags for all the axes that have NAN */ private HashMap<Integer, Boolean> hashExcludeNAN; private HashMap<Integer, ArrayList<Integer>> hashIsNANBlocking; private ArrayList<ArrayList<Integer>> alIsAngleBlocking; private ArrayList<Float> alAxisSpacing; private int iDraggedGateNumber = 0; private float fXDefaultTranslation = 0; private float fXTranslation = 0; private float fYTranslation = 0; private float fXTargetTranslation = 0; private boolean bIsTranslationActive = false; private boolean bAngularBrushingSelectPolyline = false; private boolean bIsAngularBrushingActive = false; private boolean bIsAngularBrushingFirstTime = false; private boolean bIsAngularDraggingActive = false; private boolean bIsGateDraggingFirstTime = false; private boolean bIsDraggingActive = false; private boolean hasFilterChanged = false; private boolean bWasAxisMoved = false; private boolean bWasAxisDraggedFirstTime = true; private float fAxisDraggingOffset; private int iMovedAxisPosition = -1; private Vec3f vecAngularBrushingPoint; private float fDefaultAngle = (float) Math.PI / 6; private float fCurrentAngle = 0; // private boolean bIsLineSelected = false; private int iSelectedLineID = -1; private Pick linePick; private SelectedElementRep elementRep; // private int iPolylineVAID = 0; // private int iAxisVAID = 0; protected PCRenderStyle renderStyle; private int displayEveryNthPolyline = 1; EIconTextures dropTexture = EIconTextures.DROP_NORMAL; int iChangeDropOnAxisNumber = -1; GLBookmarkManager glBookmarks; boolean bShowSelectionHeatMap = false; private GLInfoAreaManager infoAreaManager; /** Utility object for coordinate transformation and projection */ protected StandardTransformer selectionTransformer; // listeners private ApplyCurrentSelectionToVirtualArrayListener applyCurrentSelectionToVirtualArrayListener; private ResetAxisSpacingListener resetAxisSpacingListener; private BookmarkButtonListener bookmarkListener; private ResetViewListener resetViewListener; private UseRandomSamplingListener useRandomSamplingListener; private AngularBrushingListener angularBrushingListener; private org.eclipse.swt.graphics.Point upperLeftScreenPos = new org.eclipse.swt.graphics.Point( 0, 0); /** * FIXME: remove after data flipper video */ private boolean renderConnectionsLeft = true; /** * Constructor. */ public GLParallelCoordinates(GLCaleydoCanvas glCanvas, final String sLabel, final IViewFrustum viewFrustum) { super(glCanvas, sLabel, viewFrustum); viewType = GLParallelCoordinates.VIEW_ID; renderStyle = new PCRenderStyle(this, viewFrustum); super.renderStyle = this.renderStyle; alIsAngleBlocking = new ArrayList<ArrayList<Integer>>(); alIsAngleBlocking.add(new ArrayList<Integer>()); alAxisSpacing = new ArrayList<Float>(); iNumberOfRandomElements = generalManager.getPreferenceStore().getInt( PreferenceConstants.PC_NUM_RANDOM_SAMPLING_POINT); // glSelectionHeatMap = // ((ViewManager)generalManager.getViewGLCanvasManager()).getSelectionHeatMap(); icon = EIconTextures.PAR_COORDS_ICON; } @Override public void initLocal(final GL gl) { iGLDisplayListIndexLocal = gl.glGenLists(1); iGLDisplayListToCall = iGLDisplayListIndexLocal; // glSelectionHeatMap.addSets(alSets); // glSelectionHeatMap.initRemote(gl, getID(), // glMouseListener, // remoteRenderingGLCanvas); createSelectionHeatMap(gl); infoAreaManager = new GLInfoAreaManager(); infoAreaManager.initInfoInPlace(viewFrustum); selectionTransformer = new StandardTransformer(iUniqueID); init(gl); } @Override public void initRemote(final GL gl, final AGLView glParentView, final GLMouseListener glMouseListener, GLInfoAreaManager infoAreaManager) { bShowSelectionHeatMap = false; this.glMouseListener = glMouseListener; this.infoAreaManager = infoAreaManager; iGLDisplayListIndexRemote = gl.glGenLists(1); iGLDisplayListToCall = iGLDisplayListIndexRemote; selectionTransformer = new StandardTransformer(iUniqueID); init(gl); // toggleRenderContext(); } @Override public void init(final GL gl) { // FIXME: Alex, is it save to call this here? initData(); fXDefaultTranslation = renderStyle.getXSpacing(); fYTranslation = renderStyle.getBottomSpacing(); } @Override public void initData() { super.initData(); initGates(); resetAxisSpacing(); } @Override public void displayLocal(final GL gl) { if (glBookmarks != null) glBookmarks.processEvents(); if (set == null) return; if (bIsTranslationActive) { doTranslation(); } pickingManager.handlePicking(this, gl); if (bIsDisplayListDirtyLocal) { handleUnselection(); buildDisplayList(gl, iGLDisplayListIndexLocal); bIsDisplayListDirtyLocal = false; } iGLDisplayListToCall = iGLDisplayListIndexLocal; checkForHits(gl); display(gl); // ConnectedElementRepresentationManager cerm = // GeneralManager.get().getViewGLCanvasManager().getConnectedElementRepresentationManager(); // cerm.doViewRelatedTransformation(gl, selectionTransformer); if (eBusyModeState != EBusyModeState.OFF) { renderBusyMode(gl); } } @Override public void displayRemote(final GL gl) { if (set == null) return; if (bIsTranslationActive) { doTranslation(); } handleUnselection(); if (bIsDisplayListDirtyRemote) { buildDisplayList(gl, iGLDisplayListIndexRemote); bIsDisplayListDirtyRemote = false; } iGLDisplayListToCall = iGLDisplayListIndexRemote; display(gl); checkForHits(gl); } @Override public void display(final GL gl) { gl.glEnable(GL.GL_BLEND); if (bShowSelectionHeatMap) { gl.glTranslatef(viewFrustum.getRight() - glBookmarks.getViewFrustum().getWidth(), 0, 0.002f); // Render memo pad background IViewFrustum sHMFrustum = glBookmarks.getViewFrustum(); sHMFrustum.setTop(viewFrustum.getTop()); sHMFrustum.setBottom(viewFrustum.getBottom()); gl.glColor4fv(GeneralRenderStyle.PANEL_BACKGROUN_COLOR, 0); gl.glLineWidth(1); gl.glBegin(GL.GL_POLYGON); gl.glVertex3f(0, 0, 0); gl.glVertex3f(glBookmarks.getViewFrustum().getWidth(), 0, 0); gl.glVertex3f(glBookmarks.getViewFrustum().getWidth(), glBookmarks .getViewFrustum().getHeight(), 0); gl.glVertex3f(0, glBookmarks.getViewFrustum().getHeight(), 0); gl.glEnd(); int iPickingID = pickingManager.getPickingID(iUniqueID, EPickingType.PCS_VIEW_SELECTION, glBookmarks.getID()); gl.glPushName(iPickingID); glBookmarks.displayRemote(gl); gl.glPopName(); gl.glTranslatef(-viewFrustum.getRight() + glBookmarks.getViewFrustum().getWidth(), 0, -0.002f); } if (generalManager.getTrackDataProvider().isTrackModeActive()) handleTrackInput(gl); // TODO another display list // clipToFrustum(gl); gl.glTranslatef(fXDefaultTranslation + fXTranslation, fYTranslation, 0.0f); if (bIsDraggingActive) { handleGateDragging(gl); } if (bWasAxisMoved) { adjustAxisSpacing(gl); if (glMouseListener.wasMouseReleased()) { bWasAxisMoved = false; } } gl.glCallList(iGLDisplayListToCall); if (bIsAngularBrushingActive && iSelectedLineID != -1) { handleAngularBrushing(gl); } gl.glTranslatef(-fXDefaultTranslation - fXTranslation, -fYTranslation, 0.0f); if (!isRenderedRemote()) contextMenu.render(gl, this); } private void createSelectionHeatMap(GL gl) { // Create selection panel CmdCreateView cmdCreateGLView = (CmdCreateView) generalManager .getCommandManager().createCommandByType(ECommandType.CREATE_GL_VIEW); cmdCreateGLView.setViewID("org.caleydo.view.bookmarking"); cmdCreateGLView.setAttributes(EProjectionMode.ORTHOGRAPHIC, 0, 0.8f, viewFrustum.getBottom(), viewFrustum.getTop(), -20, 20, -1); cmdCreateGLView.setDataDomainType(dataDomain.getDataDomainType()); cmdCreateGLView.doCommand(); glBookmarks = (GLBookmarkManager) cmdCreateGLView.getCreatedObject(); glBookmarks.setRemoteRenderingGLView(this); glBookmarks.setDataDomain(dataDomain); glBookmarks.initData(); // FIXME: remoteRenderingGLCanvas is null, conceptual error glBookmarks.initRemote(gl, this, glMouseListener, null); } public void triggerAngularBrushing() { bAngularBrushingSelectPolyline = true; setDisplayListDirty(); } @Override public void renderContext(boolean bRenderOnlyContext) { this.bRenderOnlyContext = bRenderOnlyContext; if (bRenderOnlyContext) { contentVA = dataDomain.getContentVA(ContentVAType.CONTENT_CONTEXT); } else { contentVA = dataDomain.getContentVA(ContentVAType.CONTENT); } contentSelectionManager.setVA(contentVA); initContentVariables(); // initGates(); clearAllSelections(); setDisplayListDirty(); } /** * Reset all selections and deselections */ @Override public void clearAllSelections() { initGates(); contentSelectionManager.clearSelections(); storageSelectionManager.clearSelections(); // isEnabled = false; bIsAngularBrushingActive = false; for (ArrayList<Integer> alCurrent : alIsAngleBlocking) { alCurrent.clear(); } for (ArrayList<Integer> alCurrent : hashIsGateBlocking.values()) { alCurrent.clear(); } setDisplayListDirty(); connectedElementRepresentationManager.clear(EIDType.EXPRESSION_INDEX); if (glBookmarks != null) { glBookmarks.clearAllSelections(); } } /** * Sends a bookmark event containing all elements which are currently * visible in the pcs, if the number of elements is less than 20. If it's * more than 20 an error message is displayed. */ public void bookmarkElements() { ContentVADelta delta = contentSelectionManager.getBroadcastVADelta(); if (delta.size() > 20) { getParentGLCanvas().getParentComposite().getDisplay() .asyncExec(new Runnable() { @Override public void run() { MessageDialog .openError(getParentGLCanvas().getParentComposite() .getShell(), "Bookmark Limit", "Can not bookmark more than 20 elements - reduce polylines to less than 20 first"); return; } }); return; } if (!isRenderedRemote()) { bShowSelectionHeatMap = true; BookmarkEvent<Integer> bookmarkEvent = new BookmarkEvent<Integer>( EIDType.EXPRESSION_INDEX); for (VADeltaItem item : delta.getAllItems()) { bookmarkEvent.addBookmark(item.getPrimaryID()); } eventPublisher.triggerEvent(bookmarkEvent); resetAxisSpacing(); setDisplayListDirty(); } } public void saveSelection() { // polylineSelectionManager.moveType(SelectionType.DESELECTED, // SelectionType.REMOVE); contentSelectionManager.removeElements(SelectionType.DESELECTED); clearAllSelections(); setDisplayListDirty(); contentVA.setGroupList(null); // todo this doesn't work for turned stuff ReplaceContentVAInUseCaseEvent event = new ReplaceContentVAInUseCaseEvent( dataDomain.getDataDomainType(), contentVAType, contentVA); event.setDataDomainType(dataDomain.getDataDomainType()); event.setSender(this); eventPublisher.triggerEvent(event); } /** * Initializes the array lists that contain the data. Must be run at program * start, every time you exchange axis and polylines and every time you * change storages or selections * */ @Override protected void initLists() { if (bRenderOnlyContext) contentVAType = ContentVAType.CONTENT_CONTEXT; else contentVAType = ContentVAType.CONTENT; contentVA = dataDomain.getContentVA(contentVAType); storageVA = dataDomain.getStorageVA(storageVAType); initContentVariables(); contentSelectionManager.setVA(contentVA); storageSelectionManager.setVA(storageVA); initGates(); } /** * Build mapping between polyline/axis and storage/content for virtual * arrays and selection managers */ private void initContentVariables() { // EIDType contentDataType; // EIDType storageDataType; // if // (dataDomain.getDataDomainType().equals("org.caleydo.datadomain.genetic")) // { // contentDataType = EIDType.EXPRESSION_INDEX; // storageDataType = EIDType.EXPERIMENT_INDEX; // } else if (dataDomain.getDataDomainType().equals( // "org.caleydo.datadomain.clinical") // || dataDomain.getDataDomainType() // .equals("org.caleydo.datadomain.generic")) { // contentDataType = EIDType.EXPERIMENT; // storageDataType = EIDType.EXPERIMENT_INDEX; // // } else { // throw new IllegalStateException("Unsupported data domain (" + // dataDomain // + ") for parallel coordinates"); // } } /** * Initialize the gates. The gate heights are saved in two lists, which * contain the rendering height of the gate */ private void initGates() { hashGates = new HashMap<Integer, AGate>(); hashIsGateBlocking = new HashMap<Integer, ArrayList<Integer>>(); if (set.isSetHomogeneous()) { hashMasterGates = new HashMap<Integer, Gate>(); } hashExcludeNAN = new HashMap<Integer, Boolean>(); hashIsNANBlocking = new HashMap<Integer, ArrayList<Integer>>(); } /** * Build polyline display list. Renders coordinate system, polylines and * gates, by calling the render methods * * @param gl * GL context * @param iGLDisplayListIndex * the index of the display list */ private void buildDisplayList(final GL gl, int iGLDisplayListIndex) { gl.glNewList(iGLDisplayListIndex, GL.GL_COMPILE); if (contentVA.size() == 0) { gl.glTranslatef(-fXDefaultTranslation - fXTranslation, -fYTranslation, 0.0f); renderSymbol(gl, EIconTextures.PAR_COORDS_SYMBOL, 2); gl.glTranslatef(+fXDefaultTranslation + fXTranslation, fYTranslation, 0.0f); } else { if (set.isSetHomogeneous()) { renderMasterGate(gl); } renderCoordinateSystem(gl); for (SelectionType selectionType : contentSelectionManager .getSelectionTypes()) { if (selectionType.isVisible()) { if (selectionType == SelectionType.NORMAL) renderNormalPolylines(gl, selectionType); else renderSelectedPolylines(gl, selectionType); } } renderGates(gl); } gl.glEndList(); } /** * Polyline rendering method. All polylines that are contained in the * polylineSelectionManager and are of the selection type specified in * renderMode * * FIXME this needs to be changed to iterate over the virtual array, * considering the deselected elements * * @param gl * the GL context * @param renderMode * the type of selection in the selection manager to render */ @SuppressWarnings("unchecked") private void renderNormalPolylines(GL gl, SelectionType selectionType) { int nrVisibleLines; nrVisibleLines = contentVA.size() - contentSelectionManager.getNumberOfElements(SelectionType.DESELECTED); displayEveryNthPolyline = (contentVA.size() - contentSelectionManager .getNumberOfElements(SelectionType.DESELECTED)) / iNumberOfRandomElements; if (displayEveryNthPolyline == 0) { displayEveryNthPolyline = 1; } PolyLineState renderState = renderStyle.getPolyLineState(selectionType, nrVisibleLines / displayEveryNthPolyline); // this loop executes once per polyline for (int contentIndex = 0; contentIndex < contentVA.size(); contentIndex += displayEveryNthPolyline) { int contentID = contentVA.get(contentIndex); if (!contentSelectionManager.checkStatus(SelectionType.DESELECTED, contentID)) renderSingleLine(gl, contentID, selectionType, renderState, false); } } private void renderSelectedPolylines(GL gl, SelectionType selectionType) { int nrVisibleLines = contentSelectionManager.getNumberOfElements(selectionType); Iterable<Integer> lines = contentSelectionManager.getElements(selectionType); PolyLineState renderState = renderStyle.getPolyLineState(selectionType, nrVisibleLines / displayEveryNthPolyline); for (Integer contentID : lines) { renderSingleLine(gl, contentID, selectionType, renderState, true); } } private void renderSingleLine(GL gl, Integer polyLineID, SelectionType selectionType, PolyLineState renderState, boolean bRenderingSelection) { // Integer polyLineID = lines.; // if (contentSelectionManager.checkStatus(SelectionType.DESELECTED, // polyLineID)) // continue; gl.glColor4fv(renderState.color, 0); gl.glLineWidth(renderState.lineWidth); if ((selectionType == SelectionType.SELECTION || selectionType == SelectionType.MOUSE_OVER) && detailLevel == EDetailLevel.HIGH) { bRenderingSelection = true; } else bRenderingSelection = false; // if (bUseRandomSampling // && (selectionType == SelectionType.DESELECTED || selectionType == // SelectionType.NORMAL)) { // if (polyLineID % displayEveryNthPolyline != 0) { // continue; // // if(!alUseInRandomSampling.get(contentVA.indexOf(iPolyLineID))) // // continue; // } // } if (selectionType != SelectionType.DESELECTED) { gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.POLYLINE_SELECTION, polyLineID)); } if (!bRenderingSelection) { gl.glBegin(GL.GL_LINE_STRIP); } IStorage currentStorage = null; float fPreviousXValue = 0; float fPreviousYValue = 0; float fCurrentXValue = 0; float fCurrentYValue = 0; // this loop executes once per axis for (int iVertexCount = 0; iVertexCount < storageVA.size(); iVertexCount++) { int iStorageIndex = 0; currentStorage = set.get(storageVA.get(iVertexCount)); iStorageIndex = polyLineID; fCurrentXValue = alAxisSpacing.get(iVertexCount); fCurrentYValue = currentStorage.getFloat(EDataRepresentation.NORMALIZED, iStorageIndex); if (Float.isNaN(fCurrentYValue)) { fCurrentYValue = NAN_Y_OFFSET / renderStyle.getAxisHeight(); } if (iVertexCount != 0) { if (bRenderingSelection) { gl.glBegin(GL.GL_LINES); } gl.glVertex3f(fPreviousXValue, fPreviousYValue * renderStyle.getAxisHeight(), renderState.zDepth); gl.glVertex3f(fCurrentXValue, fCurrentYValue * renderStyle.getAxisHeight(), renderState.zDepth); if (bRenderingSelection) { gl.glEnd(); } } if (bRenderingSelection) { String sRawValue; if (currentStorage instanceof INumericalStorage) { sRawValue = Formatter.formatNumber(currentStorage.getFloat( EDataRepresentation.RAW, iStorageIndex)); } else if (currentStorage instanceof INominalStorage) { sRawValue = ((INominalStorage<String>) currentStorage) .getRaw(iStorageIndex); } else throw new IllegalStateException("Unknown Storage Type"); renderBoxedYValues(gl, fCurrentXValue, fCurrentYValue * renderStyle.getAxisHeight(), sRawValue, selectionType); } fPreviousXValue = fCurrentXValue; fPreviousYValue = fCurrentYValue; } if (!bRenderingSelection) { gl.glEnd(); } if (selectionType != SelectionType.DESELECTED) { gl.glPopName(); } } /** * Render the coordinate system of the parallel coordinates, including the * axis captions and axis-specific buttons * * @param gl * the gl context * @param iNumberAxis */ private void renderCoordinateSystem(GL gl) { textRenderer.setColor(0, 0, 0, 1); int iNumberAxis = storageVA.size(); // draw X-Axis gl.glColor4fv(X_AXIS_COLOR, 0); gl.glLineWidth(X_AXIS_LINE_WIDTH); gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.X_AXIS_SELECTION, 1)); gl.glBegin(GL.GL_LINES); gl.glVertex3f(renderStyle.getXAxisStart(), 0.0f, 0.0f); gl.glVertex3f(renderStyle.getXAxisEnd(), 0.0f, 0.0f); gl.glEnd(); gl.glPopName(); // draw all Y-Axis Set<Integer> selectedSet = storageSelectionManager .getElements(SelectionType.SELECTION); Set<Integer> mouseOverSet = storageSelectionManager .getElements(SelectionType.MOUSE_OVER); int iCount = 0; while (iCount < iNumberAxis) { float fXPosition = alAxisSpacing.get(iCount); if (selectedSet.contains(storageVA.get(iCount))) { gl.glColor4fv(SelectionType.SELECTION.getColor(), 0); gl.glLineWidth(Y_AXIS_SELECTED_LINE_WIDTH); gl.glEnable(GL.GL_LINE_STIPPLE); gl.glLineStipple(2, (short) 0xAAAA); } else if (mouseOverSet.contains(storageVA.get(iCount))) { gl.glColor4fv(SelectionType.MOUSE_OVER.getColor(), 0); gl.glLineWidth(Y_AXIS_MOUSE_OVER_LINE_WIDTH); gl.glEnable(GL.GL_LINE_STIPPLE); gl.glLineStipple(2, (short) 0xAAAA); } else { gl.glColor4fv(Y_AXIS_COLOR, 0); gl.glLineWidth(Y_AXIS_LINE_WIDTH); } gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.Y_AXIS_SELECTION, storageVA.get(iCount))); gl.glBegin(GL.GL_LINES); gl.glVertex3f(fXPosition, Y_AXIS_LOW, AXIS_Z); gl.glVertex3f(fXPosition, renderStyle.getAxisHeight(), AXIS_Z); // Top marker gl.glVertex3f(fXPosition - AXIS_MARKER_WIDTH, renderStyle.getAxisHeight(), AXIS_Z); gl.glVertex3f(fXPosition + AXIS_MARKER_WIDTH, renderStyle.getAxisHeight(), AXIS_Z); gl.glEnd(); gl.glDisable(GL.GL_LINE_STIPPLE); if (detailLevel != EDetailLevel.HIGH || !renderStyle.isEnoughSpaceForText(iNumberAxis)) { // pop the picking id here when we don't want to include the // axis label gl.glPopName(); } if (detailLevel == EDetailLevel.HIGH) { // NaN Button float fXButtonOrigin = alAxisSpacing.get(iCount); Vec3f lowerLeftCorner = new Vec3f(fXButtonOrigin - 0.03f, PCRenderStyle.NAN_Y_OFFSET - 0.03f, PCRenderStyle.NAN_Z); Vec3f lowerRightCorner = new Vec3f(fXButtonOrigin + 0.03f, PCRenderStyle.NAN_Y_OFFSET - 0.03f, PCRenderStyle.NAN_Z); Vec3f upperRightCorner = new Vec3f(fXButtonOrigin + 0.03f, PCRenderStyle.NAN_Y_OFFSET + 0.03f, PCRenderStyle.NAN_Z); Vec3f upperLeftCorner = new Vec3f(fXButtonOrigin - 0.03f, PCRenderStyle.NAN_Y_OFFSET + 0.03f, PCRenderStyle.NAN_Z); Vec3f scalingPivot = new Vec3f(fXButtonOrigin, PCRenderStyle.NAN_Y_OFFSET, PCRenderStyle.NAN_Z); int iPickingID = pickingManager.getPickingID(iUniqueID, EPickingType.REMOVE_NAN, storageVA.get(iCount)); gl.glPushName(iPickingID); textureManager.renderGUITexture(gl, EIconTextures.NAN, lowerLeftCorner, lowerRightCorner, upperRightCorner, upperLeftCorner, scalingPivot, 1, 1, 1, 1, 100); gl.glPopName(); // markers on axis float fMarkerSpacing = renderStyle.getAxisHeight() / (NUMBER_AXIS_MARKERS + 1); for (int iInnerCount = 1; iInnerCount <= NUMBER_AXIS_MARKERS; iInnerCount++) { float fCurrentHeight = fMarkerSpacing * iInnerCount; if (iCount == 0) { if (set.isSetHomogeneous()) { float fNumber = (float) set .getRawForNormalized(fCurrentHeight / renderStyle.getAxisHeight()); Rectangle2D bounds = textRenderer.getScaledBounds(gl, Formatter.formatNumber(fNumber), renderStyle.getSmallFontScalingFactor(), PCRenderStyle.MIN_NUMBER_TEXT_SIZE); float fWidth = (float) bounds.getWidth(); float fHeightHalf = (float) bounds.getHeight() / 3.0f; renderNumber(gl, Formatter.formatNumber(fNumber), fXPosition - fWidth - AXIS_MARKER_WIDTH, fCurrentHeight - fHeightHalf); } else { // TODO: storage based access } } gl.glColor3fv(Y_AXIS_COLOR, 0); gl.glBegin(GL.GL_LINES); gl.glVertex3f(fXPosition - AXIS_MARKER_WIDTH, fCurrentHeight, AXIS_Z); gl.glVertex3f(fXPosition + AXIS_MARKER_WIDTH, fCurrentHeight, AXIS_Z); gl.glEnd(); } String sAxisLabel = null; // switch (eAxisDataType) { // // TODO not very generic here // // case EXPRESSION_INDEX: // // FIXME: Due to new mapping system, a mapping involving // // expression index can return a // // Set of // // values, depending on the IDType that has been // // specified when loading expression // // data. // // Possibly a different handling of the Set is required. // Set<String> setGeneSymbols = idMappingManager.getIDAsSet( // EIDType.EXPRESSION_INDEX, EIDType.GENE_SYMBOL, // axisVA.get(iCount)); // // if ((setGeneSymbols != null && !setGeneSymbols.isEmpty())) { // sAxisLabel = (String) setGeneSymbols.toArray()[0]; // } // if (sAxisLabel == null) // sAxisLabel = "Unknown Gene"; // break; // // case EXPERIMENT: // default: // if (bRenderStorageHorizontally) { // sAxisLabel = "TODO: gene labels for axis"; // } else sAxisLabel = set.get(storageVA.get(iCount)).getLabel(); // break; // } gl.glPushAttrib(GL.GL_CURRENT_BIT | GL.GL_LINE_BIT); gl.glTranslatef( fXPosition, renderStyle.getAxisHeight() + renderStyle.getAxisCaptionSpacing(), 0); gl.glRotatef(25, 0, 0, 1); textRenderer.begin3DRendering(); float fScaling = renderStyle.getSmallFontScalingFactor(); if (isRenderedRemote()) fScaling *= 1.5f; textRenderer.draw3D(gl, sAxisLabel, 0, 0, 0, fScaling, PCRenderStyle.MIN_AXIS_LABEL_TEXT_SIZE); textRenderer.end3DRendering(); gl.glRotatef(-25, 0, 0, 1); gl.glTranslatef(-fXPosition, -(renderStyle.getAxisHeight() + renderStyle .getAxisCaptionSpacing()), 0); if (set.isSetHomogeneous()) { // textRenderer.begin3DRendering(); // // // render values on top and bottom of axis // // // top // String text = getDecimalFormat().format(set.getMax()); // textRenderer.draw3D(text, fXPosition + 2 * // AXIS_MARKER_WIDTH, renderStyle // .getAxisHeight(), 0, // renderStyle.getSmallFontScalingFactor()); // // // bottom // text = getDecimalFormat().format(set.getMin()); // textRenderer.draw3D(text, fXPosition + 2 * // AXIS_MARKER_WIDTH, 0, 0, // renderStyle.getSmallFontScalingFactor()); // textRenderer.end3DRendering(); } else { // TODO } gl.glPopAttrib(); // render Buttons iPickingID = -1; float fYDropOrigin = -PCRenderStyle.AXIS_BUTTONS_Y_OFFSET; gl.glBlendFunc(GL.GL_ONE, GL.GL_ONE_MINUS_SRC_ALPHA); // the gate add button float fYGateAddOrigin = renderStyle.getAxisHeight(); iPickingID = pickingManager.getPickingID(iUniqueID, EPickingType.ADD_GATE, storageVA.get(iCount)); lowerLeftCorner.set(fXButtonOrigin - 0.03f, fYGateAddOrigin, AXIS_Z); lowerRightCorner.set(fXButtonOrigin + 0.03f, fYGateAddOrigin, AXIS_Z); upperRightCorner.set(fXButtonOrigin + 0.03f, fYGateAddOrigin + 0.12f, AXIS_Z); upperLeftCorner.set(fXButtonOrigin - 0.03f, fYGateAddOrigin + 0.12f, AXIS_Z); scalingPivot.set(fXButtonOrigin, fYGateAddOrigin, AXIS_Z); gl.glPushName(iPickingID); textureManager.renderGUITexture(gl, EIconTextures.ADD_GATE, lowerLeftCorner, lowerRightCorner, upperRightCorner, upperLeftCorner, scalingPivot, 1, 1, 1, 1, 100); gl.glPopName(); if (selectedSet.contains(storageVA.get(iCount)) || mouseOverSet.contains(storageVA.get(iCount))) { lowerLeftCorner.set(fXButtonOrigin - 0.15f, fYDropOrigin - 0.3f, AXIS_Z + 0.005f); lowerRightCorner.set(fXButtonOrigin + 0.15f, fYDropOrigin - 0.3f, AXIS_Z + 0.005f); upperRightCorner.set(fXButtonOrigin + 0.15f, fYDropOrigin, AXIS_Z + 0.005f); upperLeftCorner.set(fXButtonOrigin - 0.15f, fYDropOrigin, AXIS_Z + 0.005f); scalingPivot.set(fXButtonOrigin, fYDropOrigin, AXIS_Z + 0.005f); // the mouse over drop if (iChangeDropOnAxisNumber == iCount) { // tempTexture = textureManager.getIconTexture(gl, // dropTexture); textureManager.renderGUITexture(gl, dropTexture, lowerLeftCorner, lowerRightCorner, upperRightCorner, upperLeftCorner, scalingPivot, 1, 1, 1, 1, 80); if (!bWasAxisMoved) { dropTexture = EIconTextures.DROP_NORMAL; } } else { textureManager.renderGUITexture(gl, EIconTextures.DROP_NORMAL, lowerLeftCorner, lowerRightCorner, upperRightCorner, upperLeftCorner, scalingPivot, 1, 1, 1, 1, 80); } iPickingID = pickingManager.getPickingID(iUniqueID, EPickingType.MOVE_AXIS, iCount); gl.glColor4f(0, 0, 0, 0f); gl.glPushName(iPickingID); gl.glBegin(GL.GL_TRIANGLES); gl.glVertex3f(fXButtonOrigin, fYDropOrigin, AXIS_Z + 0.01f); gl.glVertex3f(fXButtonOrigin + 0.08f, fYDropOrigin - 0.3f, AXIS_Z + 0.01f); gl.glVertex3f(fXButtonOrigin - 0.08f, fYDropOrigin - 0.3f, AXIS_Z + 0.01f); gl.glEnd(); gl.glPopName(); iPickingID = pickingManager.getPickingID(iUniqueID, EPickingType.DUPLICATE_AXIS, iCount); // gl.glColor4f(0, 1, 0, 0.5f); gl.glPushName(iPickingID); gl.glBegin(GL.GL_TRIANGLES); gl.glVertex3f(fXButtonOrigin, fYDropOrigin, AXIS_Z + 0.01f); gl.glVertex3f(fXButtonOrigin - 0.08f, fYDropOrigin - 0.21f, AXIS_Z + 0.01f); gl.glVertex3f(fXButtonOrigin - 0.23f, fYDropOrigin - 0.21f, AXIS_Z + 0.01f); gl.glEnd(); gl.glPopName(); iPickingID = pickingManager.getPickingID(iUniqueID, EPickingType.REMOVE_AXIS, iCount); // gl.glColor4f(0, 0, 1, 0.5f); gl.glPushName(iPickingID); gl.glBegin(GL.GL_TRIANGLES); gl.glVertex3f(fXButtonOrigin, fYDropOrigin, AXIS_Z + 0.01f); gl.glVertex3f(fXButtonOrigin + 0.08f, fYDropOrigin - 0.21f, AXIS_Z + 0.01f); gl.glVertex3f(fXButtonOrigin + 0.23f, fYDropOrigin - 0.21f, AXIS_Z + 0.01f); gl.glEnd(); gl.glPopName(); } else { iPickingID = pickingManager.getPickingID(iUniqueID, EPickingType.MOVE_AXIS, iCount); gl.glPushAttrib(GL.GL_CURRENT_BIT | GL.GL_LINE_BIT); gl.glPushName(iPickingID); lowerLeftCorner.set(fXButtonOrigin - 0.05f, fYDropOrigin - 0.2f, AXIS_Z); lowerRightCorner.set(fXButtonOrigin + 0.05f, fYDropOrigin - 0.2f, AXIS_Z); upperRightCorner.set(fXButtonOrigin + 0.05f, fYDropOrigin, AXIS_Z); upperLeftCorner.set(fXButtonOrigin - 0.05f, fYDropOrigin, AXIS_Z); scalingPivot.set(fXButtonOrigin, fYDropOrigin, AXIS_Z); textureManager.renderGUITexture(gl, EIconTextures.SMALL_DROP, lowerLeftCorner, lowerRightCorner, upperRightCorner, upperLeftCorner, scalingPivot, 1, 1, 1, 1, 80); gl.glPopName(); gl.glPopAttrib(); } gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); gl.glPopName(); } iCount++; } } /** * Render the gates and update the fArGateHeights for the * selection/unselection * * @param gl * @param iNumberAxis */ private void renderGates(GL gl) { if (detailLevel != EDetailLevel.HIGH) return; for (Integer iGateID : hashGates.keySet()) { // Gate ID / 1000 is axis ID AGate gate = hashGates.get(iGateID); int iAxisID = gate.getAxisID(); // Pair<Float, Float> gate = hashGates.get(iGateID); // TODO for all indices ArrayList<Integer> iAlAxisIndex = storageVA.indicesOf(iAxisID); for (int iAxisIndex : iAlAxisIndex) { float fCurrentPosition = alAxisSpacing.get(iAxisIndex); gate.setCurrentPosition(fCurrentPosition); // String label = set.get(iAxisID).getLabel(); gate.draw(gl, pickingManager, textureManager, textRenderer, iUniqueID); // renderSingleGate(gl, gate, iAxisID, iGateID, // fCurrentPosition); } } } private void renderMasterGate(GL gl) { if (detailLevel != EDetailLevel.HIGH) return; gl.glColor4f(0, 0, 0, 1f); gl.glLineWidth(PCRenderStyle.Y_AXIS_LINE_WIDTH); // gl.glPushName(iPickingID); float fXOrigin = -0.25f; gl.glBegin(GL.GL_LINES); gl.glVertex3f(fXOrigin, 0, AXIS_Z); gl.glVertex3f(fXOrigin, renderStyle.getAxisHeight(), AXIS_Z); gl.glVertex3f(fXOrigin - AXIS_MARKER_WIDTH, 0, AXIS_Z); gl.glVertex3f(fXOrigin + AXIS_MARKER_WIDTH, 0, AXIS_Z); gl.glVertex3f(fXOrigin - AXIS_MARKER_WIDTH, renderStyle.getAxisHeight(), AXIS_Z); gl.glVertex3f(fXOrigin + AXIS_MARKER_WIDTH, renderStyle.getAxisHeight(), AXIS_Z); gl.glEnd(); gl.glBlendFunc(GL.GL_ONE, GL.GL_ONE_MINUS_SRC_ALPHA); // the gate add button float fYGateAddOrigin = renderStyle.getAxisHeight(); int iPickingID = pickingManager.getPickingID(iUniqueID, EPickingType.ADD_MASTER_GATE, 1); gl.glPushName(iPickingID); Vec3f lowerLeftCorner = new Vec3f(fXOrigin - 0.05f, fYGateAddOrigin, AXIS_Z); Vec3f lowerRightCorner = new Vec3f(fXOrigin + 0.05f, fYGateAddOrigin, AXIS_Z); Vec3f upperRightCorner = new Vec3f(fXOrigin + 0.05f, fYGateAddOrigin + 0.2f, AXIS_Z); Vec3f upperLeftCorner = new Vec3f(fXOrigin - 0.05f, fYGateAddOrigin + 0.2f, AXIS_Z); Vec3f scalingPivot = new Vec3f(fXOrigin, fYGateAddOrigin, AXIS_Z); textureManager.renderGUITexture(gl, EIconTextures.ADD_GATE, lowerLeftCorner, lowerRightCorner, upperRightCorner, upperLeftCorner, scalingPivot, 1, 1, 1, 1, 100); gl.glPopName(); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); for (Integer iGateID : hashMasterGates.keySet()) { Gate gate = hashMasterGates.get(iGateID); Float fBottom = gate.getBottom(); Float fTop = gate.getTop(); gl.glColor4fv(PCRenderStyle.GATE_BODY_COLOR, 0); gl.glBegin(GL.GL_POLYGON); gl.glVertex3f(fXOrigin, fBottom, 0); gl.glVertex3f(viewFrustum.getWidth() - 1, fBottom, 0); gl.glVertex3f(viewFrustum.getWidth() - 1, fTop, 0); // TODO eurovis hacke // gl.glVertex3f(viewFrustum.getWidth(), fBottom, 0); // gl.glVertex3f(viewFrustum.getWidth(), fTop, 0); // gl.glVertex3f(fXOrigin - 0.05f, fTop, 0); gl.glEnd(); gate.setCurrentPosition(fXOrigin); gate.draw(gl, pickingManager, textureManager, textRenderer, iUniqueID); // renderSingleGate(gl, gate, -1, iGateID, fXOrigin); } // gl.glPopName(); } /** * Render the captions on the axis * * @param gl * @param fXOrigin * @param fYOrigin * @param renderMode */ private void renderBoxedYValues(GL gl, float fXOrigin, float fYOrigin, String sRawValue, SelectionType renderMode) { float fScaling = renderStyle.getSmallFontScalingFactor(); if (isRenderedRemote()) fScaling *= 1.5f; // don't render values that are below the y axis if (fYOrigin < 0) return; gl.glPushAttrib(GL.GL_CURRENT_BIT | GL.GL_LINE_BIT); gl.glLineWidth(Y_AXIS_LINE_WIDTH); gl.glColor4fv(Y_AXIS_COLOR, 0); Rectangle2D tempRectangle = textRenderer.getScaledBounds(gl, sRawValue, fScaling, PCRenderStyle.MIN_NUMBER_TEXT_SIZE); float fSmallSpacing = renderStyle.getVerySmallSpacing(); float fBackPlaneWidth = (float) tempRectangle.getWidth(); float fBackPlaneHeight = (float) tempRectangle.getHeight(); float fXTextOrigin = fXOrigin + 2 * AXIS_MARKER_WIDTH; float fYTextOrigin = fYOrigin; gl.glColor4f(1f, 1f, 1f, 0.8f); gl.glBegin(GL.GL_POLYGON); gl.glVertex3f(fXTextOrigin - fSmallSpacing, fYTextOrigin - fSmallSpacing, LABEL_Z); gl.glVertex3f(fXTextOrigin + fBackPlaneWidth, fYTextOrigin - fSmallSpacing, LABEL_Z); gl.glVertex3f(fXTextOrigin + fBackPlaneWidth, fYTextOrigin + fBackPlaneHeight, LABEL_Z); gl.glVertex3f(fXTextOrigin - fSmallSpacing, fYTextOrigin + fBackPlaneHeight, LABEL_Z); gl.glEnd(); renderNumber(gl, sRawValue, fXTextOrigin, fYTextOrigin); gl.glPopAttrib(); } private void renderNumber(GL gl, String sRawValue, float fXOrigin, float fYOrigin) { textRenderer.begin3DRendering(); // String text = ""; // if (Float.isNaN(fRawValue)) // text = "NaN"; // else // text = getDecimalFormat().format(fRawValue); float fScaling = renderStyle.getSmallFontScalingFactor(); if (isRenderedRemote()) fScaling *= 1.5f; textRenderer.draw3D(gl, sRawValue, fXOrigin, fYOrigin, PCRenderStyle.TEXT_ON_LABEL_Z, fScaling, PCRenderStyle.MIN_NUMBER_TEXT_SIZE); textRenderer.end3DRendering(); } /** * Renders the gates and updates their values * * @param gl */ private void handleGateDragging(GL gl) { hasFilterChanged = true; // bIsDisplayListDirtyLocal = true; // bIsDisplayListDirtyRemote = true; Point currentPoint = glMouseListener.getPickedPoint(); float[] fArTargetWorldCoordinates = GLCoordinateUtils .convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x, currentPoint.y); // todo only valid for one gate AGate gate = null; gate = hashGates.get(iDraggedGateNumber); if (gate == null) { gate = hashMasterGates.get(iDraggedGateNumber); if (gate == null) return; } gate.handleDragging(gl, fArTargetWorldCoordinates[0], fArTargetWorldCoordinates[1], draggedObject, bIsGateDraggingFirstTime); bIsGateDraggingFirstTime = false; bIsDisplayListDirtyLocal = true; bIsDisplayListDirtyRemote = true; InfoAreaUpdateEvent event = new InfoAreaUpdateEvent(); event.setDataDomainType(dataDomain.getDataDomainType()); event.setSender(this); event.setInfo(getShortInfoLocal()); eventPublisher.triggerEvent(event); if (glMouseListener.wasMouseReleased()) { bIsDraggingActive = false; } } /** * Unselect all lines that are deselected with the gates * * @param iChangeDropOnAxisNumber */ // TODO revise private void handleGateUnselection() { float fCurrentValue = -1; for (Integer iGateID : hashGates.keySet()) { ArrayList<Integer> alCurrentGateBlocks = hashIsGateBlocking.get(iGateID); if (alCurrentGateBlocks == null) return; alCurrentGateBlocks.clear(); AGate gate = hashGates.get(iGateID); int iAxisID = gate.getAxisID(); if (iAxisID == -1) continue; for (int iPolylineIndex : contentVA) { EDataRepresentation usedDataRepresentation = EDataRepresentation.RAW; if (!set.isSetHomogeneous()) usedDataRepresentation = EDataRepresentation.NORMALIZED; fCurrentValue = set.get(iAxisID).getFloat(usedDataRepresentation, iPolylineIndex); if (Float.isNaN(fCurrentValue)) { continue; } if (fCurrentValue <= gate.getUpperValue() && fCurrentValue >= gate.getLowerValue()) { alCurrentGateBlocks.add(iPolylineIndex); } } } } private void handleNANUnselection() { float fCurrentValue = 0; hashIsNANBlocking.clear(); for (Integer iAxisID : hashExcludeNAN.keySet()) { ArrayList<Integer> alDeselectedLines = new ArrayList<Integer>(); for (int iPolylineIndex : contentVA) { fCurrentValue = set.get(iAxisID).getFloat(EDataRepresentation.NORMALIZED, iPolylineIndex); if (Float.isNaN(fCurrentValue)) { alDeselectedLines.add(iPolylineIndex); } } hashIsNANBlocking.put(iAxisID, alDeselectedLines); } } private void handleMasterGateUnselection() { float fCurrentValue = -1; for (Integer iGateID : hashMasterGates.keySet()) { ArrayList<Integer> alCurrentGateBlocks = hashIsGateBlocking.get(iGateID); if (alCurrentGateBlocks == null) return; alCurrentGateBlocks.clear(); Gate gate = hashMasterGates.get(iGateID); for (int iPolylineIndex : contentVA) { boolean bIsBlocking = true; for (int iAxisIndex : storageVA) { fCurrentValue = set.get(iAxisIndex).getFloat(EDataRepresentation.RAW, iPolylineIndex); if (Float.isNaN(fCurrentValue)) { continue; } if (fCurrentValue <= gate.getUpperValue() && fCurrentValue >= gate.getLowerValue()) { bIsBlocking = true; } else { bIsBlocking = false; break; } } if (bIsBlocking) { alCurrentGateBlocks.add(iPolylineIndex); } } } } @Override protected void reactOnExternalSelection(boolean scrollToSelection) { handleUnselection(); resetAxisSpacing(); } @Override protected void reactOnContentVAChanges(ContentVADelta delta) { contentSelectionManager.setVADelta(delta); } @Override protected void reactOnStorageVAChanges(StorageVADelta delta) { for (VADeltaItem item : delta) { if (item.getType() == EVAOperation.REMOVE) { int iElement = storageVA.get(item.getIndex()); // resetAxisSpacing(); if (storageVA.containsElement(iElement) == 1) { removeGate(iElement); } } else if (item.getType() == EVAOperation.REMOVE_ELEMENT) { removeGate(item.getPrimaryID()); } } storageSelectionManager.setVADelta(delta); resetAxisSpacing(); } /** removes a gate based on an axis id **/ private void removeGate(int axisID) { Iterator<Integer> gateIterator = hashGates.keySet().iterator(); while (gateIterator.hasNext()) { int gateID = gateIterator.next(); if (hashGates.get(gateID).getAxisID() == axisID) { gateIterator.remove(); hashIsGateBlocking.remove(gateID); } } } /** * TODO: revise this, not very performance friendly, especially the clearing * of the DESELECTED */ private void handleUnselection() { if (!hasFilterChanged) return; handleGateUnselection(); handleNANUnselection(); if (set.isSetHomogeneous()) handleMasterGateUnselection(); // HashMap<Integer, Boolean> hashDeselectedPolylines = new // HashMap<Integer, Boolean>(); contentSelectionManager.clearSelection(SelectionType.DESELECTED); for (ArrayList<Integer> alCurrent : hashIsGateBlocking.values()) { contentSelectionManager.addToType(SelectionType.DESELECTED, alCurrent); // for (Integer iCurrent : alCurrent) // { // hashDeselectedPolylines.put(iCurrent, null); // } } for (ArrayList<Integer> alCurrent : alIsAngleBlocking) { contentSelectionManager.addToType(SelectionType.DESELECTED, alCurrent); // for (Integer iCurrent : alCurrent) // { // hashDeselectedPolylines.put(iCurrent, null); // } } for (ArrayList<Integer> alCurrent : hashIsNANBlocking.values()) { contentSelectionManager.addToType(SelectionType.DESELECTED, alCurrent); // for (Integer iCurrent : alCurrent) // { // hashDeselectedPolylines.put(iCurrent, null); // } } if (bIsDraggingActive || bIsAngularBrushingActive) { // triggerSelectionUpdate(); } // for (int iCurrent : hashDeselectedPolylines.keySet()) // { // polylineSelectionManager.addToType(SelectionType.DESELECTED, // alCurrent); // polylineSelectionManager.addToType(SelectionType.DESELECTED, // iCurrent); // } } private void triggerSelectionUpdate() { SelectionUpdateEvent selectionUpdateEvent = new SelectionUpdateEvent(); selectionUpdateEvent.setDataDomainType(dataDomain.getDataDomainType()); selectionUpdateEvent.setSelectionDelta(contentSelectionManager.getDelta()); selectionUpdateEvent.setSender(this); eventPublisher.triggerEvent(selectionUpdateEvent); // send out a major update which tells the hhm to update its textures UpdateViewEvent updateView = new UpdateViewEvent(); updateView.setSender(this); eventPublisher.triggerEvent(updateView); } @Override protected void handlePickingEvents(final EPickingType ePickingType, final EPickingMode ePickingMode, final int iExternalID, final Pick pick) { if (detailLevel == EDetailLevel.VERY_LOW || bIsDraggingActive || bWasAxisMoved) { return; } SelectionType selectionType; switch (ePickingType) { case PCS_VIEW_SELECTION: break; case POLYLINE_SELECTION: switch (ePickingMode) { case CLICKED: selectionType = SelectionType.SELECTION; if (bAngularBrushingSelectPolyline) { bAngularBrushingSelectPolyline = false; bIsAngularBrushingActive = true; iSelectedLineID = iExternalID; linePick = pick; bIsAngularBrushingFirstTime = true; } break; case MOUSE_OVER: selectionType = SelectionType.MOUSE_OVER; break; case RIGHT_CLICKED: selectionType = SelectionType.SELECTION; // Prevent handling of non genetic data in context menu if (!dataDomain.getDataDomainType().equals( "org.caleydo.datadomain.genetic")) break; ContentContextMenuItemContainer geneContextMenuItemContainer = new ContentContextMenuItemContainer(); geneContextMenuItemContainer.setID(EIDType.EXPRESSION_INDEX, iExternalID); contextMenu.addItemContanier(geneContextMenuItemContainer); if (!isRenderedRemote()) { contextMenu.setLocation(pick.getPickedPoint(), getParentGLCanvas() .getWidth(), getParentGLCanvas().getHeight()); contextMenu.setMasterGLView(this); } break; default: return; } if (contentSelectionManager.checkStatus(selectionType, iExternalID)) { break; } connectedElementRepresentationManager.clear(contentSelectionManager .getIDType()); contentSelectionManager.clearSelection(selectionType); // TODO: Integrate multi spotting support again // if (ePolylineDataType == EIDType.EXPRESSION_INDEX) { // // Resolve multiple spotting on chip and add all to the // // selection manager. // Integer iRefSeqID = // idMappingManager.getID(EMappingType.EXPRESSION_INDEX_2_REFSEQ_MRNA_INT, // iExternalID); // if (iRefSeqID == null) { // pickingManager.flushHits(iUniqueID, ePickingType); // return; // } // int iConnectionID = // generalManager.getIDManager().createID(EManagedObjectType.CONNECTION); // for (Object iExpressionIndex : idMappingManager.getMultiID( // EMappingType.REFSEQ_MRNA_INT_2_EXPRESSION_INDEX, iRefSeqID)) // { // polylineSelectionManager.addToType(SelectionType, (Integer) // iExpressionIndex); // polylineSelectionManager.addConnectionID(iConnectionID, // (Integer) iExpressionIndex); // } // } // else { contentSelectionManager.addToType(selectionType, iExternalID); contentSelectionManager.addConnectionID(generalManager.getIDManager() .createID(EManagedObjectType.CONNECTION), iExternalID); // } // if (ePolylineDataType == EIDType.EXPRESSION_INDEX && // !bAngularBrushingSelectPolyline) { if (!bAngularBrushingSelectPolyline) { // // // SelectionCommand command = new SelectionCommand( // ESelectionCommandType.CLEAR, selectionType); // sendSelectionCommandEvent(EIDType.EXPRESSION_INDEX, command); ISelectionDelta selectionDelta = contentSelectionManager.getDelta(); handleConnectedElementRep(selectionDelta); SelectionUpdateEvent event = new SelectionUpdateEvent(); event.setSender(this); event.setDataDomainType(dataDomain.getDataDomainType()); event.setSelectionDelta((SelectionDelta) selectionDelta); event.setInfo(getShortInfoLocal()); eventPublisher.triggerEvent(event); } setDisplayListDirty(); break; case X_AXIS_SELECTION: break; case Y_AXIS_SELECTION: switch (ePickingMode) { case CLICKED: selectionType = SelectionType.SELECTION; break; case MOUSE_OVER: selectionType = SelectionType.MOUSE_OVER; break; case RIGHT_CLICKED: selectionType = SelectionType.SELECTION; if (!isRenderedRemote()) { contextMenu.setLocation(pick.getPickedPoint(), getParentGLCanvas() .getWidth(), getParentGLCanvas().getHeight()); contextMenu.setMasterGLView(this); } ExperimentContextMenuItemContainer experimentContextMenuItemContainer = new ExperimentContextMenuItemContainer(); experimentContextMenuItemContainer.setID(iExternalID); contextMenu.addItemContanier(experimentContextMenuItemContainer); default: return; } storageSelectionManager.clearSelection(selectionType); storageSelectionManager.addToType(selectionType, iExternalID); storageSelectionManager.addConnectionID(generalManager.getIDManager() .createID(EManagedObjectType.CONNECTION), iExternalID); connectedElementRepresentationManager.clear(storageSelectionManager .getIDType()); // triggerSelectionUpdate(EMediatorType.SELECTION_MEDIATOR, // axisSelectionManager // .getDelta(), null); // SelectionCommand command = new SelectionCommand( // ESelectionCommandType.CLEAR, selectionType); // sendSelectionCommandEvent(eAxisDataType, command); ISelectionDelta selectionDelta = storageSelectionManager.getDelta(); if (storageSelectionManager.getIDType() == EIDType.EXPERIMENT_INDEX) { handleConnectedElementRep(selectionDelta); } SelectionUpdateEvent event = new SelectionUpdateEvent(); event.setSender(this); event.setDataDomainType(dataDomain.getDataDomainType()); event.setSelectionDelta((SelectionDelta) selectionDelta); eventPublisher.triggerEvent(event); setDisplayListDirty(); break; case GATE_TIP_SELECTION: switch (ePickingMode) { case MOUSE_OVER: iDraggedGateNumber = iExternalID; draggedObject = EPickingType.GATE_TIP_SELECTION; setDisplayListDirty(); break; case CLICKED: bIsDraggingActive = true; draggedObject = EPickingType.GATE_TIP_SELECTION; iDraggedGateNumber = iExternalID; break; // case DRAGGED: // bIsDraggingActive = true; // draggedObject = EPickingType.GATE_TIP_SELECTION; // iDraggedGateNumber = iExternalID; // break; } break; case GATE_BOTTOM_SELECTION: switch (ePickingMode) { case MOUSE_OVER: iDraggedGateNumber = iExternalID; draggedObject = EPickingType.GATE_BOTTOM_SELECTION; setDisplayListDirty(); break; case CLICKED: bIsDraggingActive = true; draggedObject = EPickingType.GATE_BOTTOM_SELECTION; iDraggedGateNumber = iExternalID; break; } break; case GATE_BODY_SELECTION: switch (ePickingMode) { case MOUSE_OVER: iDraggedGateNumber = iExternalID; draggedObject = EPickingType.GATE_BODY_SELECTION; setDisplayListDirty(); break; case CLICKED: bIsDraggingActive = true; bIsGateDraggingFirstTime = true; draggedObject = EPickingType.GATE_BODY_SELECTION; iDraggedGateNumber = iExternalID; break; } break; case PC_ICON_SELECTION: switch (ePickingMode) { case CLICKED: break; } break; case REMOVE_AXIS: switch (ePickingMode) { case MOUSE_OVER: dropTexture = EIconTextures.DROP_DELETE; iChangeDropOnAxisNumber = iExternalID; break; case CLICKED: if (storageVA.containsElement(storageVA.get(iExternalID)) == 1) { removeGate(storageVA.get(iExternalID)); } storageVA.remove(iExternalID); storageSelectionManager.remove(iExternalID, false); StorageVADelta vaDelta = new StorageVADelta(StorageVAType.STORAGE, EIDType.EXPERIMENT_INDEX); vaDelta.add(VADeltaItem.remove(iExternalID)); sendStorageVAUpdateEvent(vaDelta); setDisplayListDirty(); resetAxisSpacing(); break; } break; case MOVE_AXIS: switch (ePickingMode) { case CLICKED: bWasAxisMoved = true; bWasAxisDraggedFirstTime = true; iMovedAxisPosition = iExternalID; setDisplayListDirty(); case MOUSE_OVER: dropTexture = EIconTextures.DROP_MOVE; iChangeDropOnAxisNumber = iExternalID; setDisplayListDirty(); break; } break; case DUPLICATE_AXIS: switch (ePickingMode) { case MOUSE_OVER: dropTexture = EIconTextures.DROP_DUPLICATE; iChangeDropOnAxisNumber = iExternalID; break; case CLICKED: if (iExternalID >= 0) { storageVA.copy(iExternalID); StorageVADelta vaDelta = new StorageVADelta(StorageVAType.STORAGE, EIDType.EXPERIMENT_INDEX); vaDelta.add(VADeltaItem.copy(iExternalID)); sendStorageVAUpdateEvent(vaDelta); setDisplayListDirty(); // resetSelections(); // initGates(); resetAxisSpacing(); break; } } break; case ADD_GATE: switch (ePickingMode) { case CLICKED: hasFilterChanged = true; AGate gate; if (set.isSetHomogeneous()) { gate = new Gate(++iGateCounter, iExternalID, (float) set.getRawForNormalized(0), (float) set.getRawForNormalized(0.5f), set, renderStyle); } else { gate = new NominalGate(++iGateCounter, iExternalID, 0, 0.5f, set, renderStyle); } hashGates.put(this.iGateCounter, gate); hashIsGateBlocking.put(this.iGateCounter, new ArrayList<Integer>()); handleUnselection(); triggerSelectionUpdate(); setDisplayListDirty(); break; } break; case ADD_MASTER_GATE: switch (ePickingMode) { case CLICKED: hasFilterChanged = true; Gate gate = new Gate(++iGateCounter, -1, (float) set.getRawForNormalized(0), (float) set.getRawForNormalized(0.5f), set, renderStyle); gate.setMasterGate(true); hashMasterGates.put(iGateCounter, gate); hashIsGateBlocking.put(iGateCounter, new ArrayList<Integer>()); handleUnselection(); triggerSelectionUpdate(); setDisplayListDirty(); break; } break; case REMOVE_GATE: switch (ePickingMode) { case CLICKED: hasFilterChanged = true; // either the gate belongs to the normal or to the master gates if (hashGates.remove(iExternalID) == null) hashMasterGates.remove(iExternalID); hashIsGateBlocking.remove(iExternalID); handleUnselection(); triggerSelectionUpdate(); setDisplayListDirty(); break; } break; case ANGULAR_UPPER: switch (ePickingMode) { case CLICKED: bIsAngularDraggingActive = true; case DRAGGED: bIsAngularDraggingActive = true; } break; case ANGULAR_LOWER: switch (ePickingMode) { case CLICKED: bIsAngularDraggingActive = true; case DRAGGED: bIsAngularDraggingActive = true; } break; case REMOVE_NAN: switch (ePickingMode) { case CLICKED: hasFilterChanged = true; if (hashExcludeNAN.containsKey(iExternalID)) { hashExcludeNAN.remove(iExternalID); } else { hashExcludeNAN.put(iExternalID, null); } setDisplayListDirty(); break; } break; } } private void sendContentVAUpdateEvent(ContentVADelta delta) { ContentVAUpdateEvent virtualArrayUpdateEvent = new ContentVAUpdateEvent(); virtualArrayUpdateEvent.setSender(this); virtualArrayUpdateEvent.setDataDomainType(dataDomain.getDataDomainType()); virtualArrayUpdateEvent.setVirtualArrayDelta(delta); virtualArrayUpdateEvent.setInfo(getShortInfoLocal()); eventPublisher.triggerEvent(virtualArrayUpdateEvent); } private void sendStorageVAUpdateEvent(StorageVADelta delta) { StorageVAUpdateEvent virtualArrayUpdateEvent = new StorageVAUpdateEvent(); virtualArrayUpdateEvent.setSender(this); virtualArrayUpdateEvent.setDataDomainType(dataDomain.getDataDomainType()); virtualArrayUpdateEvent.setVirtualArrayDelta(delta); virtualArrayUpdateEvent.setInfo(getShortInfoLocal()); eventPublisher.triggerEvent(virtualArrayUpdateEvent); } @Override protected ArrayList<SelectedElementRep> createElementRep(EIDType idType, int iStorageIndex) throws InvalidAttributeValueException { ArrayList<SelectedElementRep> alElementReps = new ArrayList<SelectedElementRep>(); float x = 0; float y = 0; if (idType == EIDType.EXPERIMENT_INDEX && dataDomain.getDataDomainType() .equals("org.caleydo.datadomain.genetic")) { int axisCount = storageVA.indexOf(iStorageIndex); // for (int iAxisID : storageVA) { x = axisCount * renderStyle.getAxisSpacing(storageVA.size()); axisCount++; x = x + renderStyle.getXSpacing(); y = renderStyle.getBottomSpacing(); // y =set.get(storageVA.get(storageVA.size() - 1)).getFloat( // EDataRepresentation.NORMALIZED, iAxisID); alElementReps.add(new SelectedElementRep(idType, iUniqueID, x, y, 0.0f)); // } // } // else if (idType == EIDType.EXPERIMENT_INDEX // && dataDomain.getDataDomainType().equals( // "org.caleydo.datadomain.clinical")) { // System.out.println("wu"); // alElementReps.add(new SelectedElementRep(idType, iUniqueID, 0, 0, 0.0f)); } else { // if (eAxisDataType == EIDType.EXPERIMENT_RECORD) // fXValue = viewFrustum.getRight() - 0.2f; // else // fXValue = viewFrustum.getRight() - 0.4f; if (renderConnectionsLeft) { x = x + renderStyle.getXSpacing(); y = set.get(storageVA.get(0)).getFloat(EDataRepresentation.NORMALIZED, iStorageIndex); } else { // if (eAxisDataType == EIDType.EXPERIMENT_RECORD) // fXValue = viewFrustum.getRight() - 0.2f; // else x = viewFrustum.getRight() - 0.4f; y = set.get(storageVA.get(storageVA.size() - 1)).getFloat( EDataRepresentation.NORMALIZED, iStorageIndex); } // // get the value on the leftmost axis // fYValue = // set.get(storageVA.get(0)).getFloat(EDataRepresentation.NORMALIZED, // iStorageIndex); if (Float.isNaN(y)) { y = NAN_Y_OFFSET * renderStyle.getAxisHeight() + renderStyle.getBottomSpacing(); } else { y = y * renderStyle.getAxisHeight() + renderStyle.getBottomSpacing(); } alElementReps.add(new SelectedElementRep(idType, iUniqueID, x, y, 0.0f)); } return alElementReps; } @Override public String getShortInfo() { String message; int iNumLines = contentVA.size(); if (displayEveryNthPolyline == 1) { message = "Parallel Coordinates - " + iNumLines + " " + dataDomain.getContentLabel(false, true) + " / " + storageVA.size() + " experiments"; } else { message = "Parallel Coordinates - a sample of " + iNumLines / displayEveryNthPolyline + " out of " + iNumLines + " " + dataDomain.getContentLabel(false, true) + " / \n " + storageVA.size() + " experiments"; } return message; } @Override public String getDetailedInfo() { StringBuffer sInfoText = new StringBuffer(); sInfoText.append("<b>Type:</b> Parallel Coordinates\n"); sInfoText.append(contentVA.size() + dataDomain.getContentLabel(false, true) + " as polylines and " + storageVA.size() + " experiments as axis.\n"); if (bRenderOnlyContext) { sInfoText .append("Showing only genes which occur in one of the other views in focus\n"); } else { if (bUseRandomSampling) { sInfoText.append("Random sampling active, sample size: " + iNumberOfRandomElements + "\n"); } else { sInfoText.append("Random sampling inactive\n"); } if (dataFilterLevel == EDataFilterLevel.COMPLETE) { sInfoText.append("Showing all " + dataDomain.getContentLabel(false, true) + " in the dataset\n"); } else if (dataFilterLevel == EDataFilterLevel.ONLY_MAPPING) { sInfoText.append("Showing all " + dataDomain.getContentLabel(false, true) + " that have a known DAVID ID mapping\n"); } else if (dataFilterLevel == EDataFilterLevel.ONLY_CONTEXT) { sInfoText .append("Showing all genes that are contained in any of the KEGG or Biocarta Pathways\n"); } } return sInfoText.toString(); } /** * Re-position a view centered on a element, specified by the element ID * * @param iElementID * the ID of the element that should be in the center */ // TODO private void doTranslation() { float fDelta = 0; if (fXTargetTranslation < fXTranslation - 0.3) { fDelta = -0.3f; } else if (fXTargetTranslation > fXTranslation + 0.3) { fDelta = 0.3f; } else { fDelta = fXTargetTranslation - fXTranslation; bIsTranslationActive = false; } if (elementRep != null) { ArrayList<Vec3f> alPoints = elementRep.getPoints(); for (Vec3f currentPoint : alPoints) { currentPoint.setX(currentPoint.x() + fDelta); } } fXTranslation += fDelta; } // TODO private void handleAngularBrushing(final GL gl) { hasFilterChanged = true; if (bIsAngularBrushingFirstTime) { fCurrentAngle = fDefaultAngle; Point currentPoint = linePick.getPickedPoint(); float[] fArPoint = GLCoordinateUtils .convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x, currentPoint.y); vecAngularBrushingPoint = new Vec3f(fArPoint[0], fArPoint[1], 0.01f); bIsAngularBrushingFirstTime = false; } alIsAngleBlocking.get(0).clear(); int iPosition = 0; for (int iCount = 0; iCount < alAxisSpacing.size() - 1; iCount++) { if (vecAngularBrushingPoint.x() > alAxisSpacing.get(iCount) && vecAngularBrushingPoint.x() < alAxisSpacing.get(iCount + 1)) { iPosition = iCount; } } int iAxisLeftIndex; int iAxisRightIndex; iAxisLeftIndex = storageVA.get(iPosition); iAxisRightIndex = storageVA.get(iPosition + 1); Vec3f vecLeftPoint = new Vec3f(0, 0, 0); Vec3f vecRightPoint = new Vec3f(0, 0, 0); vecLeftPoint.setY(set.get(iAxisLeftIndex).getFloat( EDataRepresentation.NORMALIZED, iSelectedLineID) * renderStyle.getAxisHeight()); vecRightPoint.setY(set.get(iAxisRightIndex).getFloat( EDataRepresentation.NORMALIZED, iSelectedLineID) * renderStyle.getAxisHeight()); vecLeftPoint.setX(alAxisSpacing.get(iPosition)); vecRightPoint.setX(alAxisSpacing.get(iPosition + 1)); Vec3f vecDirectional = vecRightPoint.minus(vecLeftPoint); float fLength = vecDirectional.length(); vecDirectional.normalize(); Vec3f vecTriangleOrigin = vecLeftPoint.addScaled(fLength / 4, vecDirectional); Vec3f vecTriangleLimit = vecLeftPoint.addScaled(fLength / 4 * 3, vecDirectional); Rotf rotf = new Rotf(); Vec3f vecCenterLine = vecTriangleLimit.minus(vecTriangleOrigin); float fLegLength = vecCenterLine.length(); if (bIsAngularDraggingActive) { Point pickedPoint = glMouseListener.getPickedPoint(); float fArPoint[] = GLCoordinateUtils .convertWindowCoordinatesToWorldCoordinates(gl, pickedPoint.x, pickedPoint.y); Vec3f vecPickedPoint = new Vec3f(fArPoint[0], fArPoint[1], 0.01f); Vec3f vecTempLine = vecPickedPoint.minus(vecTriangleOrigin); fCurrentAngle = getAngle(vecTempLine, vecCenterLine); bIsDisplayListDirtyLocal = true; bIsDisplayListDirtyRemote = true; } rotf.set(new Vec3f(0, 0, 1), fCurrentAngle); Vec3f vecUpperPoint = rotf.rotateVector(vecCenterLine); rotf.set(new Vec3f(0, 0, 1), -fCurrentAngle); Vec3f vecLowerPoint = rotf.rotateVector(vecCenterLine); vecUpperPoint.add(vecTriangleOrigin); vecLowerPoint.add(vecTriangleOrigin); gl.glColor4fv(ANGULAR_COLOR, 0); gl.glLineWidth(ANGLUAR_LINE_WIDTH); gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.ANGULAR_UPPER, iPosition)); gl.glBegin(GL.GL_LINES); gl.glVertex3f(vecTriangleOrigin.x(), vecTriangleOrigin.y(), vecTriangleOrigin.z() + 0.02f); gl.glVertex3f(vecUpperPoint.x(), vecUpperPoint.y(), vecUpperPoint.z() + 0.02f); gl.glEnd(); gl.glPopName(); gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.ANGULAR_UPPER, iPosition)); gl.glBegin(GL.GL_LINES); gl.glVertex3f(vecTriangleOrigin.x(), vecTriangleOrigin.y(), vecTriangleOrigin.z() + 0.02f); gl.glVertex3f(vecLowerPoint.x(), vecLowerPoint.y(), vecLowerPoint.z() + 0.02f); gl.glEnd(); gl.glPopName(); // draw angle polygon gl.glColor4fv(ANGULAR_POLYGON_COLOR, 0); // gl.glColor4f(1, 0, 0, 0.5f); gl.glBegin(GL.GL_POLYGON); rotf.set(new Vec3f(0, 0, 1), -fCurrentAngle / 10); Vec3f tempVector = vecCenterLine.copy(); gl.glVertex3f(vecTriangleOrigin.x(), vecTriangleOrigin.y(), vecTriangleOrigin.z() + 0.02f); for (int iCount = 0; iCount <= 10; iCount++) { Vec3f vecPoint = tempVector.copy(); vecPoint.normalize(); vecPoint.scale(fLegLength); gl.glVertex3f(vecTriangleOrigin.x() + vecPoint.x(), vecTriangleOrigin.y() + vecPoint.y(), vecTriangleOrigin.z() + vecPoint.z() + 0.02f); tempVector = rotf.rotateVector(tempVector); } gl.glEnd(); gl.glBegin(GL.GL_POLYGON); rotf.set(new Vec3f(0, 0, 1), fCurrentAngle / 10); tempVector = vecCenterLine.copy(); gl.glVertex3f(vecTriangleOrigin.x(), vecTriangleOrigin.y(), vecTriangleOrigin.z() + 0.02f); for (int iCount = 0; iCount <= 10; iCount++) { Vec3f vecPoint = tempVector.copy(); vecPoint.normalize(); vecPoint.scale(fLegLength); gl.glVertex3f(vecTriangleOrigin.x() + vecPoint.x(), vecTriangleOrigin.y() + vecPoint.y(), vecTriangleOrigin.z() + vecPoint.z() + 0.02f); tempVector = rotf.rotateVector(tempVector); } // gl.glVertex3f(vecUpperPoint.x(), vecUpperPoint.y(), vecUpperPoint.z() // + 0.02f); gl.glEnd(); // check selection for (Integer iCurrent : contentVA) { vecLeftPoint.setY(set.get(iAxisLeftIndex).getFloat( EDataRepresentation.NORMALIZED, iCurrent) * renderStyle.getAxisHeight()); vecRightPoint.setY(set.get(iAxisRightIndex).getFloat( EDataRepresentation.NORMALIZED, iCurrent) * renderStyle.getAxisHeight()); vecLeftPoint.setX(alAxisSpacing.get(iPosition)); vecRightPoint.setX(alAxisSpacing.get(iPosition + 1)); // Vec3f vecCompareLine = vecLeftPoint.minus(vecRightPoint); Vec3f vecCompareLine = vecRightPoint.minus(vecLeftPoint); float fCompareAngle = getAngle(vecCompareLine, vecCenterLine); if (fCompareAngle > fCurrentAngle || fCompareAngle < -fCurrentAngle) // !(fCompareAngle < fAngle && fCompareAngle < -fAngle)) { // contentSelectionManager.addToType(EViewInternalSelectionType // .DESELECTED, iCurrent); alIsAngleBlocking.get(0).add(iCurrent); } // else // { // // TODO combinations // //contentSelectionManager.addToType(EViewInternalSelectionType. // NORMAL, iCurrent); // } } if (glMouseListener.wasMouseReleased()) { bIsAngularDraggingActive = false; // bIsAngularBrushingActive = false; } } private float getAngle(final Vec3f vecOne, final Vec3f vecTwo) { Vec3f vecNewOne = vecOne.copy(); Vec3f vecNewTwo = vecTwo.copy(); vecNewOne.normalize(); vecNewTwo.normalize(); float fTmp = vecNewOne.dot(vecNewTwo); return (float) Math.acos(fTmp); } private void adjustAxisSpacing(GL gl) { Point currentPoint = glMouseListener.getPickedPoint(); float[] fArTargetWorldCoordinates = GLCoordinateUtils .convertWindowCoordinatesToWorldCoordinates(gl, currentPoint.x, currentPoint.y); float fWidth = fArTargetWorldCoordinates[0] - fXTranslation - fXDefaultTranslation; if (bWasAxisDraggedFirstTime) { // adjust from the actually clicked point to the center of the axis fAxisDraggingOffset = fWidth - alAxisSpacing.get(iMovedAxisPosition); bWasAxisDraggedFirstTime = false; } fWidth -= fAxisDraggingOffset; if (fWidth < renderStyle.getXAxisStart()) { fWidth = renderStyle.getXAxisStart(); } if (fWidth > renderStyle.getXAxisEnd()) { fWidth = renderStyle.getXAxisEnd(); } int iSwitchAxisWithThis = -1; for (int iCount = 0; iCount < alAxisSpacing.size(); iCount++) { if (iMovedAxisPosition > iCount && fWidth < alAxisSpacing.get(iCount)) { iSwitchAxisWithThis = iCount; break; } if (iMovedAxisPosition < iCount && fWidth > alAxisSpacing.get(iCount)) { iSwitchAxisWithThis = iCount; } } if (iSwitchAxisWithThis != -1) { storageVA.move(iMovedAxisPosition, iSwitchAxisWithThis); alAxisSpacing.remove(iMovedAxisPosition); alAxisSpacing.add(iSwitchAxisWithThis, fWidth); StorageVADelta vaDelta = new StorageVADelta(storageVAType, EIDType.EXPERIMENT_INDEX); vaDelta.add(VADeltaItem.move(iMovedAxisPosition, iSwitchAxisWithThis)); sendStorageVAUpdateEvent(vaDelta); iMovedAxisPosition = iSwitchAxisWithThis; } else { alAxisSpacing.set(iMovedAxisPosition, fWidth); } setDisplayListDirty(); } private void handleTrackInput(final GL gl) { // TODO: very performance intensive - better solution needed (only in // reshape)! getParentGLCanvas().getParentComposite().getDisplay().asyncExec(new Runnable() { @Override public void run() { upperLeftScreenPos = getParentGLCanvas().getParentComposite().toDisplay( 1, 1); } }); Rectangle screenRect = getParentGLCanvas().getBounds(); float[] fArTrackPos = generalManager.getTrackDataProvider().getEyeTrackData(); fArTrackPos[0] -= upperLeftScreenPos.x; fArTrackPos[1] -= upperLeftScreenPos.y; // GLHelperFunctions.drawPointAt(gl, new Vec3f(fArTrackPos[0] / // screenRect.width * 8f, // (1f - fArTrackPos[1] / screenRect.height) * 8f * fAspectRatio, // 0.01f)); float fTrackX = (generalManager.getTrackDataProvider().getEyeTrackData()[0]) / screenRect.width; fTrackX *= renderStyle.getWidthOfCoordinateSystem(); int iAxisNumber = 0; for (int iCount = 0; iCount < alAxisSpacing.size() - 1; iCount++) { if (alAxisSpacing.get(iCount) < fTrackX && alAxisSpacing.get(iCount + 1) > fTrackX) { if (fTrackX - alAxisSpacing.get(iCount) < alAxisSpacing.get(iCount) - fTrackX) { iAxisNumber = iCount; } else { iAxisNumber = iCount + 1; } break; } } int iNumberOfAxis = storageVA.size(); float fOriginalAxisSpacing = renderStyle.getAxisSpacing(iNumberOfAxis); float fFocusAxisSpacing = fOriginalAxisSpacing * 2; float fReducedSpacing = (renderStyle.getWidthOfCoordinateSystem() - 2 * fFocusAxisSpacing) / (iNumberOfAxis - 3); float fCurrentX = 0; alAxisSpacing.clear(); for (int iCount = 0; iCount < iNumberOfAxis; iCount++) { alAxisSpacing.add(fCurrentX); if (iCount + 1 == iAxisNumber || iCount == iAxisNumber) { fCurrentX += fFocusAxisSpacing; } else { fCurrentX += fReducedSpacing; } } setDisplayListDirty(); } // private void focusOnAreaWii() { // if (!generalManager.isWiiModeActive()) // return; // // WiiRemote wii = generalManager.getWiiRemote(); // // float fXWiiPosition = wii.getCurrentSmoothHeadPosition()[0] + 1f; // // // we assume that this is far right, and -fMax is far left // float fMaxX = 2; // // if (fXWiiPosition > fMaxX) { // fXWiiPosition = fMaxX; // } // else if (fXWiiPosition < -fMaxX) { // fXWiiPosition = -fMaxX; // } // // // now we normalize to 0 to 1 // fXWiiPosition = (fXWiiPosition + fMaxX) / (2 * fMaxX); // // fXWiiPosition *= renderStyle.getWidthOfCoordinateSystem(); // int iAxisNumber = 0; // for (int iCount = 0; iCount < alAxisSpacing.size() - 1; iCount++) { // if (alAxisSpacing.get(iCount) < fXWiiPosition && alAxisSpacing.get(iCount // + 1) > fXWiiPosition) { // if (fXWiiPosition - alAxisSpacing.get(iCount) < alAxisSpacing.get(iCount) // - fXWiiPosition) { // iAxisNumber = iCount; // } // else { // iAxisNumber = iCount + 1; // } // // break; // } // } // // int iNumberOfAxis = axisVA.size(); // // float fOriginalAxisSpacing = renderStyle.getAxisSpacing(iNumberOfAxis); // // float fFocusAxisSpacing = 2 * fOriginalAxisSpacing; // // float fReducedSpacing = // (renderStyle.getWidthOfCoordinateSystem() - 2 * fFocusAxisSpacing) / // (iNumberOfAxis - 3); // // float fCurrentX = 0; // alAxisSpacing.clear(); // for (int iCount = 0; iCount < iNumberOfAxis; iCount++) { // alAxisSpacing.add(fCurrentX); // if (iCount + 1 == iAxisNumber || iCount == iAxisNumber) { // fCurrentX += fFocusAxisSpacing; // } // else { // fCurrentX += fReducedSpacing; // } // } // // setDisplayListDirty(); // } public void resetAxisSpacing() { alAxisSpacing.clear(); int iNumAxis = storageVA.size(); float fInitAxisSpacing = renderStyle.getAxisSpacing(iNumAxis); for (int iCount = 0; iCount < iNumAxis; iCount++) { alAxisSpacing.add(fInitAxisSpacing * iCount); } setDisplayListDirty(); } @Override public ASerializedView getSerializableRepresentation() { SerializedParallelCoordinatesView serializedForm = new SerializedParallelCoordinatesView( dataDomain.getDataDomainType()); serializedForm.setViewID(this.getID()); return serializedForm; } @Override public void handleUpdateView() { setDisplayListDirty(); } @Override public void destroy() { selectionTransformer.destroy(); super.destroy(); } @Override public void registerEventListeners() { super.registerEventListeners(); applyCurrentSelectionToVirtualArrayListener = new ApplyCurrentSelectionToVirtualArrayListener(); applyCurrentSelectionToVirtualArrayListener.setHandler(this); eventPublisher.addListener(ApplyCurrentSelectionToVirtualArrayEvent.class, applyCurrentSelectionToVirtualArrayListener); resetAxisSpacingListener = new ResetAxisSpacingListener(); resetAxisSpacingListener.setHandler(this); eventPublisher.addListener(ResetAxisSpacingEvent.class, resetAxisSpacingListener); bookmarkListener = new BookmarkButtonListener(); bookmarkListener.setHandler(this); eventPublisher.addListener(BookmarkButtonEvent.class, bookmarkListener); resetViewListener = new ResetViewListener(); resetViewListener.setHandler(this); eventPublisher.addListener(ResetAllViewsEvent.class, resetViewListener); // second event for same listener eventPublisher .addListener(ResetParallelCoordinatesEvent.class, resetViewListener); useRandomSamplingListener = new UseRandomSamplingListener(); useRandomSamplingListener.setHandler(this); eventPublisher.addListener(UseRandomSamplingEvent.class, useRandomSamplingListener); angularBrushingListener = new AngularBrushingListener(); angularBrushingListener.setHandler(this); eventPublisher.addListener(AngularBrushingEvent.class, angularBrushingListener); } @Override public void unregisterEventListeners() { super.unregisterEventListeners(); if (applyCurrentSelectionToVirtualArrayListener != null) { eventPublisher.removeListener(applyCurrentSelectionToVirtualArrayListener); applyCurrentSelectionToVirtualArrayListener = null; } if (resetAxisSpacingListener != null) { eventPublisher.removeListener(resetAxisSpacingListener); resetAxisSpacingListener = null; } if (bookmarkListener != null) { eventPublisher.removeListener(bookmarkListener); bookmarkListener = null; } if (resetViewListener != null) { eventPublisher.removeListener(resetViewListener); resetViewListener = null; } if (angularBrushingListener != null) { eventPublisher.removeListener(angularBrushingListener); angularBrushingListener = null; } } @Override public void handleSelectionCommand(EIDCategory category, SelectionCommand selectionCommand) { if (category == contentSelectionManager.getIDType().getCategory()) contentSelectionManager.executeSelectionCommand(selectionCommand); else if (category == storageSelectionManager.getIDType().getCategory()) storageSelectionManager.executeSelectionCommand(selectionCommand); else return; setDisplayListDirty(); } @Override public String toString() { int iNumElements = (contentSelectionManager.getNumberOfElements() - contentSelectionManager .getNumberOfElements(SelectionType.DESELECTED)); String renderMode = "standalone"; if (isRenderedRemote()) renderMode = "remote"; return ("PCs, " + renderMode + ", " + iNumElements + " elements" + " Axis DT: " + storageSelectionManager.getIDType() + " Polyline DT:" + contentSelectionManager .getIDType()); } @Override public List<AGLView> getRemoteRenderedViews() { return new ArrayList<AGLView>(); } public void setRenderConnectionState(boolean renderConnectionssLeft) { this.renderConnectionsLeft = renderConnectionssLeft; } public ISet getSet() { return set; } }
Improved linking destinations git-svn-id: 149221363d454b9399d51e0b24a857a738336ca8@3454 1f7349ae-fd9f-0d40-aeb8-9798e6c0fce3
org.caleydo.view.parcoords/src/org/caleydo/view/parcoords/GLParallelCoordinates.java
Improved linking destinations
<ide><path>rg.caleydo.view.parcoords/src/org/caleydo/view/parcoords/GLParallelCoordinates.java <ide> <ide> @Override <ide> public void display(final GL gl) { <del> <add> <ide> gl.glEnable(GL.GL_BLEND); <del> <add> <ide> if (bShowSelectionHeatMap) { <ide> <ide> gl.glTranslatef(viewFrustum.getRight() <ide> .equals("org.caleydo.datadomain.genetic")) { <ide> <ide> int axisCount = storageVA.indexOf(iStorageIndex); <del>// for (int iAxisID : storageVA) { <del> x = axisCount * renderStyle.getAxisSpacing(storageVA.size()); <del> axisCount++; <del> x = x + renderStyle.getXSpacing(); <del> y = renderStyle.getBottomSpacing(); <del> // y =set.get(storageVA.get(storageVA.size() - 1)).getFloat( <del> // EDataRepresentation.NORMALIZED, iAxisID); <del> alElementReps.add(new SelectedElementRep(idType, iUniqueID, x, y, 0.0f)); <del>// } <del>// } <del>// else if (idType == EIDType.EXPERIMENT_INDEX <del>// && dataDomain.getDataDomainType().equals( <del>// "org.caleydo.datadomain.clinical")) { <del>// System.out.println("wu"); <del>// alElementReps.add(new SelectedElementRep(idType, iUniqueID, 0, 0, 0.0f)); <add> // for (int iAxisID : storageVA) { <add> x = axisCount * renderStyle.getAxisSpacing(storageVA.size()); <add> axisCount++; <add> x = x + renderStyle.getXSpacing(); <add> y = renderStyle.getBottomSpacing(); <add> // y =set.get(storageVA.get(storageVA.size() - 1)).getFloat( <add> // EDataRepresentation.NORMALIZED, iAxisID); <add> alElementReps.add(new SelectedElementRep(idType, iUniqueID, x, y, 0.0f)); <add> // } <add> // } <add> // else if (idType == EIDType.EXPERIMENT_INDEX <add> // && dataDomain.getDataDomainType().equals( <add> // "org.caleydo.datadomain.clinical")) { <add> // System.out.println("wu"); <add> // alElementReps.add(new SelectedElementRep(idType, iUniqueID, 0, 0, <add> // 0.0f)); <ide> <ide> } else { <ide> // if (eAxisDataType == EIDType.EXPERIMENT_RECORD) <ide> // else <ide> // fXValue = viewFrustum.getRight() - 0.4f; <ide> <del> if (renderConnectionsLeft) { <del> x = x + renderStyle.getXSpacing(); <del> y = set.get(storageVA.get(0)).getFloat(EDataRepresentation.NORMALIZED, <del> iStorageIndex); <del> } else { <del> // if (eAxisDataType == EIDType.EXPERIMENT_RECORD) <del> // fXValue = viewFrustum.getRight() - 0.2f; <del> // else <del> x = viewFrustum.getRight() - 0.4f; <del> y = set.get(storageVA.get(storageVA.size() - 1)).getFloat( <del> EDataRepresentation.NORMALIZED, iStorageIndex); <del> } <add> // if (renderConnectionsLeft) { <add> // x = x + renderStyle.getXSpacing(); <add> // y = <add> // set.get(storageVA.get(0)).getFloat(EDataRepresentation.NORMALIZED, <add> // iStorageIndex); <add> // } else { <add> // if (eAxisDataType == EIDType.EXPERIMENT_RECORD) <add> // fXValue = viewFrustum.getRight() - 0.2f; <add> // else <add> x = viewFrustum.getLeft() + renderStyle.getXSpacing(); <add> y = set.get(storageVA.get(0)).getFloat( <add> EDataRepresentation.NORMALIZED, iStorageIndex); <add> // } <ide> <ide> // // get the value on the leftmost axis <ide> // fYValue =
Java
apache-2.0
0e34dcbf4b98140cf00945aa5e235f9c2dca6959
0
apurtell/hbase,ChinmaySKulkarni/hbase,mahak/hbase,ChinmaySKulkarni/hbase,ndimiduk/hbase,mahak/hbase,mahak/hbase,apurtell/hbase,ndimiduk/hbase,ndimiduk/hbase,mahak/hbase,francisliu/hbase,ChinmaySKulkarni/hbase,apurtell/hbase,mahak/hbase,Apache9/hbase,francisliu/hbase,francisliu/hbase,ndimiduk/hbase,ChinmaySKulkarni/hbase,ndimiduk/hbase,Apache9/hbase,ChinmaySKulkarni/hbase,apurtell/hbase,ChinmaySKulkarni/hbase,Apache9/hbase,mahak/hbase,ndimiduk/hbase,ndimiduk/hbase,apurtell/hbase,ndimiduk/hbase,francisliu/hbase,ndimiduk/hbase,apurtell/hbase,francisliu/hbase,ChinmaySKulkarni/hbase,ChinmaySKulkarni/hbase,apurtell/hbase,Apache9/hbase,Apache9/hbase,Apache9/hbase,ndimiduk/hbase,Apache9/hbase,apurtell/hbase,mahak/hbase,francisliu/hbase,francisliu/hbase,Apache9/hbase,mahak/hbase,Apache9/hbase,francisliu/hbase,Apache9/hbase,apurtell/hbase,mahak/hbase,ChinmaySKulkarni/hbase,mahak/hbase,francisliu/hbase,ChinmaySKulkarni/hbase,francisliu/hbase,apurtell/hbase
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.io.hfile; import static org.apache.hadoop.hbase.HConstants.BUCKET_CACHE_IOENGINE_KEY; import static org.apache.hadoop.hbase.HConstants.BUCKET_CACHE_SIZE_KEY; import java.io.IOException; import java.util.concurrent.ForkJoinPool; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.io.hfile.bucket.BucketCache; import org.apache.hadoop.hbase.io.util.MemorySizeUtil; import org.apache.hadoop.hbase.util.ReflectionUtils; import org.apache.hadoop.util.StringUtils; import org.apache.yetus.audience.InterfaceAudience; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @InterfaceAudience.Private public final class BlockCacheFactory { private static final Logger LOG = LoggerFactory.getLogger(BlockCacheFactory.class.getName()); /** * Configuration keys for Bucket cache */ /** * Configuration key to cache block policy (Lru, TinyLfu). */ public static final String BLOCKCACHE_POLICY_KEY = "hfile.block.cache.policy"; public static final String BLOCKCACHE_POLICY_DEFAULT = "LRU"; /** * If the chosen ioengine can persist its state across restarts, the path to the file to persist * to. This file is NOT the data file. It is a file into which we will serialize the map of * what is in the data file. For example, if you pass the following argument as * BUCKET_CACHE_IOENGINE_KEY ("hbase.bucketcache.ioengine"), * <code>file:/tmp/bucketcache.data </code>, then we will write the bucketcache data to the file * <code>/tmp/bucketcache.data</code> but the metadata on where the data is in the supplied file * is an in-memory map that needs to be persisted across restarts. Where to store this * in-memory state is what you supply here: e.g. <code>/tmp/bucketcache.map</code>. */ public static final String BUCKET_CACHE_PERSISTENT_PATH_KEY = "hbase.bucketcache.persistent.path"; public static final String BUCKET_CACHE_WRITER_THREADS_KEY = "hbase.bucketcache.writer.threads"; public static final String BUCKET_CACHE_WRITER_QUEUE_KEY = "hbase.bucketcache.writer.queuelength"; /** * A comma-delimited array of values for use as bucket sizes. */ public static final String BUCKET_CACHE_BUCKETS_KEY = "hbase.bucketcache.bucket.sizes"; /** * Defaults for Bucket cache */ public static final int DEFAULT_BUCKET_CACHE_WRITER_THREADS = 3; public static final int DEFAULT_BUCKET_CACHE_WRITER_QUEUE = 64; /** * The target block size used by blockcache instances. Defaults to * {@link HConstants#DEFAULT_BLOCKSIZE}. * TODO: this config point is completely wrong, as it's used to determine the * target block size of BlockCache instances. Rename. */ public static final String BLOCKCACHE_BLOCKSIZE_KEY = "hbase.offheapcache.minblocksize"; private static final String EXTERNAL_BLOCKCACHE_KEY = "hbase.blockcache.use.external"; private static final boolean EXTERNAL_BLOCKCACHE_DEFAULT = false; private static final String EXTERNAL_BLOCKCACHE_CLASS_KEY = "hbase.blockcache.external.class"; private BlockCacheFactory() { } public static BlockCache createBlockCache(Configuration conf) { FirstLevelBlockCache l1Cache = createFirstLevelCache(conf); if (l1Cache == null) { return null; } boolean useExternal = conf.getBoolean(EXTERNAL_BLOCKCACHE_KEY, EXTERNAL_BLOCKCACHE_DEFAULT); if (useExternal) { BlockCache l2CacheInstance = createExternalBlockcache(conf); return l2CacheInstance == null ? l1Cache : new InclusiveCombinedBlockCache(l1Cache, l2CacheInstance); } else { // otherwise use the bucket cache. BucketCache bucketCache = createBucketCache(conf); if (!conf.getBoolean("hbase.bucketcache.combinedcache.enabled", true)) { // Non combined mode is off from 2.0 LOG.warn( "From HBase 2.0 onwards only combined mode of LRU cache and bucket cache is available"); } return bucketCache == null ? l1Cache : new CombinedBlockCache(l1Cache, bucketCache); } } private static FirstLevelBlockCache createFirstLevelCache(final Configuration c) { final long cacheSize = MemorySizeUtil.getOnHeapCacheSize(c); if (cacheSize < 0) { return null; } String policy = c.get(BLOCKCACHE_POLICY_KEY, BLOCKCACHE_POLICY_DEFAULT); int blockSize = c.getInt(BLOCKCACHE_BLOCKSIZE_KEY, HConstants.DEFAULT_BLOCKSIZE); LOG.info("Allocating BlockCache size=" + StringUtils.byteDesc(cacheSize) + ", blockSize=" + StringUtils.byteDesc(blockSize)); if (policy.equalsIgnoreCase("LRU")) { return new LruBlockCache(cacheSize, blockSize, true, c); } else if (policy.equalsIgnoreCase("TinyLFU")) { return new TinyLfuBlockCache(cacheSize, blockSize, ForkJoinPool.commonPool(), c); } else { throw new IllegalArgumentException("Unknown policy: " + policy); } } /** * Enum of all built in external block caches. * This is used for config. */ private static enum ExternalBlockCaches { memcached("org.apache.hadoop.hbase.io.hfile.MemcachedBlockCache"); // TODO(eclark): Consider more. Redis, etc. Class<? extends BlockCache> clazz; ExternalBlockCaches(String clazzName) { try { clazz = (Class<? extends BlockCache>) Class.forName(clazzName); } catch (ClassNotFoundException cnef) { clazz = null; } } ExternalBlockCaches(Class<? extends BlockCache> clazz) { this.clazz = clazz; } } private static BlockCache createExternalBlockcache(Configuration c) { if (LOG.isDebugEnabled()) { LOG.debug("Trying to use External l2 cache"); } Class klass = null; // Get the class, from the config. s try { klass = ExternalBlockCaches .valueOf(c.get(EXTERNAL_BLOCKCACHE_CLASS_KEY, "memcache")).clazz; } catch (IllegalArgumentException exception) { try { klass = c.getClass(EXTERNAL_BLOCKCACHE_CLASS_KEY, Class.forName( "org.apache.hadoop.hbase.io.hfile.MemcachedBlockCache")); } catch (ClassNotFoundException e) { return null; } } // Now try and create an instance of the block cache. try { LOG.info("Creating external block cache of type: " + klass); return (BlockCache) ReflectionUtils.newInstance(klass, c); } catch (Exception e) { LOG.warn("Error creating external block cache", e); } return null; } private static BucketCache createBucketCache(Configuration c) { // Check for L2. ioengine name must be non-null. String bucketCacheIOEngineName = c.get(BUCKET_CACHE_IOENGINE_KEY, null); if (bucketCacheIOEngineName == null || bucketCacheIOEngineName.length() <= 0) { return null; } int blockSize = c.getInt(BLOCKCACHE_BLOCKSIZE_KEY, HConstants.DEFAULT_BLOCKSIZE); final long bucketCacheSize = MemorySizeUtil.getBucketCacheSize(c); if (bucketCacheSize <= 0) { throw new IllegalStateException("bucketCacheSize <= 0; Check " + BUCKET_CACHE_SIZE_KEY + " setting and/or server java heap size"); } if (c.get("hbase.bucketcache.percentage.in.combinedcache") != null) { LOG.warn("Configuration 'hbase.bucketcache.percentage.in.combinedcache' is no longer " + "respected. See comments in http://hbase.apache.org/book.html#_changes_of_note"); } int writerThreads = c.getInt(BUCKET_CACHE_WRITER_THREADS_KEY, DEFAULT_BUCKET_CACHE_WRITER_THREADS); int writerQueueLen = c.getInt(BUCKET_CACHE_WRITER_QUEUE_KEY, DEFAULT_BUCKET_CACHE_WRITER_QUEUE); String persistentPath = c.get(BUCKET_CACHE_PERSISTENT_PATH_KEY); String[] configuredBucketSizes = c.getStrings(BUCKET_CACHE_BUCKETS_KEY); int [] bucketSizes = null; if (configuredBucketSizes != null) { bucketSizes = new int[configuredBucketSizes.length]; for (int i = 0; i < configuredBucketSizes.length; i++) { int bucketSize = Integer.parseInt(configuredBucketSizes[i].trim()); if (bucketSize % 256 != 0) { // We need all the bucket sizes to be multiples of 256. Having all the configured bucket // sizes to be multiples of 256 will ensure that the block offsets within buckets, // that are calculated, will also be multiples of 256. // See BucketEntry where offset to each block is represented using 5 bytes (instead of 8 // bytes long). We would like to save heap overhead as less as possible. throw new IllegalArgumentException("Illegal value: " + bucketSize + " configured for '" + BUCKET_CACHE_BUCKETS_KEY + "'. All bucket sizes to be multiples of 256"); } bucketSizes[i] = bucketSize; } } BucketCache bucketCache = null; try { int ioErrorsTolerationDuration = c.getInt( "hbase.bucketcache.ioengine.errors.tolerated.duration", BucketCache.DEFAULT_ERROR_TOLERATION_DURATION); // Bucket cache logs its stats on creation internal to the constructor. bucketCache = new BucketCache(bucketCacheIOEngineName, bucketCacheSize, blockSize, bucketSizes, writerThreads, writerQueueLen, persistentPath, ioErrorsTolerationDuration, c); } catch (IOException ioex) { LOG.error("Can't instantiate bucket cache", ioex); throw new RuntimeException(ioex); } return bucketCache; } }
hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/BlockCacheFactory.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.io.hfile; import static org.apache.hadoop.hbase.HConstants.BUCKET_CACHE_IOENGINE_KEY; import static org.apache.hadoop.hbase.HConstants.BUCKET_CACHE_SIZE_KEY; import java.io.IOException; import java.util.concurrent.ForkJoinPool; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.io.hfile.bucket.BucketCache; import org.apache.hadoop.hbase.io.util.MemorySizeUtil; import org.apache.hadoop.hbase.util.ReflectionUtils; import org.apache.hadoop.util.StringUtils; import org.apache.yetus.audience.InterfaceAudience; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @InterfaceAudience.Private public final class BlockCacheFactory { private static final Logger LOG = LoggerFactory.getLogger(BlockCacheFactory.class.getName()); /** * Configuration keys for Bucket cache */ /** * Configuration key to cache block policy (Lru, TinyLfu). */ public static final String BLOCKCACHE_POLICY_KEY = "hfile.block.cache.policy"; public static final String BLOCKCACHE_POLICY_DEFAULT = "LRU"; /** * If the chosen ioengine can persist its state across restarts, the path to the file to persist * to. This file is NOT the data file. It is a file into which we will serialize the map of * what is in the data file. For example, if you pass the following argument as * BUCKET_CACHE_IOENGINE_KEY ("hbase.bucketcache.ioengine"), * <code>file:/tmp/bucketcache.data </code>, then we will write the bucketcache data to the file * <code>/tmp/bucketcache.data</code> but the metadata on where the data is in the supplied file * is an in-memory map that needs to be persisted across restarts. Where to store this * in-memory state is what you supply here: e.g. <code>/tmp/bucketcache.map</code>. */ public static final String BUCKET_CACHE_PERSISTENT_PATH_KEY = "hbase.bucketcache.persistent.path"; public static final String BUCKET_CACHE_WRITER_THREADS_KEY = "hbase.bucketcache.writer.threads"; public static final String BUCKET_CACHE_WRITER_QUEUE_KEY = "hbase.bucketcache.writer.queuelength"; /** * A comma-delimited array of values for use as bucket sizes. */ public static final String BUCKET_CACHE_BUCKETS_KEY = "hbase.bucketcache.bucket.sizes"; /** * Defaults for Bucket cache */ public static final int DEFAULT_BUCKET_CACHE_WRITER_THREADS = 3; public static final int DEFAULT_BUCKET_CACHE_WRITER_QUEUE = 64; /** * The target block size used by blockcache instances. Defaults to * {@link HConstants#DEFAULT_BLOCKSIZE}. */ public static final String BLOCKCACHE_BLOCKSIZE_KEY = "hbase.blockcache.minblocksize"; private static final String EXTERNAL_BLOCKCACHE_KEY = "hbase.blockcache.use.external"; private static final boolean EXTERNAL_BLOCKCACHE_DEFAULT = false; private static final String EXTERNAL_BLOCKCACHE_CLASS_KEY = "hbase.blockcache.external.class"; /** * @deprecated use {@link BlockCacheFactory#BLOCKCACHE_BLOCKSIZE_KEY} instead. */ @Deprecated static final String DEPRECATED_BLOCKCACHE_BLOCKSIZE_KEY = "hbase.blockcache.minblocksize"; /** * The config point hbase.offheapcache.minblocksize is completely wrong, which is replaced by * {@link BlockCacheFactory#BLOCKCACHE_BLOCKSIZE_KEY}. Keep the old config key here for backward * compatibility. */ static { Configuration.addDeprecation(DEPRECATED_BLOCKCACHE_BLOCKSIZE_KEY, BLOCKCACHE_BLOCKSIZE_KEY); } private BlockCacheFactory() { } public static BlockCache createBlockCache(Configuration conf) { if (conf.get(DEPRECATED_BLOCKCACHE_BLOCKSIZE_KEY) != null) { LOG.warn("The config key {} is deprecated now, instead please use {}. In future release " + "we will remove the deprecated config.", DEPRECATED_BLOCKCACHE_BLOCKSIZE_KEY, BLOCKCACHE_BLOCKSIZE_KEY); } FirstLevelBlockCache l1Cache = createFirstLevelCache(conf); if (l1Cache == null) { return null; } boolean useExternal = conf.getBoolean(EXTERNAL_BLOCKCACHE_KEY, EXTERNAL_BLOCKCACHE_DEFAULT); if (useExternal) { BlockCache l2CacheInstance = createExternalBlockcache(conf); return l2CacheInstance == null ? l1Cache : new InclusiveCombinedBlockCache(l1Cache, l2CacheInstance); } else { // otherwise use the bucket cache. BucketCache bucketCache = createBucketCache(conf); if (!conf.getBoolean("hbase.bucketcache.combinedcache.enabled", true)) { // Non combined mode is off from 2.0 LOG.warn( "From HBase 2.0 onwards only combined mode of LRU cache and bucket cache is available"); } return bucketCache == null ? l1Cache : new CombinedBlockCache(l1Cache, bucketCache); } } private static FirstLevelBlockCache createFirstLevelCache(final Configuration c) { final long cacheSize = MemorySizeUtil.getOnHeapCacheSize(c); if (cacheSize < 0) { return null; } String policy = c.get(BLOCKCACHE_POLICY_KEY, BLOCKCACHE_POLICY_DEFAULT); int blockSize = c.getInt(BLOCKCACHE_BLOCKSIZE_KEY, HConstants.DEFAULT_BLOCKSIZE); LOG.info("Allocating BlockCache size=" + StringUtils.byteDesc(cacheSize) + ", blockSize=" + StringUtils.byteDesc(blockSize)); if (policy.equalsIgnoreCase("LRU")) { return new LruBlockCache(cacheSize, blockSize, true, c); } else if (policy.equalsIgnoreCase("TinyLFU")) { return new TinyLfuBlockCache(cacheSize, blockSize, ForkJoinPool.commonPool(), c); } else { throw new IllegalArgumentException("Unknown policy: " + policy); } } /** * Enum of all built in external block caches. * This is used for config. */ private static enum ExternalBlockCaches { memcached("org.apache.hadoop.hbase.io.hfile.MemcachedBlockCache"); // TODO(eclark): Consider more. Redis, etc. Class<? extends BlockCache> clazz; ExternalBlockCaches(String clazzName) { try { clazz = (Class<? extends BlockCache>) Class.forName(clazzName); } catch (ClassNotFoundException cnef) { clazz = null; } } ExternalBlockCaches(Class<? extends BlockCache> clazz) { this.clazz = clazz; } } private static BlockCache createExternalBlockcache(Configuration c) { if (LOG.isDebugEnabled()) { LOG.debug("Trying to use External l2 cache"); } Class klass = null; // Get the class, from the config. s try { klass = ExternalBlockCaches .valueOf(c.get(EXTERNAL_BLOCKCACHE_CLASS_KEY, "memcache")).clazz; } catch (IllegalArgumentException exception) { try { klass = c.getClass(EXTERNAL_BLOCKCACHE_CLASS_KEY, Class.forName( "org.apache.hadoop.hbase.io.hfile.MemcachedBlockCache")); } catch (ClassNotFoundException e) { return null; } } // Now try and create an instance of the block cache. try { LOG.info("Creating external block cache of type: " + klass); return (BlockCache) ReflectionUtils.newInstance(klass, c); } catch (Exception e) { LOG.warn("Error creating external block cache", e); } return null; } private static BucketCache createBucketCache(Configuration c) { // Check for L2. ioengine name must be non-null. String bucketCacheIOEngineName = c.get(BUCKET_CACHE_IOENGINE_KEY, null); if (bucketCacheIOEngineName == null || bucketCacheIOEngineName.length() <= 0) { return null; } int blockSize = c.getInt(BLOCKCACHE_BLOCKSIZE_KEY, HConstants.DEFAULT_BLOCKSIZE); final long bucketCacheSize = MemorySizeUtil.getBucketCacheSize(c); if (bucketCacheSize <= 0) { throw new IllegalStateException("bucketCacheSize <= 0; Check " + BUCKET_CACHE_SIZE_KEY + " setting and/or server java heap size"); } if (c.get("hbase.bucketcache.percentage.in.combinedcache") != null) { LOG.warn("Configuration 'hbase.bucketcache.percentage.in.combinedcache' is no longer " + "respected. See comments in http://hbase.apache.org/book.html#_changes_of_note"); } int writerThreads = c.getInt(BUCKET_CACHE_WRITER_THREADS_KEY, DEFAULT_BUCKET_CACHE_WRITER_THREADS); int writerQueueLen = c.getInt(BUCKET_CACHE_WRITER_QUEUE_KEY, DEFAULT_BUCKET_CACHE_WRITER_QUEUE); String persistentPath = c.get(BUCKET_CACHE_PERSISTENT_PATH_KEY); String[] configuredBucketSizes = c.getStrings(BUCKET_CACHE_BUCKETS_KEY); int [] bucketSizes = null; if (configuredBucketSizes != null) { bucketSizes = new int[configuredBucketSizes.length]; for (int i = 0; i < configuredBucketSizes.length; i++) { int bucketSize = Integer.parseInt(configuredBucketSizes[i].trim()); if (bucketSize % 256 != 0) { // We need all the bucket sizes to be multiples of 256. Having all the configured bucket // sizes to be multiples of 256 will ensure that the block offsets within buckets, // that are calculated, will also be multiples of 256. // See BucketEntry where offset to each block is represented using 5 bytes (instead of 8 // bytes long). We would like to save heap overhead as less as possible. throw new IllegalArgumentException("Illegal value: " + bucketSize + " configured for '" + BUCKET_CACHE_BUCKETS_KEY + "'. All bucket sizes to be multiples of 256"); } bucketSizes[i] = bucketSize; } } BucketCache bucketCache = null; try { int ioErrorsTolerationDuration = c.getInt( "hbase.bucketcache.ioengine.errors.tolerated.duration", BucketCache.DEFAULT_ERROR_TOLERATION_DURATION); // Bucket cache logs its stats on creation internal to the constructor. bucketCache = new BucketCache(bucketCacheIOEngineName, bucketCacheSize, blockSize, bucketSizes, writerThreads, writerQueueLen, persistentPath, ioErrorsTolerationDuration, c); } catch (IOException ioex) { LOG.error("Can't instantiate bucket cache", ioex); throw new RuntimeException(ioex); } return bucketCache; } }
Revert "HBASE-22610 [BucketCache] Rename hbase.offheapcache.minblocksize" Reason: Deprecated a wrong parameter. This reverts commit fe450b50c1c0060773f5e3f3b884da2cf45beadc.
hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/BlockCacheFactory.java
Revert "HBASE-22610 [BucketCache] Rename hbase.offheapcache.minblocksize"
<ide><path>base-server/src/main/java/org/apache/hadoop/hbase/io/hfile/BlockCacheFactory.java <ide> /** <ide> * The target block size used by blockcache instances. Defaults to <ide> * {@link HConstants#DEFAULT_BLOCKSIZE}. <del> */ <del> public static final String BLOCKCACHE_BLOCKSIZE_KEY = "hbase.blockcache.minblocksize"; <add> * TODO: this config point is completely wrong, as it's used to determine the <add> * target block size of BlockCache instances. Rename. <add> */ <add> public static final String BLOCKCACHE_BLOCKSIZE_KEY = "hbase.offheapcache.minblocksize"; <ide> <ide> private static final String EXTERNAL_BLOCKCACHE_KEY = "hbase.blockcache.use.external"; <ide> private static final boolean EXTERNAL_BLOCKCACHE_DEFAULT = false; <ide> <ide> private static final String EXTERNAL_BLOCKCACHE_CLASS_KEY = "hbase.blockcache.external.class"; <ide> <del> /** <del> * @deprecated use {@link BlockCacheFactory#BLOCKCACHE_BLOCKSIZE_KEY} instead. <del> */ <del> @Deprecated <del> static final String DEPRECATED_BLOCKCACHE_BLOCKSIZE_KEY = "hbase.blockcache.minblocksize"; <del> <del> /** <del> * The config point hbase.offheapcache.minblocksize is completely wrong, which is replaced by <del> * {@link BlockCacheFactory#BLOCKCACHE_BLOCKSIZE_KEY}. Keep the old config key here for backward <del> * compatibility. <del> */ <del> static { <del> Configuration.addDeprecation(DEPRECATED_BLOCKCACHE_BLOCKSIZE_KEY, BLOCKCACHE_BLOCKSIZE_KEY); <del> } <del> <ide> private BlockCacheFactory() { <ide> } <ide> <ide> public static BlockCache createBlockCache(Configuration conf) { <del> if (conf.get(DEPRECATED_BLOCKCACHE_BLOCKSIZE_KEY) != null) { <del> LOG.warn("The config key {} is deprecated now, instead please use {}. In future release " <del> + "we will remove the deprecated config.", DEPRECATED_BLOCKCACHE_BLOCKSIZE_KEY, <del> BLOCKCACHE_BLOCKSIZE_KEY); <del> } <ide> FirstLevelBlockCache l1Cache = createFirstLevelCache(conf); <ide> if (l1Cache == null) { <ide> return null;
Java
apache-2.0
8d42b051efc2c682e73e437694b8dc120ebda642
0
hansenwt2/java-koans,itbhp/java-koans,pcssi/java-koans,dayFun/JavaKoans,DavidWhitlock/java-koans,dayFun/JavaKoans,YohendryAdmios/java-koans,itbhp/java-koans,matyb/java-koans,darsen/java-koans,yottamoto/java-koans,BWoodfork/java-koans,yottamoto/java-koans,blogscot/java-koans,rloomans/java-koans,matyb/java-koans,spyrosoft/java-koans-solutions,blogscot/java-koans,designreuse/java-koans,YohendryAdmios/java-koans,SylvesterAbreu/java-koans,xala3pa/java-koans,BillSchofield/java-koans,aetindle/java-koans,designreuse/java-koans,seanli310/java-koans,aetindle/java-koans,QLGu/java-koans,pcssi/java-koans,blogscot/java-koans,xala3pa/java-koans,yottamoto/java-koans,blogscot/java-koans,SylvesterAbreu/java-koans,darsen/java-koans,seanli310/java-koans,another-dave/java-koans,QLGu/java-koans,djrobson/java-koans,rloomans/java-koans,hansenwt2/java-koans,another-dave/java-koans,spyrosoft/java-koans-solutions,BWoodfork/java-koans,BillSchofield/java-koans,matyb/java-koans,jpodlech/java-koans,DavidWhitlock/java-koans,jpodlech/java-koans,djrobson/java-koans
package beginner; import java.io.IOException; import com.sandwich.koan.Koan; import static com.sandwich.koan.constant.KoanConstants.__; import static com.sandwich.util.Assert.assertEquals; public class AboutExceptions { private void doStuff() throws IOException { throw new IOException(); } @Koan public void catchCheckedExceptions() { String s; try { doStuff(); s = "code ran normally"; } catch(IOException e) { s = "exception thrown"; } assertEquals(s, __); } @Koan public void useFinally() { String s = ""; try { doStuff(); s += "code ran normally"; } catch(IOException e) { s += "exception thrown"; } finally { s += " and finally ran as well"; } assertEquals(s, __); } @Koan public void finallyWithoutCatch() { String s = ""; try { s = "code ran normally"; } finally { s += " and finally ran as well"; } assertEquals(s, __); } private void tryCatchFinallyWithVoidReturn(StringBuilder whatHappened) { try { whatHappened.append("did something dangerous"); doStuff(); } catch(IOException e) { whatHappened.append("; the catch block executed"); return; } finally { whatHappened.append(", but so did the finally!"); } } @Koan public void finallyIsAlwaysRan() { StringBuilder whatHappened = new StringBuilder(); tryCatchFinallyWithVoidReturn(whatHappened); assertEquals(whatHappened.toString(), __); } @SuppressWarnings("finally") // this is suppressed because returning in finally block is obviously a compiler warning private String returnStatementsEverywhere(StringBuilder whatHappened) { try { whatHappened.append("try"); doStuff(); return "from try"; } catch (IOException e) { whatHappened.append(", catch"); return "from catch"; } finally { whatHappened.append(", finally"); // Think about how bad an idea it is to put a return statement in the finally block // DO NOT DO THIS! return "from finally"; } } @Koan public void returnInFinallyBlock() { StringBuilder whatHappened = new StringBuilder(); // Which value will be returned here? assertEquals(returnStatementsEverywhere(whatHappened), __); assertEquals(whatHappened.toString(), __); } private void doUncheckedStuff() { throw new RuntimeException(); } @Koan public void catchUncheckedExceptions() { // What do you need to do to catch the unchecked exception? doUncheckedStuff(); } @SuppressWarnings("serial") static class ParentException extends Exception {} @SuppressWarnings("serial") static class ChildException extends ParentException {} private void throwIt() throws ParentException { throw new ChildException(); } @Koan public void catchOrder() { String s = ""; try { throwIt(); } catch(ChildException e) { s = "ChildException"; } catch(ParentException e) { s = "ParentException"; } assertEquals(s, __); } }
koans/src/beginner/AboutExceptions.java
package beginner; import java.io.IOException; import com.sandwich.koan.Koan; import static com.sandwich.koan.constant.KoanConstants.__; import static com.sandwich.util.Assert.assertEquals; public class AboutExceptions { private void doStuff() throws IOException { throw new IOException(); } @Koan public void catchCheckedExceptions() { String s; try { doStuff(); s = "code ran normally"; } catch(IOException e) { s = "exception thrown"; } assertEquals(s, __); } @Koan public void useFinally() { String s = ""; try { doStuff(); s += "code ran normally"; } catch(IOException e) { s += "exception thrown"; } finally { s += " and finally ran as well"; } assertEquals(s, __); } @Koan public void finallyWithoutCatch() { String s = ""; try { s = "code ran normally"; } finally { s += " and finally ran as well"; } assertEquals(s, __); } private void tryCatchFinallyWithVoidReturn(StringBuilder whatHappened) { try { whatHappened.append("did something dangerous"); doStuff(); } catch(IOException e) { whatHappened.append("; the catch block executed"); return; } finally { whatHappened.append(", but so did the finally!"); } } @Koan public void finallyIsAlwaysRan() { StringBuilder whatHappened = new StringBuilder(); tryCatchFinallyWithVoidReturn(whatHappened); assertEquals(whatHappened.toString(), __); } @SuppressWarnings("finally") // this is suppressed because returning in finally block is obviously a compiler warning private String returnStatementsEverywhere(StringBuilder whatHappened) { try { whatHappened.append("try"); doStuff(); return "from try"; } catch (IOException e) { whatHappened.append(", catch"); return "from catch"; } finally { whatHappened.append(", finally"); // Think about how bad an idea it is to put a return statement in the finally block // DO NOT DO THIS! return "from finally"; } } @Koan public void returnInFinallyBlock() { StringBuilder whatHappened = new StringBuilder(); // Which value will be returned here? assertEquals(returnStatementsEverywhere(whatHappened), __); assertEquals(whatHappened.toString(), __); } private void doUncheckedStuff() { throw new RuntimeException(); } @Koan public void catchUncheckedExceptions() { // What do you need to do to catch the unchecked exception? doUncheckedStuff(); } @SuppressWarnings("serial") static class ParentException extends Exception {} @SuppressWarnings("serial") static class ChildException extends ParentException {} private void throwIt() throws ParentException { throw new ChildException(); } @Koan public void catchOrder() { String s = ""; try { throwIt(); } catch(ChildException e) { s = "ChildException"; } catch(ParentException e) { s = "ParentException"; } assertEquals(s, __); } }
Whitespace cleanup
koans/src/beginner/AboutExceptions.java
Whitespace cleanup
<ide><path>oans/src/beginner/AboutExceptions.java <ide> <ide> @Koan <ide> public void catchOrder() { <del> String s = ""; <add> String s = ""; <ide> try { <ide> throwIt(); <ide> } catch(ChildException e) {
Java
apache-2.0
5c1f93f7979c2916ccec78179eec814505eedd42
0
stefanverhoeff/android-sunshine-v2
package com.example.android.sunshine.app; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutionException; public class ForecastFragment extends Fragment { static String LOG_TAG = ForecastFragment.class.getSimpleName(); public ForecastFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); Context context = getActivity(); List<String> mockWeatherData = Arrays.asList("Hey", "Ho", "hey", "ho", "off", "to", "work", "we", "go"); ArrayAdapter<String> forecastAdaptor = new ArrayAdapter<>( context, R.layout.list_item_forecast, R.id.list_item_forecast_textview, mockWeatherData); ListView listViewForecast = rootView.findViewById(R.id.listview_forecast); listViewForecast.setAdapter(forecastAdaptor); WeatherFetchingTask weatherFetcher = new WeatherFetchingTask(); weatherFetcher.execute(); String weatherDataJson = null; try { weatherDataJson = weatherFetcher.get(); } catch (InterruptedException | ExecutionException e) { Log.e(LOG_TAG, e.getMessage(), e); } Log.i(LOG_TAG + ":jsonData", weatherDataJson); return rootView; } private static class WeatherFetchingTask extends AsyncTask<Void, Void, String> { static final String LOG_TAG = WeatherFetchingTask.class.getSimpleName(); static final String APP_ID = "b95677c89902dc35959d2ef9c3a455d9"; static final int TAMPERE_CITY_ID = 634963; @Override protected String doInBackground(Void... objects) { // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; try { // Construct the URL for the OpenWeatherMap query // Possible parameters are avaiable at OWM's forecast API page, at // http://openweathermap.org/API#forecast URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?id=" + TAMPERE_CITY_ID + "&units=metric&mode=json&cnt=7&appid=" + APP_ID); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuilder buffer = new StringBuilder(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line).append("\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } forecastJsonStr = buffer.toString(); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); // If the code didn't successfully get the weather data, there's no point in attemping // to parse it. return null; } finally{ if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } return forecastJsonStr; } } }
app/src/main/java/com/example/android/sunshine/app/ForecastFragment.java
package com.example.android.sunshine.app; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutionException; public class ForecastFragment extends Fragment { static String LOG_TAG = ForecastFragment.class.getCanonicalName(); public ForecastFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); Context context = getActivity(); List<String> mockWeatherData = Arrays.asList("Hey", "Ho", "hey", "ho", "off", "to", "work", "we", "go"); ArrayAdapter<String> forecastAdaptor = new ArrayAdapter<>( context, R.layout.list_item_forecast, R.id.list_item_forecast_textview, mockWeatherData); ListView listViewForecast = rootView.findViewById(R.id.listview_forecast); listViewForecast.setAdapter(forecastAdaptor); WeatherFetchingTask weatherFetcher = new WeatherFetchingTask(); weatherFetcher.execute(); String weatherDataJson = null; try { weatherDataJson = weatherFetcher.get(); } catch (InterruptedException | ExecutionException e) { Log.e(LOG_TAG, e.getMessage(), e); } Log.i(LOG_TAG + ":jsonData", weatherDataJson); return rootView; } private static class WeatherFetchingTask extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... objects) { // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; try { // Construct the URL for the OpenWeatherMap query // Possible parameters are avaiable at OWM's forecast API page, at // http://openweathermap.org/API#forecast String appId = "b95677c89902dc35959d2ef9c3a455d9"; int tampereCityId = 634963; URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?id=" + tampereCityId + "&units=metric&mode=json&cnt=7&appid=" + appId); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuilder buffer = new StringBuilder(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line).append("\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } forecastJsonStr = buffer.toString(); } catch (IOException e) { Log.e("ForecastFragment", "Error ", e); // If the code didn't successfully get the weather data, there's no point in attemping // to parse it. return null; } finally{ if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e("ForecastFragment", "Error closing stream", e); } } } return forecastJsonStr; } } }
Refactoring: cleaner logging and extract some constants
app/src/main/java/com/example/android/sunshine/app/ForecastFragment.java
Refactoring: cleaner logging and extract some constants
<ide><path>pp/src/main/java/com/example/android/sunshine/app/ForecastFragment.java <ide> import java.util.concurrent.ExecutionException; <ide> <ide> public class ForecastFragment extends Fragment { <del> static String LOG_TAG = ForecastFragment.class.getCanonicalName(); <add> static String LOG_TAG = ForecastFragment.class.getSimpleName(); <ide> <ide> public ForecastFragment() { <ide> } <ide> } <ide> <ide> private static class WeatherFetchingTask extends AsyncTask<Void, Void, String> { <add> <add> static final String LOG_TAG = WeatherFetchingTask.class.getSimpleName(); <add> static final String APP_ID = "b95677c89902dc35959d2ef9c3a455d9"; <add> static final int TAMPERE_CITY_ID = 634963; <add> <ide> @Override <ide> protected String doInBackground(Void... objects) { <ide> // These two need to be declared outside the try/catch <ide> // Construct the URL for the OpenWeatherMap query <ide> // Possible parameters are avaiable at OWM's forecast API page, at <ide> // http://openweathermap.org/API#forecast <del> String appId = "b95677c89902dc35959d2ef9c3a455d9"; <del> int tampereCityId = 634963; <del> URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?id=" + tampereCityId + "&units=metric&mode=json&cnt=7&appid=" + appId); <add> URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?id=" + TAMPERE_CITY_ID + "&units=metric&mode=json&cnt=7&appid=" + APP_ID); <ide> <ide> // Create the request to OpenWeatherMap, and open the connection <ide> urlConnection = (HttpURLConnection) url.openConnection(); <ide> } <ide> forecastJsonStr = buffer.toString(); <ide> } catch (IOException e) { <del> Log.e("ForecastFragment", "Error ", e); <add> Log.e(LOG_TAG, "Error ", e); <ide> // If the code didn't successfully get the weather data, there's no point in attemping <ide> // to parse it. <ide> return null; <ide> try { <ide> reader.close(); <ide> } catch (final IOException e) { <del> Log.e("ForecastFragment", "Error closing stream", e); <add> Log.e(LOG_TAG, "Error closing stream", e); <ide> } <ide> } <ide> }
Java
apache-2.0
83e0d6176148356c12682fc35edd60e62158a97a
0
vpro/poel,vpro/poel,vpro/poel,vpro/poel
package nl.vpro.poel.dto; public class PredictionDTO { private Long matchId; private Integer homeTeamGoals; private Integer awayTeamGoals; public Long getMatchId() { return matchId; } public void setMatchId(Long matchId) { this.matchId = matchId; } public Integer getHomeTeamGoals() { return homeTeamGoals; } public void setHomeTeamGoals(int homeTeamGoals) { this.homeTeamGoals = homeTeamGoals; } public Integer getAwayTeamGoals() { return awayTeamGoals; } public void setAwayTeamGoals(int awayTeamGoals) { this.awayTeamGoals = awayTeamGoals; } @Override public String toString() { return "PredictionDTO{" + "matchId=" + matchId + ", homeTeamGoals=" + homeTeamGoals + ", awayTeamGoals=" + awayTeamGoals + '}'; } }
src/main/java/nl/vpro/poel/dto/PredictionDTO.java
package nl.vpro.poel.dto; import javax.validation.constraints.Null; public class PredictionDTO { private Long matchId; private Integer homeTeamGoals; private Integer awayTeamGoals; public Long getMatchId() { return matchId; } public void setMatchId(Long matchId) { this.matchId = matchId; } public Integer getHomeTeamGoals() { return homeTeamGoals; } public void setHomeTeamGoals(int homeTeamGoals) { this.homeTeamGoals = homeTeamGoals; } public Integer getAwayTeamGoals() { return awayTeamGoals; } public void setAwayTeamGoals(int awayTeamGoals) { this.awayTeamGoals = awayTeamGoals; } @Override public String toString() { return "PredictionDTO{" + "matchId=" + matchId + ", homeTeamGoals=" + homeTeamGoals + ", awayTeamGoals=" + awayTeamGoals + '}'; } }
Don't use the unused import, Luke!
src/main/java/nl/vpro/poel/dto/PredictionDTO.java
Don't use the unused import, Luke!
<ide><path>rc/main/java/nl/vpro/poel/dto/PredictionDTO.java <ide> package nl.vpro.poel.dto; <del> <del>import javax.validation.constraints.Null; <ide> <ide> public class PredictionDTO { <ide>
Java
agpl-3.0
6787f4caa12099e82ce4ab20b9471a1bef8e4970
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
2cac2370-2e60-11e5-9284-b827eb9e62be
hello.java
2ca55ca2-2e60-11e5-9284-b827eb9e62be
2cac2370-2e60-11e5-9284-b827eb9e62be
hello.java
2cac2370-2e60-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>2ca55ca2-2e60-11e5-9284-b827eb9e62be <add>2cac2370-2e60-11e5-9284-b827eb9e62be
Java
apache-2.0
9d6da6347050c950931516362b5b131efca87376
0
Netflix/hollow,Netflix/hollow,Netflix/hollow
/* * * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.producer.validation; import java.util.logging.Level; import java.util.logging.Logger; import com.netflix.hollow.api.producer.HollowProducer.ReadState; import com.netflix.hollow.api.producer.HollowProducer.Validator; import com.netflix.hollow.core.read.engine.HollowTypeReadState; /** * @author lkanchanapalli * */ public class RecordCountVarianceValidator implements Validator { private final String typeName; private final float allowableVariancePercent; private final Logger log = Logger.getLogger(RecordCountVarianceValidator.class.getName()); /** * * @param typeName * @param allowableVariancePercent: Used to validate if the cardinality change in current cycle is with in the allowed percent. * Ex: 0% allowableVariancePercent ensures type cardinality does not vary at all for cycle to cycle. Ex: Number of state in United States. * 10% allowableVariancePercent: from previous cycle any addition or removal within 10% cardinality is valid. Anything more results in failure of validation. */ public RecordCountVarianceValidator(String typeName, float allowableVariancePercent) { this.typeName = typeName; if(allowableVariancePercent < 0) throw new IllegalArgumentException("RecordCountVarianceValidator for type "+typeName+": cannot have allowableVariancePercent less than 0. Value provided: "+allowableVariancePercent); this.allowableVariancePercent = allowableVariancePercent; } /* (non-Javadoc) * @see com.netflix.hollow.api.producer.HollowProducer.Validator#validate(com.netflix.hollow.api.producer.HollowProducer.ReadState) */ @Override public void validate(ReadState readState) { log.log(Level.INFO, "Running RecordCountVarianceValidator for type "+typeName); HollowTypeReadState typeState = readState.getStateEngine().getTypeState(typeName); int latestCardinality = typeState.getPopulatedOrdinals().cardinality(); int previousCardinality = typeState.getPreviousOrdinals().cardinality(); // TODO: log message indicating previous state is 0. Can happen for new name space. And also can happen // when a type gets to zero count then the validation will be skipped. if(previousCardinality == 0){ log.log(Level.WARNING, "previousCardinality is 0. Not running RecordCountVarianceValidator for type "+typeName +". This scenario is not expected except when starting a new namespace.O"); return; } float actualChangePercent = getChangePercent(latestCardinality, previousCardinality); if (Float.compare(actualChangePercent, allowableVariancePercent) > 0) { throw new ValidationException("RecordCountVarianceValidator for type " + typeName + " failed. Actual variance: " + actualChangePercent + "%; Allowed variance: " + allowableVariancePercent + "%; previous cycle record count: " + previousCardinality + "; current cycle record count: " + latestCardinality); } } float getChangePercent(int latestCardinality, int previousCardinality) { int diff = Math.abs(latestCardinality - previousCardinality); float changePercent = ((float)100.0* diff)/(float)previousCardinality; return changePercent; } }
hollow/src/main/java/com/netflix/hollow/api/producer/validation/RecordCountVarianceValidator.java
/* * * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.producer.validation; import java.util.logging.Level; import java.util.logging.Logger; import com.netflix.hollow.api.producer.HollowProducer.ReadState; import com.netflix.hollow.api.producer.HollowProducer.Validator; import com.netflix.hollow.core.read.engine.HollowTypeReadState; /** * @author lkanchanapalli * */ public class RecordCountVarianceValidator implements Validator { private final String typeName; private final float allowableVariancePercent; private final Logger log = Logger.getLogger(RecordCountVarianceValidator.class.getName()); /** * * @param typeName * @param allowableVariancePercent: Used to validate if the cardinality change in current cycle is with in the allowed percent. * Ex: 0% allowableVariancePercent ensures type cardinality does not vary at all for cycle to cycle. Ex: Number of state in United States. * 10% allowableVariancePercent: from previous cycle any addition or removal within 10% cardinality is valid. Anything more results in failure of validation. */ public RecordCountVarianceValidator(String typeName, float allowableVariancePercent) { this.typeName = typeName; if(allowableVariancePercent < 0) throw new IllegalArgumentException("RecordCountVarianceValidator for type "+typeName+": cannot have allowableVariancePercent less than 0. Value provided: "+allowableVariancePercent); this.allowableVariancePercent = allowableVariancePercent; } /* (non-Javadoc) * @see com.netflix.hollow.api.producer.HollowProducer.Validator#validate(com.netflix.hollow.api.producer.HollowProducer.ReadState) */ @Override public void validate(ReadState readState) { log.log(Level.INFO, "Running RecordCountVarianceValidator for type "+typeName); HollowTypeReadState typeState = readState.getStateEngine().getTypeState(typeName); int latestCardinality = typeState.getPopulatedOrdinals().cardinality(); int previousCardinality = typeState.getPreviousOrdinals().cardinality(); // TODO: log message indicating previous state is 0. Can happen for new name space. And also can happen // when a type gets to zero count then the validation will be skipped. if(previousCardinality == 0) return; float actualChangePercent = getChangePercent(latestCardinality, previousCardinality); if (Float.compare(actualChangePercent, allowableVariancePercent) > 0) { throw new ValidationException("RecordCountVarianceValidator for type " + typeName + " failed. Actual variance: " + actualChangePercent + "%; Allowed variance: " + allowableVariancePercent + "%; previous cycle record count: " + previousCardinality + "; current cycle record count: " + latestCardinality); } } float getChangePercent(int latestCardinality, int previousCardinality) { int diff = Math.abs(latestCardinality - previousCardinality); float changePercent = ((float)100.0* diff)/(float)previousCardinality; return changePercent; } }
Add logging
hollow/src/main/java/com/netflix/hollow/api/producer/validation/RecordCountVarianceValidator.java
Add logging
<ide><path>ollow/src/main/java/com/netflix/hollow/api/producer/validation/RecordCountVarianceValidator.java <ide> <ide> // TODO: log message indicating previous state is 0. Can happen for new name space. And also can happen <ide> // when a type gets to zero count then the validation will be skipped. <del> if(previousCardinality == 0) <add> if(previousCardinality == 0){ <add> log.log(Level.WARNING, "previousCardinality is 0. Not running RecordCountVarianceValidator for type "+typeName <add> +". This scenario is not expected except when starting a new namespace.O"); <ide> return; <add> } <ide> <ide> float actualChangePercent = getChangePercent(latestCardinality, previousCardinality); <ide> if (Float.compare(actualChangePercent, allowableVariancePercent) > 0) {
Java
apache-2.0
0e40170e74d60b6c2cc111ed95d113bc5a028494
0
Dakror/Arise,Dakror/Arise
package de.dakror.arise.game.building; import org.json.JSONException; import de.dakror.arise.game.Game; import de.dakror.arise.settings.Resources.Resource; import de.dakror.arise.ui.BuildButton; /** * @author Dakror */ public class Barracks extends Building { public Barracks(int x, int y, int level) { super(x, y, 8, 7, level); typeId = 5; name = "Kaserne"; desc = "Hier können Fußsoldaten ausgebildet und verbessert werden."; tx = 6; ty = 9; tw = 8; th = 7; by = 4; bh -= 4; // final Resources r = new Resources(); // r.add(Resource.GOLD, 20); // r.add(Resource.WOOD, 10); // r.add(Resource.STONE, 2); // addGuiButton(0, 1, new Point(4, 0), "10 Schwertkämpfer", "Eine Einheit aus 10 starken und gut gepanzerten, jedoch langsamen Nahkämpfern.", r, 0, new ClickEvent() // { // @Override // public void trigger() // { // // queue(r, "S"); // } // }); // // final Resources r2 = new Resources(); // r2.add(Resource.GOLD, 40); // r2.add(Resource.WOOD, 20); // addGuiButton(1, 1, new Point(4, 1), "10 Lanzenträger", "Eine Einheit aus 10 mäßig starken und gepanzerten, jedoch schnellen Nahkämpfern.", r2, 0, new ClickEvent() // { // @Override // public void trigger() // { // // queue(r2, "L"); // } // }); // init(); } // protected void queue(Resources r, String n) // { // if (metadata.length() < Building.MAX_QUEUE) // { // CityLayer.resources.add(Resources.mul(r, -1)); // if (metadata.length() == 0) setStageChangeTimestamp(System.currentTimeMillis() / 1000); // metadata += n; // CityHUDLayer.cl.saveData(); // // updateQueueDisplay(); // } // } @Override protected float getStageChangeDuration() { try { return (stage != 1) ? super.getStageChangeDuration() : Math.round(Building.TROOPS.getInt(getResourceNameForTroop(getFirstPlaceInQueue()).name()) / Game.world.getSpeed()); } catch (JSONException e) { e.printStackTrace(); return 0; } } @Override public void onSpecificChange() { // if (stage == 1) // { // Resource r = getResourceNameForTroop(getFirstPlaceInQueue()); // if (r != null) // { // metadata = (metadata.length() > 1 ? metadata.substring(1) : ""); // CityLayer.resources.add(r, 10); // // if (metadata.length() > 0) setStageChangeTimestamp(System.currentTimeMillis() / 1000); // // CityHUDLayer.cl.saveData(); // // updateQueueDisplay(); // } // } } protected String getFirstPlaceInQueue() { if (metadata.length() == 0) return ""; else return metadata.substring(0, 1); } protected Resource getResourceNameForTroop(String troop) { if (troop.equals("S")) return Resource.SWORDFIGHTER; if (troop.equals("L")) return Resource.LANCEBEARER; return null; } @Override public void setMetadata(String s) { super.setMetadata(s); updateQueueDisplay(); } protected void updateQueueDisplay() { int S = 0, L = 0; for (int i = 0; i < metadata.length(); i++) { if (metadata.charAt(i) == 'S') S++; if (metadata.charAt(i) == 'L') L++; } ((BuildButton) guiContainer.components.get(0)).number = S; ((BuildButton) guiContainer.components.get(1)).number = L; } @Override public void updateGuiButtons() { for (int i = 0; i < guiContainer.components.size(); i++) guiContainer.components.get(i).enabled = metadata.length() < Building.MAX_QUEUE; } }
src/main/java/de/dakror/arise/game/building/Barracks.java
package de.dakror.arise.game.building; import java.awt.Point; import org.json.JSONException; import de.dakror.arise.game.Game; import de.dakror.arise.settings.Resources; import de.dakror.arise.settings.Resources.Resource; import de.dakror.arise.ui.BuildButton; import de.dakror.gamesetup.ui.ClickEvent; /** * @author Dakror */ public class Barracks extends Building { public Barracks(int x, int y, int level) { super(x, y, 8, 7, level); typeId = 5; name = "Kaserne"; desc = "Hier können Fußsoldaten ausgebildet und verbessert werden."; tx = 6; ty = 9; tw = 8; th = 7; by = 4; bh -= 4; final Resources r = new Resources(); r.add(Resource.GOLD, 20); r.add(Resource.WOOD, 10); r.add(Resource.STONE, 2); addGuiButton(0, 1, new Point(4, 0), "10 Schwertkämpfer", "Eine Einheit aus 10 starken und gut gepanzerten, jedoch langsamen Nahkämpfern.", r, 0, new ClickEvent() { @Override public void trigger() { // queue(r, "S"); } }); final Resources r2 = new Resources(); r2.add(Resource.GOLD, 40); r2.add(Resource.WOOD, 20); addGuiButton(1, 1, new Point(4, 1), "10 Lanzenträger", "Eine Einheit aus 10 mäßig starken und gepanzerten, jedoch schnellen Nahkämpfern.", r2, 0, new ClickEvent() { @Override public void trigger() { // queue(r2, "L"); } }); init(); } // protected void queue(Resources r, String n) // { // if (metadata.length() < Building.MAX_QUEUE) // { // CityLayer.resources.add(Resources.mul(r, -1)); // if (metadata.length() == 0) setStageChangeTimestamp(System.currentTimeMillis() / 1000); // metadata += n; // CityHUDLayer.cl.saveData(); // // updateQueueDisplay(); // } // } @Override protected float getStageChangeDuration() { try { return (stage != 1) ? super.getStageChangeDuration() : Math.round(Building.TROOPS.getInt(getResourceNameForTroop(getFirstPlaceInQueue()).name()) / Game.world.getSpeed()); } catch (JSONException e) { e.printStackTrace(); return 0; } } @Override public void onSpecificChange() { // if (stage == 1) // { // Resource r = getResourceNameForTroop(getFirstPlaceInQueue()); // if (r != null) // { // metadata = (metadata.length() > 1 ? metadata.substring(1) : ""); // CityLayer.resources.add(r, 10); // // if (metadata.length() > 0) setStageChangeTimestamp(System.currentTimeMillis() / 1000); // // CityHUDLayer.cl.saveData(); // // updateQueueDisplay(); // } // } } protected String getFirstPlaceInQueue() { if (metadata.length() == 0) return ""; else return metadata.substring(0, 1); } protected Resource getResourceNameForTroop(String troop) { if (troop.equals("S")) return Resource.SWORDFIGHTER; if (troop.equals("L")) return Resource.LANCEBEARER; return null; } @Override public void setMetadata(String s) { super.setMetadata(s); updateQueueDisplay(); } protected void updateQueueDisplay() { int S = 0, L = 0; for (int i = 0; i < metadata.length(); i++) { if (metadata.charAt(i) == 'S') S++; if (metadata.charAt(i) == 'L') L++; } ((BuildButton) guiContainer.components.get(0)).number = S; ((BuildButton) guiContainer.components.get(1)).number = L; } @Override public void updateGuiButtons() { for (int i = 0; i < guiContainer.components.size(); i++) guiContainer.components.get(i).enabled = metadata.length() < Building.MAX_QUEUE; } }
barracks disabled
src/main/java/de/dakror/arise/game/building/Barracks.java
barracks disabled
<ide><path>rc/main/java/de/dakror/arise/game/building/Barracks.java <ide> package de.dakror.arise.game.building; <del> <del>import java.awt.Point; <ide> <ide> import org.json.JSONException; <ide> <ide> import de.dakror.arise.game.Game; <del>import de.dakror.arise.settings.Resources; <ide> import de.dakror.arise.settings.Resources.Resource; <ide> import de.dakror.arise.ui.BuildButton; <del>import de.dakror.gamesetup.ui.ClickEvent; <ide> <ide> /** <ide> * @author Dakror <ide> by = 4; <ide> bh -= 4; <ide> <del> final Resources r = new Resources(); <del> r.add(Resource.GOLD, 20); <del> r.add(Resource.WOOD, 10); <del> r.add(Resource.STONE, 2); <del> addGuiButton(0, 1, new Point(4, 0), "10 Schwertkämpfer", "Eine Einheit aus 10 starken und gut gepanzerten, jedoch langsamen Nahkämpfern.", r, 0, new ClickEvent() <del> { <del> @Override <del> public void trigger() <del> { <del> // queue(r, "S"); <del> } <del> }); <del> <del> final Resources r2 = new Resources(); <del> r2.add(Resource.GOLD, 40); <del> r2.add(Resource.WOOD, 20); <del> addGuiButton(1, 1, new Point(4, 1), "10 Lanzenträger", "Eine Einheit aus 10 mäßig starken und gepanzerten, jedoch schnellen Nahkämpfern.", r2, 0, new ClickEvent() <del> { <del> @Override <del> public void trigger() <del> { <del> // queue(r2, "L"); <del> } <del> }); <del> <add> // final Resources r = new Resources(); <add> // r.add(Resource.GOLD, 20); <add> // r.add(Resource.WOOD, 10); <add> // r.add(Resource.STONE, 2); <add> // addGuiButton(0, 1, new Point(4, 0), "10 Schwertkämpfer", "Eine Einheit aus 10 starken und gut gepanzerten, jedoch langsamen Nahkämpfern.", r, 0, new ClickEvent() <add> // { <add> // @Override <add> // public void trigger() <add> // { <add> // // queue(r, "S"); <add> // } <add> // }); <add> // <add> // final Resources r2 = new Resources(); <add> // r2.add(Resource.GOLD, 40); <add> // r2.add(Resource.WOOD, 20); <add> // addGuiButton(1, 1, new Point(4, 1), "10 Lanzenträger", "Eine Einheit aus 10 mäßig starken und gepanzerten, jedoch schnellen Nahkämpfern.", r2, 0, new ClickEvent() <add> // { <add> // @Override <add> // public void trigger() <add> // { <add> // // queue(r2, "L"); <add> // } <add> // }); <add> // <ide> init(); <ide> } <ide>
Java
apache-2.0
be1761b872e3c182719f316e9020b15355e18585
0
cping/RipplePower,cping/RipplePower,cping/RipplePower,cping/RipplePower
package org.ripple.power.hft; import java.util.ArrayList; import java.util.List; import org.address.collection.ArrayMap; import org.address.ripple.RippleSeedAddress; import org.json.JSONObject; import org.ripple.power.config.LSystem; import org.ripple.power.timer.LTimer; import org.ripple.power.timer.LTimerContext; import org.ripple.power.timer.SystemTimer; import org.ripple.power.txns.AccountFind; import org.ripple.power.txns.AccountInfo; import org.ripple.power.txns.AccountLine; import org.ripple.power.txns.OfferPrice; import org.ripple.power.txns.OtherData; import org.ripple.power.txns.OtherData.CoinmarketcapData; import org.ripple.power.txns.Updateable; import org.ripple.power.txns.OfferPrice.OfferFruit; import org.ripple.power.utils.MathUtils; import com.ripple.core.types.known.sle.entries.Offer; public class TraderProcess extends TraderBase { private int analyze_limit = 5; private ArrayList<Task> _HFT_tasks = new ArrayList<Task>(10); private long _lastTimeMicros, _currTimeMicros, _goalTimeMicros, _elapsedTimeMicros, _remainderMicros, _elapsedTime; private long _maxFrames = 60; private Thread _mainLoop = null; private final Object _synch = new Object(); private final LTimerContext _timerContext = new LTimerContext(); private SystemTimer _timer; private boolean _isRunning, _isPause, _isDestroy, _isResume; public static enum Model { CrazyBuyer, CrazySeller, Spreads, Script } public static enum Trend { UP, DOWN, UNKOWN; } protected static ArrayList<Store> _storage = new ArrayList<Store>(); private static class Store { public Trend trend = Trend.UNKOWN; public String name; public long date = 0; public Store(String name, Trend trend) { this.trend = trend; this.name = name; this.date = System.currentTimeMillis(); } } private static Trend reset(String name) { for (Store s : _storage) { if (s.name.equals(name) && (System.currentTimeMillis() - s.date) <= LSystem.MINUTE * 10) { return s.trend; } else if (s.name.equals(name)) { _storage.remove(s); return null; } } return null; } private static void addStorage(Store s) { _storage.add(s); if (_storage.size() > 100) { _storage.remove(0); } } /** * get Price trends * * @param curName * @param trend_limit * (1==10minute) * @return */ public Trend getTrend(String curName, int trend_limit) { curName = curName.trim().toLowerCase(); Trend result = reset(curName); if (result == null || result == Trend.UNKOWN) { try { if (trend_limit <= 1) { trend_limit = 2; } ArrayMap arrays = OtherData.getCapitalization(1, curName, trend_limit); if (arrays.size() == 0) { result = Trend.UNKOWN; } else { int up_coherent_flag = 0; int down_coherent_flag = 0; int size = arrays.size(); int limit = size - trend_limit; if (limit < 0) { limit = 0; } Trend last = Trend.UNKOWN; for (int i = size - trend_limit; i < size; i++) { if (i + 1 < size) { long one = (long) arrays.get(i); long two = (long) arrays.get(i + 1); if (two > one) { if (last == Trend.DOWN) { up_coherent_flag--; } else { up_coherent_flag++; } last = Trend.UP; } else { if (last == Trend.UP) { down_coherent_flag--; } else { down_coherent_flag++; } last = Trend.DOWN; } } } if (down_coherent_flag > up_coherent_flag) { return Trend.DOWN; } else if (up_coherent_flag > down_coherent_flag) { return Trend.UP; } else { return Trend.UNKOWN; } } } catch (Exception e) { try { CoinmarketcapData data = OtherData.getCoinmarketcapTo( "usd", curName); if (data.change7h.indexOf("-") == -1 && data.change1h.indexOf("-") == -1) { result = Trend.UP; } else { result = Trend.DOWN; } } catch (Exception ex) { addStorage(new Store(curName, Trend.UNKOWN)); } } } return result == null ? Trend.UNKOWN : result; } public static class Error { public int code; public String message; public Error(String mes) { this.message = mes; } public Error() { this("Empty"); } } public static class Task { int id; public TraderProcess process; public RippleSeedAddress seed; public String target_issuer = "unkown"; public String target_currency = "unkown"; public String source_currency = "unkown"; public String source_issuer = "unkown"; public double value = -1; public double real_max_value = -1; public double limit_volume = -1; public double minDifference = 0.1; public int orderId = -1; public double orderAmount = -1; public Model model = Model.Spreads; public ArrayList<Swap> swaps = new ArrayList<Swap>(10); public ArrayList<Error> errors = new ArrayList<Error>(10); public LTimer task_delay = new LTimer(LSystem.SECOND); public boolean stop; private long startTimeStamp = -1; public Task() { startTimeStamp = System.currentTimeMillis(); } public long getStartTimeStamp() { return startTimeStamp; } public void update(LTimerContext context) { if (task_delay.action(context)) { if (seed == null) { return; } if (id <= 0) { return; } if (target_currency.equalsIgnoreCase(source_currency)) { return; } if (model == null) { errors.add(new Error()); return; } if (!LSystem.nativeCurrency.equalsIgnoreCase(source_currency) && !LSystem.nativeCurrency .equalsIgnoreCase(target_currency) && !target_issuer.equalsIgnoreCase(source_issuer)) { return; } if (source_issuer == null || "unkown".equalsIgnoreCase(source_issuer)) { return; } if (target_issuer == null || "unkown".equalsIgnoreCase(target_issuer)) { return; } if (stop) { return; } // get limit trader price final double volumeWall = suggestWallVolume(real_max_value, limit_volume); // get average price String averagePrice = OfferPrice.getMoneyConvert("1", source_currency, target_currency); if (averagePrice == null || "unkown".equalsIgnoreCase(averagePrice)) { averagePrice = "-1"; } final double otherPrice = Double.parseDouble(averagePrice); // load exchange data OfferPrice.load(source_issuer, source_currency, target_currency, new OfferPrice() { @Override public void sell(Offer offer) { } @Override public void error(JSONObject obj) { errors.add(new Error(obj.toString())); } @Override public void empty() { errors.add(new Error()); } @Override public void complete(ArrayList<OfferFruit> buys, ArrayList<OfferFruit> sells, OfferPrice price) { // accurate to five decimal places String highBuy = null; if (price.highBuy != null) { if (price.highBuy.indexOf("/") != -1) { highBuy = price.highBuy.split("/")[0]; } highBuy = LSystem.getNumberShort(highBuy); } String hightSell = null; if (price.hightSell != null) { if (price.hightSell.indexOf("/") != -1) { hightSell = price.hightSell.split("/")[0]; } hightSell = LSystem .getNumberShort(hightSell); } log("other:" + otherPrice); log("buy:" + highBuy); log("sell:" + hightSell); // load data completed callCore(volumeWall, otherPrice, Task.this, buys, sells, price, Double.parseDouble(highBuy), Double.parseDouble(hightSell)); } @Override public void buy(Offer offer) { } }, false); } } } private static void callCore(double volumeWall, double otherPrice, Task task, ArrayList<OfferFruit> buys, ArrayList<OfferFruit> sells, OfferPrice price, double highBuy, double hightSell) { double avg_buy_value = task.process.averageBuyPrice(buys); double avg_sell_value = task.process.averageSellPrice(sells); double buy_difference = highBuy - avg_buy_value; double sell_difference = hightSell - avg_buy_value; double all_buy_difference = 0; if (otherPrice != -1) { all_buy_difference = otherPrice - avg_buy_value; } else { all_buy_difference = buy_difference; } double all_sell_difference = 0; if (otherPrice != -1) { all_sell_difference = otherPrice - avg_sell_value; } else { all_sell_difference = sell_difference; } Trend trend = task.process.getTrend(task.source_currency, 18); System.out.println(all_buy_difference); System.out.println(all_sell_difference); switch (task.model) { case CrazyBuyer: log("" + avg_buy_value); log("" + avg_sell_value); callBuy(0, 0, task); break; case CrazySeller: callSell(0, 0, task); break; case Spreads: break; case Script: break; default: break; } } public void setAnalyzeLimit(int l) { this.analyze_limit = l; } public int getAnalyzeLimit() { return this.analyze_limit; } private double averageBuyPrice(ArrayList<OfferFruit> bids) { double sumVolume = 0.0d; List<OfferFruit> tmp = null; if (bids.size() > analyze_limit) { tmp = bids.subList(0, analyze_limit); } else { tmp = bids; } int size = tmp.size(); for (OfferFruit bid : tmp) { double sellValue = Double.parseDouble(LSystem.getNumber( bid.offer.bidQuality(), false)); sumVolume += sellValue; } return sumVolume / size; } private double averageSellPrice(ArrayList<OfferFruit> asks) { double sumVolume = 0.0d; List<OfferFruit> tmp = null; if (asks.size() > analyze_limit) { tmp = asks.subList(0, analyze_limit); } else { tmp = asks; } int size = tmp.size(); for (OfferFruit ask : tmp) { double sellValue = Double.parseDouble(LSystem.getNumber( ask.offer.askQuality(), false)); sumVolume += sellValue; } return sumVolume / size; } private static void log(String mes) { System.out.println(mes); } static void callBuy(double srcValue, double dstValue, Task task) { log("testing..."); } static void callSell(double srcValue, double dstValue, Task task) { log("testing..."); } public boolean isRunning() { return _isRunning; } public boolean isPause() { return _isPause; } public boolean isResume() { return _isResume; } public boolean isDestroy() { return _isDestroy; } public void setFPS(long frames) { this._maxFrames = frames; } public ArrayList<Task> getAllSeller() { ArrayList<Task> tasks = new ArrayList<Task>(10); for (Task t : _HFT_tasks) { if (t.model.equals(Model.CrazySeller)) { tasks.add(t); } } return tasks; } public ArrayList<Task> getAllBuyer() { ArrayList<Task> tasks = new ArrayList<Task>(10); for (Task t : _HFT_tasks) { if (t.model.equals(Model.CrazyBuyer)) { tasks.add(t); } } return tasks; } public ArrayList<Task> getUserSpreads() { ArrayList<Task> tasks = new ArrayList<Task>(10); for (Task t : _HFT_tasks) { if (t.model.equals(Model.Spreads)) { tasks.add(t); } } return tasks; } public ArrayList<Task> getUserScript() { ArrayList<Task> tasks = new ArrayList<Task>(10); for (Task t : _HFT_tasks) { if (t.model.equals(Model.Script)) { tasks.add(t); } } return tasks; } private Updateable main() { Updateable updateable = new Updateable() { @Override public void action(Object o) { for (; _isRunning;) { _goalTimeMicros = _lastTimeMicros + 1000000L / _maxFrames; _currTimeMicros = _timer.sleepTimeMicros(_goalTimeMicros); _elapsedTimeMicros = _currTimeMicros - _lastTimeMicros + _remainderMicros; _elapsedTime = MathUtils .max(0, (_elapsedTimeMicros / 1000)); _remainderMicros = _elapsedTimeMicros - _elapsedTime * 1000; _lastTimeMicros = _currTimeMicros; _timerContext.millisSleepTime = _remainderMicros; _timerContext.timeSinceLastUpdate = _elapsedTime; runTaskTimer(_timerContext); if (_isPause) { pause(500); } } } }; return updateable; } public void loop() { _isRunning = true; if (_timer == null) { _timer = new SystemTimer(); } if (_mainLoop == null) { _mainLoop = new Thread() { public void run() { main().action(this); } }; _mainLoop.start(); } } private void runTaskTimer(LTimerContext context) { int size = _HFT_tasks.size(); for (int i = 0; i < size; i++) { Task task = _HFT_tasks.get(i); task.update(context); } } private final void pause(long sleep) { try { Thread.sleep(sleep); } catch (InterruptedException ex) { } } final void resume() { synchronized (_synch) { if (_isRunning || _mainLoop != null) { _isRunning = false; if (_mainLoop != null) { _mainLoop.interrupt(); _mainLoop = null; } } _isRunning = true; _isResume = true; loop(); } } final void pause() { synchronized (_synch) { if (!_isRunning) { return; } _isRunning = false; _isPause = true; while (_isPause) { try { _synch.wait(4000); } catch (InterruptedException ignored) { } } } } final void destroy() { synchronized (_synch) { _isRunning = false; _isDestroy = true; while (_isDestroy) { try { _synch.wait(); } catch (InterruptedException ex) { } } } } private final void callTask(Task task) { task.id += 1; _HFT_tasks.add(task); } public void execute(final Task task) { if (task.seed == null) { return; } task.process = this; String address = task.seed.getPublicKey(); AccountFind find = new AccountFind(); final AccountInfo info = new AccountInfo(); if (LSystem.nativeCurrency.equalsIgnoreCase(task.source_currency)) { find.processInfo(address, info, new Updateable() { @Override public void action(Object o) { String balance = info.balance; double srcXrpValue = Double.parseDouble(LSystem .getNumberShort(balance)); task.real_max_value = srcXrpValue; callTask(task); } }); } else { find.processLines(address, info, new Updateable() { @Override public void action(Object o) { ArrayList<AccountLine> lines = info.lines; if (lines.size() > 0) { for (AccountLine line : lines) { if (task.source_currency.equalsIgnoreCase(line .getCurrency()) && task.equals(line.getIssuer())) { double srcIouValue = Double.parseDouble(line .getAmount()); task.real_max_value = srcIouValue; } } } callTask(task); } }); } } }
eclipse/src/org/ripple/power/hft/TraderProcess.java
package org.ripple.power.hft; import java.util.ArrayList; import java.util.List; import org.address.collection.ArrayMap; import org.address.ripple.RippleSeedAddress; import org.json.JSONObject; import org.ripple.power.config.LSystem; import org.ripple.power.timer.LTimer; import org.ripple.power.timer.LTimerContext; import org.ripple.power.timer.SystemTimer; import org.ripple.power.txns.AccountFind; import org.ripple.power.txns.AccountInfo; import org.ripple.power.txns.AccountLine; import org.ripple.power.txns.OfferPrice; import org.ripple.power.txns.OtherData; import org.ripple.power.txns.OtherData.CoinmarketcapData; import org.ripple.power.txns.Updateable; import org.ripple.power.txns.OfferPrice.OfferFruit; import org.ripple.power.utils.MathUtils; import com.ripple.core.types.known.sle.entries.Offer; public class TraderProcess extends TraderBase { private int analyze_limit = 5; private ArrayList<Task> _HFT_tasks = new ArrayList<Task>(10); private long _lastTimeMicros, _currTimeMicros, _goalTimeMicros, _elapsedTimeMicros, _remainderMicros, _elapsedTime; private long _maxFrames = 60; private Thread _mainLoop = null; private final Object _synch = new Object(); private final LTimerContext _timerContext = new LTimerContext(); private SystemTimer _timer; private boolean _isRunning, _isPause, _isDestroy, _isResume; public static enum Model { CrazyBuyer, CrazySeller, Spreads, Script } public static enum Trend { UP, DOWN, UNKOWN; } protected static ArrayList<Store> _storage = new ArrayList<Store>(); private static class Store { public Trend trend = Trend.UNKOWN; public String name; public long date = 0; public Store(String name, Trend trend) { this.trend = trend; this.name = name; this.date = System.currentTimeMillis(); } } private static Trend reset(String name) { for (Store s : _storage) { if (s.name.equals(name) && (System.currentTimeMillis() - s.date) <= LSystem.MINUTE * 10) { return s.trend; } else if (s.name.equals(name)) { _storage.remove(s); return null; } } return null; } private static void addStorage(Store s) { _storage.add(s); if (_storage.size() > 100) { _storage.remove(0); } } /** * get Price trends * * @param curName * @param trend_limit * (1==10minute) * @return */ public Trend getTrend(String curName, int trend_limit) { curName = curName.trim().toLowerCase(); Trend result = reset(curName); if (result == null || result == Trend.UNKOWN) { try { if (trend_limit <= 1) { trend_limit = 2; } ArrayMap arrays = OtherData.getCapitalization(1, curName, trend_limit); if (arrays.size() == 0) { result = Trend.UNKOWN; } else { int up_coherent_flag = 0; int down_coherent_flag = 0; int size = arrays.size(); int limit = size - trend_limit; if (limit < 0) { limit = 0; } Trend last = Trend.UNKOWN; for (int i = size - trend_limit; i < size; i++) { if (i + 1 < size) { long one = (long) arrays.get(i); long two = (long) arrays.get(i + 1); if (two > one) { if (last == Trend.DOWN) { up_coherent_flag--; } else { up_coherent_flag++; } last = Trend.UP; } else { if (last == Trend.UP) { down_coherent_flag--; } else { down_coherent_flag++; } last = Trend.DOWN; } } } if (down_coherent_flag > up_coherent_flag) { return Trend.DOWN; } else if (up_coherent_flag > down_coherent_flag) { return Trend.UP; } else { return Trend.UNKOWN; } } } catch (Exception e) { try { CoinmarketcapData data = OtherData.getCoinmarketcapTo( "usd", curName); if (data.change7h.indexOf("-") == -1 && data.change1h.indexOf("-") == -1) { result = Trend.UP; } else { result = Trend.DOWN; } } catch (Exception ex) { addStorage(new Store(curName, Trend.UNKOWN)); } } } return result == null ? Trend.UNKOWN : result; } public static class Error { public int code; public String message; public Error(String mes) { this.message = mes; } public Error() { this("Empty"); } } public static class Task { int id; public TraderProcess process; public RippleSeedAddress seed; public String target_issuer = "unkown"; public String target_currency = "unkown"; public String source_currency = "unkown"; public String source_issuer = "unkown"; public double value = -1; public double real_max_value = -1; public double limit_volume = -1; public double minDifference = 0.1; public int orderId = -1; public double orderAmount = -1; public Model model = Model.Spreads; public ArrayList<Swap> swaps = new ArrayList<Swap>(10); public ArrayList<Error> errors = new ArrayList<Error>(10); public LTimer task_delay = new LTimer(LSystem.SECOND); public boolean stop; private long startTimeStamp = -1; public Task() { startTimeStamp = System.currentTimeMillis(); } public long getStartTimeStamp() { return startTimeStamp; } public void update(LTimerContext context) { if (task_delay.action(context)) { if (seed == null) { return; } if (id <= 0) { return; } if (target_currency.equalsIgnoreCase(source_currency)) { return; } if (model == null) { errors.add(new Error()); return; } if (!LSystem.nativeCurrency.equalsIgnoreCase(source_currency) && !LSystem.nativeCurrency .equalsIgnoreCase(target_currency) && !target_issuer.equalsIgnoreCase(source_issuer)) { return; } if (source_issuer == null || "unkown".equalsIgnoreCase(source_issuer)) { return; } if (target_issuer == null || "unkown".equalsIgnoreCase(target_issuer)) { return; } if (stop) { return; } // get limit trader price final double volumeWall = suggestWallVolume(real_max_value, limit_volume); // get average price String averagePrice = OfferPrice.getMoneyConvert("1", source_currency, target_currency); if (averagePrice == null || "unkown".equalsIgnoreCase(averagePrice)) { averagePrice = "-1"; } final double otherPrice = Double.parseDouble(averagePrice); // load exchange data OfferPrice.load(source_issuer, source_currency, target_currency, new OfferPrice() { @Override public void sell(Offer offer) { } @Override public void error(JSONObject obj) { errors.add(new Error(obj.toString())); } @Override public void empty() { errors.add(new Error()); } @Override public void complete(ArrayList<OfferFruit> buys, ArrayList<OfferFruit> sells, OfferPrice price) { // accurate to five decimal places String highBuy = null; if (price.highBuy != null) { if (price.highBuy.indexOf("/") != -1) { highBuy = price.highBuy.split("/")[0]; } highBuy = LSystem.getNumberShort(highBuy); } String hightSell = null; if (price.hightSell != null) { if (price.hightSell.indexOf("/") != -1) { hightSell = price.hightSell.split("/")[0]; } hightSell = LSystem .getNumberShort(hightSell); } log("other:" + otherPrice); log("buy:" + highBuy); log("sell:" + hightSell); // load data completed callCore(volumeWall, otherPrice, Task.this, buys, sells, price, Double.parseDouble(highBuy), Double.parseDouble(hightSell)); } @Override public void buy(Offer offer) { } }, false); } } } private static void callCore(double volumeWall, double otherPrice, Task task, ArrayList<OfferFruit> buys, ArrayList<OfferFruit> sells, OfferPrice price, double highBuy, double hightSell) { double avg_buy_value = task.process.averageBuyPrice(buys); double avg_sell_value = task.process.averageSellPrice(sells); double buy_difference = highBuy - avg_buy_value; double sell_difference = hightSell - avg_buy_value; double all_buy_difference = 0; if (otherPrice != -1) { all_buy_difference = otherPrice - avg_buy_value; } else { all_buy_difference = buy_difference; } double all_sell_difference = 0; if (otherPrice != -1) { all_sell_difference = otherPrice - avg_sell_value; } else { all_sell_difference = sell_difference; } System.out.println(all_buy_difference); System.out.println(all_sell_difference); switch (task.model) { case CrazyBuyer: log("" + avg_buy_value); log("" + avg_sell_value); callBuy(0, 0, task); break; case CrazySeller: callSell(0, 0, task); break; case Spreads: break; case Script: break; default: break; } } public void setAnalyzeLimit(int l) { this.analyze_limit = l; } public int getAnalyzeLimit() { return this.analyze_limit; } private double averageBuyPrice(ArrayList<OfferFruit> bids) { double sumVolume = 0.0d; List<OfferFruit> tmp = null; if (bids.size() > analyze_limit) { tmp = bids.subList(0, analyze_limit); } else { tmp = bids; } int size = tmp.size(); for (OfferFruit bid : tmp) { double sellValue = Double.parseDouble(LSystem.getNumber( bid.offer.bidQuality(), false)); sumVolume += sellValue; } return sumVolume / size; } private double averageSellPrice(ArrayList<OfferFruit> asks) { double sumVolume = 0.0d; List<OfferFruit> tmp = null; if (asks.size() > analyze_limit) { tmp = asks.subList(0, analyze_limit); } else { tmp = asks; } int size = tmp.size(); for (OfferFruit ask : tmp) { double sellValue = Double.parseDouble(LSystem.getNumber( ask.offer.askQuality(), false)); sumVolume += sellValue; } return sumVolume / size; } private static void log(String mes) { System.out.println(mes); } static void callBuy(double srcValue, double dstValue, Task task) { log("testing..."); } static void callSell(double srcValue, double dstValue, Task task) { log("testing..."); } public boolean isRunning() { return _isRunning; } public boolean isPause() { return _isPause; } public boolean isResume() { return _isResume; } public boolean isDestroy() { return _isDestroy; } public void setFPS(long frames) { this._maxFrames = frames; } public ArrayList<Task> getAllSeller() { ArrayList<Task> tasks = new ArrayList<Task>(10); for (Task t : _HFT_tasks) { if (t.model.equals(Model.CrazySeller)) { tasks.add(t); } } return tasks; } public ArrayList<Task> getAllBuyer() { ArrayList<Task> tasks = new ArrayList<Task>(10); for (Task t : _HFT_tasks) { if (t.model.equals(Model.CrazyBuyer)) { tasks.add(t); } } return tasks; } public ArrayList<Task> getUserSpreads() { ArrayList<Task> tasks = new ArrayList<Task>(10); for (Task t : _HFT_tasks) { if (t.model.equals(Model.Spreads)) { tasks.add(t); } } return tasks; } public ArrayList<Task> getUserScript() { ArrayList<Task> tasks = new ArrayList<Task>(10); for (Task t : _HFT_tasks) { if (t.model.equals(Model.Script)) { tasks.add(t); } } return tasks; } private Updateable main() { Updateable updateable = new Updateable() { @Override public void action(Object o) { for (; _isRunning;) { _goalTimeMicros = _lastTimeMicros + 1000000L / _maxFrames; _currTimeMicros = _timer.sleepTimeMicros(_goalTimeMicros); _elapsedTimeMicros = _currTimeMicros - _lastTimeMicros + _remainderMicros; _elapsedTime = MathUtils .max(0, (_elapsedTimeMicros / 1000)); _remainderMicros = _elapsedTimeMicros - _elapsedTime * 1000; _lastTimeMicros = _currTimeMicros; _timerContext.millisSleepTime = _remainderMicros; _timerContext.timeSinceLastUpdate = _elapsedTime; runTaskTimer(_timerContext); if (_isPause) { pause(500); } } } }; return updateable; } public void loop() { _isRunning = true; if (_timer == null) { _timer = new SystemTimer(); } if (_mainLoop == null) { _mainLoop = new Thread() { public void run() { main().action(this); } }; _mainLoop.start(); } } private void runTaskTimer(LTimerContext context) { int size = _HFT_tasks.size(); for (int i = 0; i < size; i++) { Task task = _HFT_tasks.get(i); task.update(context); } } private final void pause(long sleep) { try { Thread.sleep(sleep); } catch (InterruptedException ex) { } } final void resume() { synchronized (_synch) { if (_isRunning || _mainLoop != null) { _isRunning = false; if (_mainLoop != null) { _mainLoop.interrupt(); _mainLoop = null; } } _isRunning = true; _isResume = true; loop(); } } final void pause() { synchronized (_synch) { if (!_isRunning) { return; } _isRunning = false; _isPause = true; while (_isPause) { try { _synch.wait(4000); } catch (InterruptedException ignored) { } } } } final void destroy() { synchronized (_synch) { _isRunning = false; _isDestroy = true; while (_isDestroy) { try { _synch.wait(); } catch (InterruptedException ex) { } } } } private final void callTask(Task task) { task.id += 1; _HFT_tasks.add(task); } public void execute(final Task task) { if (task.seed == null) { return; } task.process = this; String address = task.seed.getPublicKey(); AccountFind find = new AccountFind(); final AccountInfo info = new AccountInfo(); if (LSystem.nativeCurrency.equalsIgnoreCase(task.source_currency)) { find.processInfo(address, info, new Updateable() { @Override public void action(Object o) { String balance = info.balance; double srcXrpValue = Double.parseDouble(LSystem .getNumberShort(balance)); task.real_max_value = srcXrpValue; callTask(task); } }); } else { find.processLines(address, info, new Updateable() { @Override public void action(Object o) { ArrayList<AccountLine> lines = info.lines; if (lines.size() > 0) { for (AccountLine line : lines) { if (task.source_currency.equalsIgnoreCase(line .getCurrency()) && task.equals(line.getIssuer())) { double srcIouValue = Double.parseDouble(line .getAmount()); task.real_max_value = srcIouValue; } } } callTask(task); } }); } } }
update update
eclipse/src/org/ripple/power/hft/TraderProcess.java
update
<ide><path>clipse/src/org/ripple/power/hft/TraderProcess.java <ide> } else { <ide> all_sell_difference = sell_difference; <ide> } <add> Trend trend = task.process.getTrend(task.source_currency, 18); <ide> <ide> System.out.println(all_buy_difference); <ide> System.out.println(all_sell_difference);
Java
mit
5909d41004e6f34c46858daa9440c95d13332c71
0
code-disaster/steamworks4j,code-disaster/steamworks4j,code-disaster/steamworks4j,AlrikG/steamworks4j,AlrikG/steamworks4j,AlrikG/steamworks4j,AlrikG/steamworks4j,code-disaster/steamworks4j
package com.codedisaster.steamworks; import java.io.*; import java.util.UUID; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; class SteamSharedLibraryLoader { private final String libraryPath; private final boolean fromJar; private String libraryCrc; private static boolean alreadyLoaded = false; private SteamSharedLibraryLoader(String libraryPath, boolean fromJar) { this.libraryPath = libraryPath; this.fromJar = fromJar; if (libraryPath != null && fromJar) { try { libraryCrc = crc(new FileInputStream(new File(libraryPath))); } catch (FileNotFoundException e) { libraryCrc = Integer.toHexString(libraryPath.hashCode()); } } } private String getLibNameWindows(String sharedLibName, boolean is64Bit) { return sharedLibName + (is64Bit ? "64" : "") + ".dll"; } private String getLibNameLinux(String sharedLibName, boolean is64Bit) { return "lib" + sharedLibName + (is64Bit ? "64" : "") + ".so"; } private String getLibNameMac(String sharedLibName) { return "lib" + sharedLibName + ".dylib"; } private void loadLibraries(String... libraryNames) throws IOException { String osName = System.getProperty("os.name"); String osArch = System.getProperty("os.arch"); boolean isWindows = osName.contains("Windows"); boolean isLinux = osName.contains("Linux"); boolean isMac = osName.contains("Mac"); boolean is64Bit = osArch.equals("amd64") || osArch.equals("x86_64"); File extractLocation = discoverExtractLocation( "steamworks4j/" + libraryCrc, UUID.randomUUID().toString()); if (extractLocation != null) { extractLocation = extractLocation.getParentFile(); } else { throw new IOException(); } for (String libraryName : libraryNames) { String librarySystemName = ""; if (isWindows) { librarySystemName = getLibNameWindows(libraryName, is64Bit); } else if (isLinux) { librarySystemName = getLibNameLinux(libraryName, is64Bit); } else if (isMac) { librarySystemName = getLibNameMac(libraryName); } String fullPath; if (fromJar) { // extract library from Jar into temp folder fullPath = extractLibrary(extractLocation, librarySystemName); } else { // load native library directly from specified path fullPath = libraryPath + "/" + librarySystemName; } String absolutePath = new File(fullPath).getCanonicalPath(); System.load(absolutePath); } } private String extractLibrary(File nativesPath, String sharedLibName) throws IOException { File nativeFile = new File(nativesPath, sharedLibName); ZipFile zip = new ZipFile(libraryPath); ZipEntry entry = zip.getEntry(sharedLibName); InputStream input = zip.getInputStream(entry); if (input == null) { throw new IOException("Error extracting " + sharedLibName + " from " + libraryPath); } FileOutputStream output = new FileOutputStream(nativeFile); byte[] buffer = new byte[4096]; while (true) { int length = input.read(buffer); if (length == -1) break; output.write(buffer, 0, length); } output.close(); zip.close(); return nativeFile.getAbsolutePath(); } private String crc(InputStream input) { CRC32 crc = new CRC32(); byte[] buffer = new byte[4096]; try { while (true) { int length = input.read(buffer); if (length == -1) break; crc.update(buffer, 0, length); } } catch (IOException e) { e.printStackTrace(); } finally { try { input.close(); } catch (IOException ignored) { } } return Long.toHexString(crc.getValue()); } static boolean extractAndLoadLibraries(boolean fromJar, String libraryPath) { if (alreadyLoaded) { return true; } SteamSharedLibraryLoader loader; if (fromJar) { if (libraryPath == null) { // if no library path is specified, extract steamworks4j-natives.jar from // resource path into temporary folder File extractLocation = discoverExtractLocation("steamworks4j", "steamworks4j-natives.jar"); if (extractLocation == null) { return false; } libraryPath = extractLocation.getPath(); try { InputStream input = SteamSharedLibraryLoader.class.getResourceAsStream("/steamworks4j-natives.jar"); if (input == null) { return false; } FileOutputStream output = new FileOutputStream(extractLocation); byte[] cache = new byte[4096]; int length; do { length = input.read(cache); if (length > 0) { output.write(cache, 0, length); } } while (length > 0); input.close(); output.close(); } catch (IOException e) { e.printStackTrace(); return false; } } } loader = new SteamSharedLibraryLoader(libraryPath, fromJar); try { loader.loadLibraries("steam_api", "steamworks4j"); } catch (IOException e) { e.printStackTrace(); return false; } alreadyLoaded = true; return true; } private static File discoverExtractLocation(String folderName, String fileName) { // Java tmpdir File path = new File(System.getProperty("java.io.tmpdir") + "/" + folderName, fileName); if (canWrite(path)) { return path; } // NIO temp file try { File file = File.createTempFile(folderName, null); if (file.delete()) { // uses temp file path as destination folder path = new File(file, fileName); if (canWrite(path)) { return path; } } } catch (IOException ignored) { } // $home path = new File(System.getProperty("user.home") + "/." + folderName, fileName); if (canWrite(path)) { return path; } // working directory path = new File(".tmp/" + folderName, fileName); if (canWrite(path)) { return path; } return null; } private static boolean canWrite(File file) { File folder = file.getParentFile(); if (file.exists()) { if (!file.canWrite() || !canExecute(file)) { return false; } } else { if (!folder.exists()) { if (!folder.mkdirs()) { return false; } } if (!folder.isDirectory()) { return false; } } File testFile = new File(folder, UUID.randomUUID().toString()); try { new FileOutputStream(testFile).close(); return canExecute(testFile); } catch (IOException e) { return false; } finally { testFile.delete(); } } private static boolean canExecute(File file) { try { if (file.canExecute()) { return true; } if (file.setExecutable(true)) { return file.canExecute(); } } catch (Exception ignored) { } return false; } }
java-wrapper/src/main/java/com/codedisaster/steamworks/SteamSharedLibraryLoader.java
package com.codedisaster.steamworks; import java.io.*; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; class SteamSharedLibraryLoader { private final String libraryPath; private final boolean fromJar; private String libraryCrc; private static boolean alreadyLoaded = false; private SteamSharedLibraryLoader(String libraryPath, boolean fromJar) { this.libraryPath = libraryPath; this.fromJar = fromJar; if (libraryPath != null && fromJar) { try { libraryCrc = crc(new FileInputStream(new File(libraryPath))); } catch (FileNotFoundException e) { libraryCrc = Integer.toHexString(libraryPath.hashCode()); } } } private String getLibNameWindows(String sharedLibName, boolean is64Bit) { return sharedLibName + (is64Bit ? "64" : "") + ".dll"; } private String getLibNameLinux(String sharedLibName, boolean is64Bit) { return "lib" + sharedLibName + (is64Bit ? "64" : "") + ".so"; } private String getLibNameMac(String sharedLibName) { return "lib" + sharedLibName + ".dylib"; } private void loadLibraries(String... libraryNames) throws IOException { String osName = System.getProperty("os.name"); String osArch = System.getProperty("os.arch"); boolean isWindows = osName.contains("Windows"); boolean isLinux = osName.contains("Linux"); boolean isMac = osName.contains("Mac"); boolean is64Bit = osArch.equals("amd64") || osArch.equals("x86_64"); for (String libraryName : libraryNames) { String librarySystemName = ""; if (isWindows) { librarySystemName = getLibNameWindows(libraryName, is64Bit); } if (isLinux) { librarySystemName = getLibNameLinux(libraryName, is64Bit); } if (isMac) { librarySystemName = getLibNameMac(libraryName); } String fullPath; if (fromJar) { // extract library from Jar into temp folder fullPath = extractLibrary(librarySystemName); } else { // load native library directly from specified path fullPath = libraryPath + "/" + librarySystemName; } String absolutePath = new File(fullPath).getCanonicalPath(); System.load(absolutePath); } } private String extractLibrary(String sharedLibName) throws IOException { File nativesPath = new File(System.getProperty("java.io.tmpdir") + "/steamworks4j/" + libraryCrc); File nativeFile = new File(nativesPath, sharedLibName); if (!nativesPath.exists()) { if (!nativesPath.mkdirs()) { throw new IOException("Error creating temp folder: " + nativesPath.getCanonicalPath()); } } ZipFile zip = new ZipFile(libraryPath); ZipEntry entry = zip.getEntry(sharedLibName); InputStream input = zip.getInputStream(entry); if (input == null) { throw new IOException("Error extracting " + sharedLibName + " from " + libraryPath); } FileOutputStream output = new FileOutputStream(nativeFile); byte[] buffer = new byte[4096]; while (true) { int length = input.read(buffer); if (length == -1) break; output.write(buffer, 0, length); } output.close(); zip.close(); return nativeFile.getAbsolutePath(); } private String crc(InputStream input) { CRC32 crc = new CRC32(); byte[] buffer = new byte[4096]; try { while (true) { int length = input.read(buffer); if (length == -1) break; crc.update(buffer, 0, length); } } catch (IOException e) { e.printStackTrace(); } finally { try { input.close(); } catch (IOException ignored) { } } return Long.toHexString(crc.getValue()); } static boolean extractAndLoadLibraries(boolean fromJar, String libraryPath) { if (alreadyLoaded) { return true; } SteamSharedLibraryLoader loader; if (fromJar) { if (libraryPath == null) { // if no library path is specified, extract steamworks4j-natives.jar from // resource path into temporary folder libraryPath = System.getProperty("java.io.tmpdir") + "/steamworks4j/steamworks4j-natives.jar"; File libraryDirectory = new File(libraryPath).getParentFile(); if (!libraryDirectory.exists()) { if (!libraryDirectory.mkdirs()) { return false; } } try { InputStream input = SteamSharedLibraryLoader.class.getResourceAsStream("/steamworks4j-natives.jar"); FileOutputStream output = new FileOutputStream(new File(libraryPath)); byte[] cache = new byte[4096]; int length; do { length = input.read(cache); if (length > 0) { output.write(cache, 0, length); } } while (length > 0); input.close(); output.close(); } catch (IOException e) { e.printStackTrace(); return false; } } } loader = new SteamSharedLibraryLoader(libraryPath, fromJar); try { loader.loadLibraries("steam_api", "steamworks4j"); } catch (IOException e) { e.printStackTrace(); return false; } alreadyLoaded = true; return true; } }
Added error checks and fallback locations for extracting native libraries.
java-wrapper/src/main/java/com/codedisaster/steamworks/SteamSharedLibraryLoader.java
Added error checks and fallback locations for extracting native libraries.
<ide><path>ava-wrapper/src/main/java/com/codedisaster/steamworks/SteamSharedLibraryLoader.java <ide> package com.codedisaster.steamworks; <ide> <ide> import java.io.*; <add>import java.util.UUID; <ide> import java.util.zip.CRC32; <ide> import java.util.zip.ZipEntry; <ide> import java.util.zip.ZipFile; <ide> <ide> boolean is64Bit = osArch.equals("amd64") || osArch.equals("x86_64"); <ide> <add> File extractLocation = discoverExtractLocation( <add> "steamworks4j/" + libraryCrc, UUID.randomUUID().toString()); <add> <add> if (extractLocation != null) { <add> extractLocation = extractLocation.getParentFile(); <add> } else { <add> throw new IOException(); <add> } <add> <ide> for (String libraryName : libraryNames) { <ide> <ide> String librarySystemName = ""; <ide> <ide> if (isWindows) { <ide> librarySystemName = getLibNameWindows(libraryName, is64Bit); <del> } <del> if (isLinux) { <add> } else if (isLinux) { <ide> librarySystemName = getLibNameLinux(libraryName, is64Bit); <del> } <del> if (isMac) { <add> } else if (isMac) { <ide> librarySystemName = getLibNameMac(libraryName); <ide> } <ide> <ide> <ide> if (fromJar) { <ide> // extract library from Jar into temp folder <del> fullPath = extractLibrary(librarySystemName); <add> fullPath = extractLibrary(extractLocation, librarySystemName); <ide> } else { <ide> // load native library directly from specified path <ide> fullPath = libraryPath + "/" + librarySystemName; <ide> } <ide> } <ide> <del> private String extractLibrary(String sharedLibName) throws IOException { <del> <del> File nativesPath = new File(System.getProperty("java.io.tmpdir") + "/steamworks4j/" + libraryCrc); <add> private String extractLibrary(File nativesPath, String sharedLibName) throws IOException { <add> <ide> File nativeFile = new File(nativesPath, sharedLibName); <del> <del> if (!nativesPath.exists()) { <del> if (!nativesPath.mkdirs()) { <del> throw new IOException("Error creating temp folder: " + nativesPath.getCanonicalPath()); <del> } <del> } <ide> <ide> ZipFile zip = new ZipFile(libraryPath); <ide> ZipEntry entry = zip.getEntry(sharedLibName); <ide> // if no library path is specified, extract steamworks4j-natives.jar from <ide> // resource path into temporary folder <ide> <del> libraryPath = System.getProperty("java.io.tmpdir") + "/steamworks4j/steamworks4j-natives.jar"; <del> <del> File libraryDirectory = new File(libraryPath).getParentFile(); <del> if (!libraryDirectory.exists()) { <del> if (!libraryDirectory.mkdirs()) { <add> File extractLocation = discoverExtractLocation("steamworks4j", "steamworks4j-natives.jar"); <add> if (extractLocation == null) { <add> return false; <add> } <add> <add> libraryPath = extractLocation.getPath(); <add> <add> try { <add> <add> InputStream input = SteamSharedLibraryLoader.class.getResourceAsStream("/steamworks4j-natives.jar"); <add> if (input == null) { <ide> return false; <ide> } <del> } <del> <del> try { <del> <del> InputStream input = SteamSharedLibraryLoader.class.getResourceAsStream("/steamworks4j-natives.jar"); <del> FileOutputStream output = new FileOutputStream(new File(libraryPath)); <add> <add> FileOutputStream output = new FileOutputStream(extractLocation); <ide> <ide> byte[] cache = new byte[4096]; <ide> int length; <ide> alreadyLoaded = true; <ide> return true; <ide> } <add> <add> private static File discoverExtractLocation(String folderName, String fileName) { <add> <add> // Java tmpdir <add> <add> File path = new File(System.getProperty("java.io.tmpdir") + "/" + folderName, fileName); <add> if (canWrite(path)) { <add> return path; <add> } <add> <add> // NIO temp file <add> <add> try { <add> File file = File.createTempFile(folderName, null); <add> if (file.delete()) { <add> // uses temp file path as destination folder <add> path = new File(file, fileName); <add> if (canWrite(path)) { <add> return path; <add> } <add> } <add> } catch (IOException ignored) { <add> <add> } <add> <add> // $home <add> <add> path = new File(System.getProperty("user.home") + "/." + folderName, fileName); <add> if (canWrite(path)) { <add> return path; <add> } <add> <add> // working directory <add> <add> path = new File(".tmp/" + folderName, fileName); <add> if (canWrite(path)) { <add> return path; <add> } <add> <add> return null; <add> } <add> <add> private static boolean canWrite(File file) { <add> <add> File folder = file.getParentFile(); <add> <add> if (file.exists()) { <add> if (!file.canWrite() || !canExecute(file)) { <add> return false; <add> } <add> } else { <add> if (!folder.exists()) { <add> if (!folder.mkdirs()) { <add> return false; <add> } <add> } <add> if (!folder.isDirectory()) { <add> return false; <add> } <add> } <add> <add> File testFile = new File(folder, UUID.randomUUID().toString()); <add> <add> try { <add> new FileOutputStream(testFile).close(); <add> return canExecute(testFile); <add> } catch (IOException e) { <add> return false; <add> } finally { <add> testFile.delete(); <add> } <add> } <add> <add> private static boolean canExecute(File file) { <add> <add> try { <add> if (file.canExecute()) { <add> return true; <add> } <add> <add> if (file.setExecutable(true)) { <add> return file.canExecute(); <add> } <add> } catch (Exception ignored) { <add> <add> } <add> <add> return false; <add> } <add> <ide> }
Java
apache-2.0
4c7fbb68ebfc3d3bcda2a6f5351b602a5a16dc5c
0
wyona/yanel,baszero/yanel,wyona/yanel,baszero/yanel,baszero/yanel,wyona/yanel,wyona/yanel,baszero/yanel,baszero/yanel,baszero/yanel,wyona/yanel,wyona/yanel
/* * Copyright 2006 Wyona * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.wyona.org/licenses/APACHE-LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wyona.yanel.impl.resources.node; import org.wyona.yanel.core.Path; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.ResourceConfiguration; import org.wyona.yanel.core.Topic; import org.wyona.yanel.core.api.attributes.CreatableV2; import org.wyona.yanel.core.api.attributes.IntrospectableV1; import org.wyona.yanel.core.api.attributes.ModifiableV2; import org.wyona.yanel.core.api.attributes.VersionableV2; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.api.attributes.WorkflowableV1; import org.wyona.yanel.core.attributes.versionable.RevisionInformation; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.attributes.viewable.ViewDescriptor; import org.wyona.yanel.core.util.PathUtil; import org.wyona.yanel.core.workflow.WorkflowException; import org.wyona.yanel.core.workflow.WorkflowHelper; import org.wyona.yanel.servlet.communication.HttpRequest; import org.wyona.yarep.core.Node; import org.wyona.yarep.core.Repository; import org.wyona.yarep.core.RepositoryFactory; import org.wyona.yarep.core.Revision; import org.wyona.yarep.util.RepoPath; import javax.servlet.http.HttpServletRequest; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.util.Date; import java.util.Enumeration; import org.apache.log4j.Category; import org.apache.commons.fileupload.util.Streams; /** * Generic Node Resource */ public class NodeResource extends Resource implements ViewableV2, ModifiableV2, VersionableV2, IntrospectableV1, WorkflowableV1, CreatableV2 { //public class NodeResource extends Resource implements ViewableV2, ModifiableV2, VersionableV2, CreatableV2 { private static Category log = Category.getInstance(NodeResource.class); private String uploadMimeType; /** * */ public NodeResource() { } /** * */ public ViewDescriptor[] getViewDescriptors() { return null; } public View getView(String viewId, String revisionName) throws Exception { View view = new View(); view.setInputStream(getRealm().getRepository().getNode(getPath()).getRevision(revisionName).getInputStream()); view.setMimeType(getMimeType(viewId)); view.setEncoding(getResourceConfigProperty("encoding")); return view; } /** * */ public View getView(String viewId) throws Exception { View view = new View(); view.setInputStream(getRealm().getRepository().getNode(getPath()).getInputStream()); view.setMimeType(getMimeType(viewId)); view.setEncoding(getResourceConfigProperty("encoding")); return view; } /** * */ public String getMimeType(String viewId) throws Exception { String mimeType = getResourceConfigProperty("mime-type"); if (mimeType != null) return mimeType; // TODO: Load config mime.types ... String suffix = PathUtil.getSuffix(getPath()); if (suffix != null) { log.debug("SUFFIX: " + suffix); mimeType = getMimeTypeBySuffix(suffix); } else { log.warn("mime-type will be set to application/octet-stream, because no suffix for " + getPath()); mimeType = "application/octet-stream"; } return mimeType; } /** * */ public Reader getReader() throws Exception { return new InputStreamReader(getInputStream(), "UTF-8"); } /** * */ public InputStream getInputStream() throws Exception { return getRealm().getRepository().getNode(getPath()).getInputStream(); } /** * */ public Writer getWriter() throws Exception { log.error("Not implemented yet!"); return null; } /** * */ public OutputStream getOutputStream() throws Exception { if (!getRealm().getRepository().existsNode(getPath())) { // TODO: create node recursively ... getRealm().getRepository().getNode(new org.wyona.commons.io.Path(getPath()).getParent().toString()).addNode(new org.wyona.commons.io.Path(getPath()).getName().toString(), org.wyona.yarep.core.NodeType.RESOURCE); } return getRealm().getRepository().getNode(getPath()).getOutputStream(); } /** * */ public void write(InputStream in) throws Exception { log.warn("Not implemented yet!"); } /** * */ public long getLastModified() throws Exception { Node node = getRealm().getRepository().getNode(getPath()); long lastModified; if (node.isResource()) { lastModified = node.getLastModified(); } else { lastModified = 0; } return lastModified; } /** * Delete data of node resource */ public boolean delete() throws Exception { getRealm().getRepository().getNode(getPath()).delete(); return true; } /** * @see org.wyona.yanel.core.api.attributes.VersionableV2#getRevisions() */ public RevisionInformation[] getRevisions() throws Exception { Revision[] revisions = getRealm().getRepository().getNode(getPath()).getRevisions(); RevisionInformation[] revisionInfos = new RevisionInformation[revisions.length]; for (int i = 0; i < revisions.length; i++) { revisionInfos[i] = new RevisionInformation(revisions[i]); } if (revisions.length > 0) { log.warn("Node \"" + getPath() + "\" does not seem to have any revisions! The repository \"" + getRealm().getRepository() + "\" might not support revisions!"); } return revisionInfos; } public void checkin(String comment) throws Exception { Node node = getRealm().getRepository().getNode(getPath()); node.checkin(comment); /* if (node.isCheckedOut()) { String checkoutUserID = node.getCheckoutUserID(); if (checkoutUserID.equals(userID)) { node.checkin(); } else { throw new Exception("Resource is checked out by another user: " + checkoutUserID); } } else { throw new Exception("Resource is not checked out."); } */ } public void checkout(String userID) throws Exception { Node node = getRealm().getRepository().getNode(getPath()); node.checkout(userID); /* if (node.isCheckedOut()) { String checkoutUserID = node.getCheckoutUserID(); if (checkoutUserID.equals(userID)) { log.warn("Resource " + getPath() + " is already checked out by this user: " + checkoutUserID); } else { throw new Exception("Resource is already checked out by another user: " + checkoutUserID); } } else { node.checkout(userID); } */ } public void cancelCheckout() throws Exception { Node node = getRealm().getRepository().getNode(getPath()); node.cancelCheckout(); } public void restore(String revisionName) throws Exception { getRealm().getRepository().getNode(getPath()).restore(revisionName); } public Date getCheckoutDate() throws Exception { Node node = getRealm().getRepository().getNode(getPath()); // return node.getCheckoutDate(); return null; } public String getCheckoutUserID() throws Exception { Node node = getRealm().getRepository().getNode(getPath()); return node.getCheckoutUserID(); } public boolean isCheckedOut() throws Exception { Node node = getRealm().getRepository().getNode(getPath()); return node.isCheckedOut(); } public boolean exists() throws Exception { return getRealm().getRepository().existsNode(getPath()); } /** * */ public long getSize() throws Exception { Node node = getRealm().getRepository().getNode(getPath()); long size; if (node.isResource()) { size = node.getSize(); } else { size = 0; } return size; } /** * */ public Object getProperty(String name) { log.warn("No implemented yet!"); return null; } /** * */ public String[] getPropertyNames() { String[] props = {"data"}; return props; } /** * */ public void setProperty(String name, Object value) { log.warn("No implemented yet!"); } /** * */ public void create(HttpServletRequest request) { try { Repository repo = getRealm().getRepository(); if (request instanceof HttpRequest) { HttpRequest yanelRequest = (HttpRequest)request; if (yanelRequest.isMultipartRequest()) { Enumeration parameters = yanelRequest.getFileNames(); if (parameters.hasMoreElements()) { String name = (String) parameters.nextElement(); Node newNode = org.wyona.yanel.core.util.YarepUtil.addNodes(repo, getPath().toString(), org.wyona.yarep.core.NodeType.RESOURCE); OutputStream output = newNode.getOutputStream(); InputStream is = yanelRequest.getInputStream(name); Streams.copy(is, output, true); uploadMimeType = yanelRequest.getContentType(name); newNode.setMimeType(uploadMimeType); } } else { log.error("this is NOT a multipart request"); } } else { log.error("this is NOT a HttpRequest"); } // TODO: Introspection should not be hardcoded! /* String name = new org.wyona.commons.io.Path(getPath()).getName(); String parent = new org.wyona.commons.io.Path(getPath()).getParent().toString(); String nameWithoutSuffix = name; int lastIndex = name.lastIndexOf("."); if (lastIndex > 0) nameWithoutSuffix = name.substring(0, lastIndex); String introspectionPath = parent + "/introspection-" + nameWithoutSuffix + ".xml"; org.wyona.yanel.core.util.YarepUtil.addNodes(repo, introspectionPath, org.wyona.yarep.core.NodeType.RESOURCE); writer = new java.io.OutputStreamWriter(repo.getNode(introspectionPath).getOutputStream()); writer.write(getIntrospection(name)); writer.close();*/ } catch (Exception e) { log.error(e.getMessage(), e); } } /** * */ public java.util.HashMap createRTIProperties(HttpServletRequest request) { java.util.HashMap map = new java.util.HashMap(); String mimeType = request.getParameter("rp.mime-type"); if (mimeType == null) { mimeType = this.uploadMimeType; } map.put("mime-type", mimeType); map.put("encoding", request.getParameter("rp.encoding")); return map; } /** * Use suggested name if not null or empty, otherwise use name of uploaded file */ public String getCreateName(String suggestedName) { if (suggestedName != null && !suggestedName.equals("")) return suggestedName; if (request instanceof HttpRequest) { HttpRequest yanelRequest = (HttpRequest)request; if (yanelRequest.isMultipartRequest()) { Enumeration parameters = yanelRequest.getFileNames(); if (parameters.hasMoreElements()) { return fixAssetName(yanelRequest.getFilesystemName((String) parameters.nextElement())); } } else { log.error("this is NOT a multipart request"); } } else { log.error("this is NOT a HttpRequest"); } return null; } /** * */ public String getPropertyType(String name) { return CreatableV2.TYPE_UPLOAD; } /** * Get introspection document */ public String getIntrospection() throws Exception { String name = PathUtil.getName(getPath()); StringBuffer buf = new StringBuffer(); buf.append("<?xml version=\"1.0\"?>"); buf.append("<introspection xmlns=\"http://www.wyona.org/neutron/2.0\">"); buf.append("<navigation>"); buf.append(" <sitetree href=\"./\" method=\"PROPFIND\"/>"); buf.append("</navigation>"); buf.append("<resource name=\"" + name + "\">"); buf.append("<edit mime-type=\"" + this.getMimeType(null) + "\">"); buf.append("<checkout url=\"?yanel.resource.usecase=checkout\" method=\"GET\"/>"); buf.append("<checkin url=\"?yanel.resource.usecase=checkin\" method=\"PUT\"/>"); buf.append("<release-lock url=\"?yanel.resource.usecase=release-lock\" method=\"GET\"/>"); buf.append("</edit>"); buf.append(getWorkflowIntrospection()); buf.append("</resource>"); buf.append("</introspection>"); return buf.toString(); } /** * */ public String getMimeTypeBySuffix(String suffix) { // TODO: use MimeTypeUtil if (suffix.equals("html")) { return "text/html"; } else if (suffix.equals("htm")) { return "text/html"; } else if (suffix.equals("xhtml")) { return "application/xhtml+xml"; } else if (suffix.equals("xml")) { return "application/xml"; } else if (suffix.equals("css")) { return "text/css"; } else if (suffix.equals("js")) { return "application/x-javascript"; } else if (suffix.equals("png")) { return "image/png"; } else if (suffix.equals("jpg")) { return "image/jpeg"; } else if (suffix.equals("gif")) { return "image/gif"; } else if (suffix.equals("pdf")) { return "application/pdf"; } else if (suffix.equals("doc")) { return "application/msword"; } else if (suffix.equals("odt")) { return "application/vnd.oasis.opendocument.text"; } else if (suffix.equals("sxc")) { return "application/vnd.sun.xml.calc"; } else if (suffix.equals("xpi")) { return "application/x-xpinstall"; } else if (suffix.equals("zip")) { return "application/zip"; } else if (suffix.equals("jar")) { // http://en.wikipedia.org/wiki/Jar_(file_format) return "application/java-archive"; } else if (suffix.equals("war")) { return "application/java-archive"; } else if (suffix.equals("flv")) { return "video/x-flv"; } else if (suffix.equals("swf")) { return "application/x-shockwave-flash"; } else if (suffix.equals("txt")) { return "text/plain"; } else if (suffix.equals("mov")) { return "video/quicktime"; } else if (suffix.equals("svg")) { return "image/svg+xml"; } else if (suffix.equals("ico")) { return "image/x-icon"; } else { log.warn("Could not determine mime-type from suffix (suffix: " + suffix + ")!"); return "application/octet-stream"; } } /** * */ public String getWorkflowIntrospection() throws WorkflowException { return WorkflowHelper.getWorkflowIntrospection(this); } /** * */ public void removeWorkflowVariable(String name) throws WorkflowException { WorkflowHelper.removeWorkflowVariable(this, name); } /** * */ public void setWorkflowVariable(String name, String value) throws WorkflowException { WorkflowHelper.setWorkflowVariable(this, name, value); } /** * */ public String getWorkflowVariable(String name) throws WorkflowException { return WorkflowHelper.getWorkflowVariable(this, name); } /** * */ public Date getWorkflowDate(String revision) throws WorkflowException { return WorkflowHelper.getWorkflowDate(this, revision); } /** * */ public void setWorkflowState(String state, String revision) throws WorkflowException { WorkflowHelper.setWorkflowState(this, state, revision); } /** * */ public String getWorkflowState(String revision) throws WorkflowException { return WorkflowHelper.getWorkflowState(this, revision); } /** * */ public View getLiveView(String viewid) throws Exception { return WorkflowHelper.getLiveView(this, viewid); } /** * */ public boolean isLive() throws WorkflowException { return WorkflowHelper.isLive(this); } /** * */ public void doTransition(String transitionID, String revision) throws WorkflowException { WorkflowHelper.doTransition(this, transitionID, revision); } protected String fixAssetName(String name) { // some browsers may send the whole path: int i = name.lastIndexOf("\\"); if (i > -1) { name = name.substring(i + 1); } i = name.lastIndexOf("/"); if (i > -1) { name = name.substring(i + 1); } name = name.replaceAll(" |&|%|\\?", "_"); return name; } }
src/resources/file/src/java/org/wyona/yanel/impl/resources/node/NodeResource.java
/* * Copyright 2006 Wyona * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.wyona.org/licenses/APACHE-LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wyona.yanel.impl.resources.node; import org.wyona.yanel.core.Path; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.ResourceConfiguration; import org.wyona.yanel.core.Topic; import org.wyona.yanel.core.api.attributes.CreatableV2; import org.wyona.yanel.core.api.attributes.IntrospectableV1; import org.wyona.yanel.core.api.attributes.ModifiableV2; import org.wyona.yanel.core.api.attributes.VersionableV2; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.api.attributes.WorkflowableV1; import org.wyona.yanel.core.attributes.versionable.RevisionInformation; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.attributes.viewable.ViewDescriptor; import org.wyona.yanel.core.util.PathUtil; import org.wyona.yanel.core.workflow.WorkflowException; import org.wyona.yanel.core.workflow.WorkflowHelper; import org.wyona.yanel.servlet.communication.HttpRequest; import org.wyona.yarep.core.Node; import org.wyona.yarep.core.Repository; import org.wyona.yarep.core.RepositoryFactory; import org.wyona.yarep.core.Revision; import org.wyona.yarep.util.RepoPath; import javax.servlet.http.HttpServletRequest; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.util.Date; import java.util.Enumeration; import org.apache.log4j.Category; import org.apache.commons.fileupload.util.Streams; /** * Generic Node Resource */ public class NodeResource extends Resource implements ViewableV2, ModifiableV2, VersionableV2, IntrospectableV1, WorkflowableV1, CreatableV2 { //public class NodeResource extends Resource implements ViewableV2, ModifiableV2, VersionableV2, CreatableV2 { private static Category log = Category.getInstance(NodeResource.class); private String uploadMimeType; /** * */ public NodeResource() { } /** * */ public ViewDescriptor[] getViewDescriptors() { return null; } public View getView(String viewId, String revisionName) throws Exception { View view = new View(); view.setInputStream(getRealm().getRepository().getNode(getPath()).getRevision(revisionName).getInputStream()); view.setMimeType(getMimeType(viewId)); view.setEncoding(getResourceConfigProperty("encoding")); return view; } /** * */ public View getView(String viewId) throws Exception { View view = new View(); view.setInputStream(getRealm().getRepository().getNode(getPath()).getInputStream()); view.setMimeType(getMimeType(viewId)); view.setEncoding(getResourceConfigProperty("encoding")); return view; } /** * */ public String getMimeType(String viewId) throws Exception { String mimeType = getResourceConfigProperty("mime-type"); if (mimeType != null) return mimeType; // TODO: Load config mime.types ... String suffix = PathUtil.getSuffix(getPath()); if (suffix != null) { log.debug("SUFFIX: " + suffix); mimeType = getMimeTypeBySuffix(suffix); } else { log.warn("mime-type will be set to application/octet-stream, because no suffix for " + getPath()); mimeType = "application/octet-stream"; } return mimeType; } /** * */ public Reader getReader() throws Exception { return new InputStreamReader(getInputStream(), "UTF-8"); } /** * */ public InputStream getInputStream() throws Exception { return getRealm().getRepository().getNode(getPath()).getInputStream(); } /** * */ public Writer getWriter() throws Exception { log.error("Not implemented yet!"); return null; } /** * */ public OutputStream getOutputStream() throws Exception { if (!getRealm().getRepository().existsNode(getPath())) { // TODO: create node recursively ... getRealm().getRepository().getNode(new org.wyona.commons.io.Path(getPath()).getParent().toString()).addNode(new org.wyona.commons.io.Path(getPath()).getName().toString(), org.wyona.yarep.core.NodeType.RESOURCE); } return getRealm().getRepository().getNode(getPath()).getOutputStream(); } /** * */ public void write(InputStream in) throws Exception { log.warn("Not implemented yet!"); } /** * */ public long getLastModified() throws Exception { Node node = getRealm().getRepository().getNode(getPath()); long lastModified; if (node.isResource()) { lastModified = node.getLastModified(); } else { lastModified = 0; } return lastModified; } /** * Delete data of node resource */ public boolean delete() throws Exception { getRealm().getRepository().getNode(getPath()).delete(); return true; } /** * @see org.wyona.yanel.core.api.attributes.VersionableV2#getRevisions() */ public RevisionInformation[] getRevisions() throws Exception { Revision[] revisions = getRealm().getRepository().getNode(getPath()).getRevisions(); RevisionInformation[] revisionInfos = new RevisionInformation[revisions.length]; for (int i = 0; i < revisions.length; i++) { revisionInfos[i] = new RevisionInformation(revisions[i]); } if (revisions.length > 0) { log.warn("Node \"" + getPath() + "\" does not seem to have any revisions! The repository \"" + getRealm().getRepository() + "\" might not support revisions!"); } return revisionInfos; } public void checkin(String comment) throws Exception { Node node = getRealm().getRepository().getNode(getPath()); node.checkin(comment); /* if (node.isCheckedOut()) { String checkoutUserID = node.getCheckoutUserID(); if (checkoutUserID.equals(userID)) { node.checkin(); } else { throw new Exception("Resource is checked out by another user: " + checkoutUserID); } } else { throw new Exception("Resource is not checked out."); } */ } public void checkout(String userID) throws Exception { Node node = getRealm().getRepository().getNode(getPath()); node.checkout(userID); /* if (node.isCheckedOut()) { String checkoutUserID = node.getCheckoutUserID(); if (checkoutUserID.equals(userID)) { log.warn("Resource " + getPath() + " is already checked out by this user: " + checkoutUserID); } else { throw new Exception("Resource is already checked out by another user: " + checkoutUserID); } } else { node.checkout(userID); } */ } public void cancelCheckout() throws Exception { Node node = getRealm().getRepository().getNode(getPath()); node.cancelCheckout(); } public void restore(String revisionName) throws Exception { getRealm().getRepository().getNode(getPath()).restore(revisionName); } public Date getCheckoutDate() throws Exception { Node node = getRealm().getRepository().getNode(getPath()); // return node.getCheckoutDate(); return null; } public String getCheckoutUserID() throws Exception { Node node = getRealm().getRepository().getNode(getPath()); return node.getCheckoutUserID(); } public boolean isCheckedOut() throws Exception { Node node = getRealm().getRepository().getNode(getPath()); return node.isCheckedOut(); } public boolean exists() throws Exception { return getRealm().getRepository().existsNode(getPath()); } /** * */ public long getSize() throws Exception { Node node = getRealm().getRepository().getNode(getPath()); long size; if (node.isResource()) { size = node.getSize(); } else { size = 0; } return size; } /** * */ public Object getProperty(String name) { log.warn("No implemented yet!"); return null; } /** * */ public String[] getPropertyNames() { String[] props = {"data"}; return props; } /** * */ public void setProperty(String name, Object value) { log.warn("No implemented yet!"); } /** * */ public void create(HttpServletRequest request) { try { Repository repo = getRealm().getRepository(); if (request instanceof HttpRequest) { HttpRequest yanelRequest = (HttpRequest)request; if (yanelRequest.isMultipartRequest()) { Enumeration parameters = yanelRequest.getFileNames(); if (parameters.hasMoreElements()) { String name = (String) parameters.nextElement(); Node newNode = org.wyona.yanel.core.util.YarepUtil.addNodes(repo, getPath().toString(), org.wyona.yarep.core.NodeType.RESOURCE); OutputStream output = newNode.getOutputStream(); InputStream is = yanelRequest.getInputStream(name); Streams.copy(is, output, true); uploadMimeType = yanelRequest.getContentType(name); newNode.setMimeType(uploadMimeType); } } else { log.error("this is NOT a multipart request"); } } else { log.error("this is NOT a HttpRequest"); } // TODO: Introspection should not be hardcoded! /* String name = new org.wyona.commons.io.Path(getPath()).getName(); String parent = new org.wyona.commons.io.Path(getPath()).getParent().toString(); String nameWithoutSuffix = name; int lastIndex = name.lastIndexOf("."); if (lastIndex > 0) nameWithoutSuffix = name.substring(0, lastIndex); String introspectionPath = parent + "/introspection-" + nameWithoutSuffix + ".xml"; org.wyona.yanel.core.util.YarepUtil.addNodes(repo, introspectionPath, org.wyona.yarep.core.NodeType.RESOURCE); writer = new java.io.OutputStreamWriter(repo.getNode(introspectionPath).getOutputStream()); writer.write(getIntrospection(name)); writer.close();*/ } catch (Exception e) { log.error(e.getMessage(), e); } } /** * */ public java.util.HashMap createRTIProperties(HttpServletRequest request) { java.util.HashMap map = new java.util.HashMap(); String mimeType = request.getParameter("rp.mime-type"); if (mimeType == null) { mimeType = this.uploadMimeType; } map.put("mime-type", mimeType); map.put("encoding", request.getParameter("rp.encoding")); return map; } public String getCreateName(String suggestedName) { if (suggestedName != null && !suggestedName.equals("")) return suggestedName; if (request instanceof HttpRequest) { HttpRequest yanelRequest = (HttpRequest)request; if (yanelRequest.isMultipartRequest()) { Enumeration parameters = yanelRequest.getFileNames(); if (parameters.hasMoreElements()) { return fixAssetName(yanelRequest.getFilesystemName((String) parameters.nextElement())); } } else { log.error("this is NOT a multipart request"); } } else { log.error("this is NOT a HttpRequest"); } return null; } /** * */ public String getPropertyType(String name) { return CreatableV2.TYPE_UPLOAD; } /** * Get introspection document */ public String getIntrospection() throws Exception { String name = PathUtil.getName(getPath()); StringBuffer buf = new StringBuffer(); buf.append("<?xml version=\"1.0\"?>"); buf.append("<introspection xmlns=\"http://www.wyona.org/neutron/2.0\">"); buf.append("<navigation>"); buf.append(" <sitetree href=\"./\" method=\"PROPFIND\"/>"); buf.append("</navigation>"); buf.append("<resource name=\"" + name + "\">"); buf.append("<edit mime-type=\"" + this.getMimeType(null) + "\">"); buf.append("<checkout url=\"?yanel.resource.usecase=checkout\" method=\"GET\"/>"); buf.append("<checkin url=\"?yanel.resource.usecase=checkin\" method=\"PUT\"/>"); buf.append("<release-lock url=\"?yanel.resource.usecase=release-lock\" method=\"GET\"/>"); buf.append("</edit>"); buf.append(getWorkflowIntrospection()); buf.append("</resource>"); buf.append("</introspection>"); return buf.toString(); } /** * */ public String getMimeTypeBySuffix(String suffix) { // TODO: use MimeTypeUtil if (suffix.equals("html")) { return "text/html"; } else if (suffix.equals("htm")) { return "text/html"; } else if (suffix.equals("xhtml")) { return "application/xhtml+xml"; } else if (suffix.equals("xml")) { return "application/xml"; } else if (suffix.equals("css")) { return "text/css"; } else if (suffix.equals("js")) { return "application/x-javascript"; } else if (suffix.equals("png")) { return "image/png"; } else if (suffix.equals("jpg")) { return "image/jpeg"; } else if (suffix.equals("gif")) { return "image/gif"; } else if (suffix.equals("pdf")) { return "application/pdf"; } else if (suffix.equals("doc")) { return "application/msword"; } else if (suffix.equals("odt")) { return "application/vnd.oasis.opendocument.text"; } else if (suffix.equals("sxc")) { return "application/vnd.sun.xml.calc"; } else if (suffix.equals("xpi")) { return "application/x-xpinstall"; } else if (suffix.equals("zip")) { return "application/zip"; } else if (suffix.equals("jar")) { // http://en.wikipedia.org/wiki/Jar_(file_format) return "application/java-archive"; } else if (suffix.equals("war")) { return "application/java-archive"; } else if (suffix.equals("flv")) { return "video/x-flv"; } else if (suffix.equals("swf")) { return "application/x-shockwave-flash"; } else if (suffix.equals("txt")) { return "text/plain"; } else if (suffix.equals("mov")) { return "video/quicktime"; } else if (suffix.equals("svg")) { return "image/svg+xml"; } else if (suffix.equals("ico")) { return "image/x-icon"; } else { log.warn("Could not determine mime-type from suffix (suffix: " + suffix + ")!"); return "application/octet-stream"; } } /** * */ public String getWorkflowIntrospection() throws WorkflowException { return WorkflowHelper.getWorkflowIntrospection(this); } /** * */ public void removeWorkflowVariable(String name) throws WorkflowException { WorkflowHelper.removeWorkflowVariable(this, name); } /** * */ public void setWorkflowVariable(String name, String value) throws WorkflowException { WorkflowHelper.setWorkflowVariable(this, name, value); } /** * */ public String getWorkflowVariable(String name) throws WorkflowException { return WorkflowHelper.getWorkflowVariable(this, name); } /** * */ public Date getWorkflowDate(String revision) throws WorkflowException { return WorkflowHelper.getWorkflowDate(this, revision); } /** * */ public void setWorkflowState(String state, String revision) throws WorkflowException { WorkflowHelper.setWorkflowState(this, state, revision); } /** * */ public String getWorkflowState(String revision) throws WorkflowException { return WorkflowHelper.getWorkflowState(this, revision); } /** * */ public View getLiveView(String viewid) throws Exception { return WorkflowHelper.getLiveView(this, viewid); } /** * */ public boolean isLive() throws WorkflowException { return WorkflowHelper.isLive(this); } /** * */ public void doTransition(String transitionID, String revision) throws WorkflowException { WorkflowHelper.doTransition(this, transitionID, revision); } protected String fixAssetName(String name) { // some browsers may send the whole path: int i = name.lastIndexOf("\\"); if (i > -1) { name = name.substring(i + 1); } i = name.lastIndexOf("/"); if (i > -1) { name = name.substring(i + 1); } name = name.replaceAll(" |&|%|\\?", "_"); return name; } }
javadoc added
src/resources/file/src/java/org/wyona/yanel/impl/resources/node/NodeResource.java
javadoc added
<ide><path>rc/resources/file/src/java/org/wyona/yanel/impl/resources/node/NodeResource.java <ide> return map; <ide> } <ide> <add> /** <add> * Use suggested name if not null or empty, otherwise use name of uploaded file <add> */ <ide> public String getCreateName(String suggestedName) { <ide> if (suggestedName != null && !suggestedName.equals("")) return suggestedName; <ide> if (request instanceof HttpRequest) {
JavaScript
mit
e8f972022ac8478efc6b202dd124c1bf4de86806
0
julien66/task-creator,julien66/task-creator
/** * @file * Waypoint file parser module for the task creator. */ define(['jquery', 'waypoints/waypoints', 'task/task', 'tracks/tracks', 'formats/oziOld', 'formats/ozi', 'formats/cup', 'formats/igc', 'formats/tsk', 'formats/gpx', 'jgrowl'], function($, waypoints, task, tracks, oziOld, ozi, cup, igc, tsk, gpx) { var formats = [oziOld, ozi, cup, igc, tsk, gpx]; var parse = function(text, filename) { var result = formatCheck(text, filename); var format = result.format; if (!format) { $.jGrowl(result.message, { header : result.state, theme : result.state, sticky : true, position : 'top-left', }); return; } var fileInfo = format.parse(text, filename); var parseInfo = {}; if (fileInfo.waypoints) { var waypointsInfos = fileInfo.waypoints; var l = waypointsInfos.length; var waypointsArray = Array(); for (var i = 0; i < l; i++) { if (!waypoints.alreadyHave(waypointsInfos[i])) { var waypoint = waypoints.addWaypoint(waypointsInfos[i]); waypointsArray.push(waypoint); } } if (l > 0) { waypoints.clearPastFile(); waypoints.addFilename(filename); $.jGrowl(l + ' waypoints succesfully imported from file : ' + filename + ' !!', { header : 'success', theme : 'success', sticky : true, position : 'top-left', }); } else { $.jGrowl('No waypoint were found from file : ' + filename + ' !!', { header : 'warning', theme : 'warning', sticky : true, position : 'top-left', }); } parseInfo.waypoints = waypointsArray; } if (fileInfo.tracks) { var tracksInfos = fileInfo.tracks; var l = tracksInfos.length; var tracksArray = Array(); for (var i = 0; i < l; i++) { var track = tracks.addTrack(tracksInfos[i]); tracksArray.push(track); } parseInfo.tracks = tracksArray; } if (fileInfo.task) { parseInfo.task = fileInfo.task; if (parseInfo.task.turnpoints.length > 0) { for (var i = 0; i < parseInfo.task.turnpoints.length; i++ ) { var tp = parseInfo.task.turnpoints[i]; var waypoint = waypoints.getWaypointByFileAndId(tp.wp.filename , tp.wp.id); tp.waypoint = waypoint; } } } return parseInfo; } var formatCheck = function(text, filename) { var formatsName = []; for (var i = 0; i < formats.length; i++) { formatsName.push(formats[i].name); } var result = { format : false, state : 'error', message : 'Waypoints file format unknown. We only support : ' + formatsName.join(" , ") + ' files', } if (waypoints.checkFilename(filename) == false) { result.message = 'This file : ' + filename + " is alredy used."; result.state = 'warning'; return result; } for (var i = 0; i < formats.length; i++) { if (formats[i].check(text, filename) == true) { result.format = formats[i]; return result; } } return result; } return { 'parse' : parse, } });
js/app/wpParser.js
/** * @file * Waypoint file parser module for the task creator. */ define(['jquery', 'waypoints/waypoints', 'task/task', 'tracks/tracks', 'formats/oziOld', 'formats/ozi', 'formats/cup', 'formats/igc', 'formats/tsk', 'formats/gpx', 'jgrowl'], function($, waypoints, task, tracks, oziOld, ozi, cup, igc, tsk, gpx) { var formats = [oziOld, ozi, cup, igc, tsk, gpx]; var parse = function(text, filename) { var result = formatCheck(text, filename); var format = result.format; if (!format) { $.jGrowl(result.message, { header : result.state, theme : result.state, sticky : true, position : 'top-left', }); return; } var fileInfo = format.parse(text, filename); var parseInfo = {}; if (fileInfo.waypoints) { var waypointsInfos = fileInfo.waypoints; var l = waypointsInfos.length; var waypointsArray = Array(); for (var i = 0; i < l; i++) { if (!waypoints.alreadyHave(waypointsInfos[i])) { var waypoint = waypoints.addWaypoint(waypointsInfos[i]); waypointsArray.push(waypoint); } } if (l > 0) { waypoints.clearPastFile(); waypoints.addFilename(filename); $.jGrowl(l + ' waypoints succesfully imported from file : ' + filename + ' !!', { header : 'success', theme : 'success', sticky : true, position : 'top-left', }); } else { $.jGrowl('No waypoint were found from file : ' + filename + ' !!', { header : 'warning', theme : 'warning', sticky : true, position : 'top-left', }); } parseInfo.waypoints = waypointsArray; } if (fileInfo.tracks) { var tracksInfos = fileInfo.tracks; var l = tracksInfos.length; var tracksArray = Array(); for (var i = 0; i < l; i++) { var track = tracks.addTrack(tracksInfos[i]); tracksArray.push(track); } parseInfo.tracks = tracksArray; } if (fileInfo.task) { parseInfo.task = fileInfo.task; if (parseInfo.task.turnpoints.length > 0) { for (var i = 0; i < parseInfo.task.turnpoints.length; i++ ) { var tp = parseInfo.task.turnpoints[i]; var waypoint = waypoints.getWaypointByFileAndId(tp.wp.filename , tp.wp.id); tp.waypoint = waypoint; } return parseInfo; } } } var formatCheck = function(text, filename) { var formatsName = []; for (var i = 0; i < formats.length; i++) { formatsName.push(formats[i].name); } var result = { format : false, state : 'error', message : 'Waypoints file format unknown. We only support : ' + formatsName.join(" , ") + ' files', } if (waypoints.checkFilename(filename) == false) { result.message = 'This file : ' + filename + " is alredy used."; result.state = 'warning'; return result; } for (var i = 0; i < formats.length; i++) { if (formats[i].check(text, filename) == true) { result.format = formats[i]; return result; } } return result; } return { 'parse' : parse, } });
Bug Fixes : Trying to import any set of existing waypoint (file) was impossible since last commit. Credits to James Bradley via PM on Paragliding Forum.
js/app/wpParser.js
Bug Fixes : Trying to import any set of existing waypoint (file) was impossible since last commit. Credits to James Bradley via PM on Paragliding Forum.
<ide><path>s/app/wpParser.js <ide> var waypoint = waypoints.getWaypointByFileAndId(tp.wp.filename , tp.wp.id); <ide> tp.waypoint = waypoint; <ide> } <del> return parseInfo; <ide> } <ide> } <add> return parseInfo; <ide> } <ide> <ide> var formatCheck = function(text, filename) {
Java
apache-2.0
434fe989985bb6f9fd3a9b3cf7a38ecbdb66cf6d
0
stain/BridgeDb,stain/BridgeDb,stain/BridgeDb,stain/BridgeDb,egonw/BridgeDb,bridgedb/BridgeDb,stain/BridgeDb,egonw/BridgeDb,stain/BridgeDb,egonw/BridgeDb,egonw/BridgeDb,egonw/BridgeDb,stain/BridgeDb,bridgedb/BridgeDb,bridgedb/BridgeDb,bridgedb/BridgeDb,stain/BridgeDb,bridgedb/BridgeDb
// BridgeDb, // An abstraction layer for identifier mapping services, both local and online. // Copyright 2006-2009 BridgeDb developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.bridgedb.webservice.biomart.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.bridgedb.impl.InternalUtils; import org.bridgedb.webservice.biomart.IDMapperBiomart; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * BioMart service class, adapted from BioMart client in Cytoscape. */ public final class BiomartClient { public static final String DEFAULT_BASE_URL = "http://www.biomart.org/biomart/martservice"; private final String baseURL; private static final String RESOURCE = "/org/bridgedb/webservice/biomart/util/filterconversion.txt"; // caches the result of getRegistry() private Map<String, Database> marts = null; private Map<String, Map<String, String>> filterConversionMap; private static final int BUFFER_SIZE = 81920; /** * Creates a new BiomartStub object from given URL. * * @param baseURL base url of martservice, for example "http://www.biomart.org/biomart/martservice" (default) * @throws IOException if failed to read local resource */ public BiomartClient(String baseURL) throws IOException { this.baseURL = baseURL + "?"; loadConversionFile(); } /** * Conversion map from filter to attribute. * @throws IOException if failed to read local resource */ private void loadConversionFile() throws IOException { filterConversionMap = new HashMap<String, Map<String, String>>(); InputStreamReader inFile = new InputStreamReader(IDMapperBiomart.class.getResource(RESOURCE).openStream()); BufferedReader inBuffer = new BufferedReader(inFile); String line; String trimed; String oldName = null; Map<String, String> oneEntry = new HashMap<String, String>(); String[] dbparts; while ((line = inBuffer.readLine()) != null) { trimed = line.trim(); dbparts = trimed.split("\\t"); if (dbparts[0].equals(oldName) == false) { oneEntry = new HashMap<String, String>(); oldName = dbparts[0]; filterConversionMap.put(oldName, oneEntry); } oneEntry.put(dbparts[1], dbparts[2]); } inFile.close(); inBuffer.close(); } /** * @param mart mart name * @param dataset dataset name * @param filter filter to convert * @return Attribute converted from filter * @throws IOException if failed to read from webservice */ public Attribute filterToAttribute(String mart, String dataset, String filter) throws IOException { String attrName; if (dataset.contains("REACTOME")) { attrName = filterConversionMap.get("REACTOME").get(filter); } else if (dataset.contains("UNIPROT")) { attrName = filterConversionMap.get("UNIPROT").get(filter); } else if (dataset.contains("VARIATION")) { attrName = filter + "_stable_id"; } else { attrName = filter; } return getMart(mart).getDataset(dataset).getAttribute(attrName); } /** * Get the registry information from the base URL. * * @return Map of registry information. Key value is "name" field. * @throws ParserConfigurationException if failed new document builder * @throws SAXException if failed to parse registry * @throws IOException if failed to read from URL */ public Map<String, Database> getRegistry() throws IOException, ParserConfigurationException, SAXException { // If already loaded, just return it. if (marts != null) return marts; // Initialize database map. marts = new HashMap<String, Database>(); // Prepare URL for the registry status final String reg = "type=registry"; final URL targetURL = new URL(baseURL + reg); // Get the result as XML document. final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); InputStream is = InternalUtils.getInputStream(targetURL); final Document registry = builder.parse(is); // Extract each datasource NodeList locations = registry.getElementsByTagName("MartURLLocation"); int locSize = locations.getLength(); NamedNodeMap attrList; int attrLen; String dbID; for (int i = 0; i < locSize; i++) { attrList = locations.item(i).getAttributes(); attrLen = attrList.getLength(); // First, get the key value dbID = attrList.getNamedItem("name").getNodeValue(); Map<String, String> entry = new HashMap<String, String>(); for (int j = 0; j < attrLen; j++) { entry.put(attrList.item(j).getNodeName(), attrList.item(j).getNodeValue()); } marts.put(dbID, new Database(dbID,entry)); } is.close(); is = null; return marts; } /** * Send the XML query to Biomart, and get the result as table. * @param xmlQuery query xml * @return result {@link BufferedReader} * @throws IOException if failed to read webservice */ public BufferedReader sendQuery(String xmlQuery) throws IOException { return new BufferedReader(new InputStreamReader(sendQueryAsStream (xmlQuery)), BUFFER_SIZE); } /** * Send the XML query to Biomart, and get the result as table. * @param xmlQuery query xml * @return result {@link BufferedReader} * @throws IOException if failed to read webservice */ public InputStream sendQueryAsStream (String xmlQuery) throws IOException { //System.out.println("=======Query = " + xmlQuery); URL url = new URL(baseURL); URLConnection uc = url.openConnection(); uc.setDoOutput(true); uc.setRequestProperty("User-Agent", "Java URLConnection"); OutputStream os = uc.getOutputStream(); final String postStr = "query=" + xmlQuery; PrintStream ps = new PrintStream(os); // Post the data ps.print(postStr); os.close(); ps.close(); ps = null; os = null; return uc.getInputStream(); } /** * get Database/mart. * @param dbname database name * @return database */ public Database getMart(final String dbname) { return marts.get(dbname); } }
org.bridgedb.webservice.biomart/src/org/bridgedb/webservice/biomart/util/BiomartClient.java
// BridgeDb, // An abstraction layer for identifier mapping services, both local and online. // Copyright 2006-2009 BridgeDb developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.bridgedb.webservice.biomart.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.bridgedb.impl.InternalUtils; import org.bridgedb.webservice.biomart.IDMapperBiomart; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * BioMart service class, adapted from BioMart client in Cytoscape. */ public final class BiomartClient { public static final String DEFAULT_BASE_URL = "http://www.biomart.org/biomart/martservice"; private final String baseURL; private static final String RESOURCE = "/org/bridgedb/webservice/biomart/util/filterconversion.txt"; // caches the result of getRegistry() private Map<String, Database> marts = null; private Map<String, Map<String, String>> filterConversionMap; private static final int BUFFER_SIZE = 81920; /** * Creates a new BiomartStub object from given URL. * * @param baseURL base url of martservice, for example "http://www.biomart.org/biomart/martservice" (default) * @throws IOException if failed to read local resource */ public BiomartClient(String baseURL) throws IOException { this.baseURL = baseURL + "?"; loadConversionFile(); } /** * Conversion map from filter to attribute. * @throws IOException if failed to read local resource */ private void loadConversionFile() throws IOException { filterConversionMap = new HashMap<String, Map<String, String>>(); InputStreamReader inFile = new InputStreamReader(IDMapperBiomart.class.getResource(RESOURCE).openStream()); BufferedReader inBuffer = new BufferedReader(inFile); String line; String trimed; String oldName = null; Map<String, String> oneEntry = new HashMap<String, String>(); String[] dbparts; while ((line = inBuffer.readLine()) != null) { trimed = line.trim(); dbparts = trimed.split("\\t"); if (dbparts[0].equals(oldName) == false) { oneEntry = new HashMap<String, String>(); oldName = dbparts[0]; filterConversionMap.put(oldName, oneEntry); } oneEntry.put(dbparts[1], dbparts[2]); } inFile.close(); inBuffer.close(); } /** * @param mart mart name * @param dataset dataset name * @param filter filter to convert * @return Attribute converted from filter * @throws IOException if failed to read from webservice */ public Attribute filterToAttribute(String mart, String dataset, String filter) throws IOException { String attrName; if (dataset.contains("REACTOME")) { attrName = filterConversionMap.get("REACTOME").get(filter); } else if (dataset.contains("UNIPROT")) { attrName = filterConversionMap.get("UNIPROT").get(filter); } else if (dataset.contains("VARIATION")) { attrName = filter + "_stable_id"; } else { attrName = filter; } return getMart(mart).getDataset(dataset).getAttribute(attrName); } /** * Get the registry information from the base URL. * * @return Map of registry information. Key value is "name" field. * @throws ParserConfigurationException if failed new document builder * @throws SAXException if failed to parse registry * @throws IOException if failed to read from URL */ public Map<String, Database> getRegistry() throws IOException, ParserConfigurationException, SAXException { // If already loaded, just return it. if (marts != null) return marts; // Initialize database map. marts = new HashMap<String, Database>(); // Prepare URL for the registry status final String reg = "type=registry"; final URL targetURL = new URL(baseURL + reg); // Get the result as XML document. final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); InputStream is = InternalUtils.getInputStream(targetURL); final Document registry = builder.parse(is); // Extract each datasource NodeList locations = registry.getElementsByTagName("MartURLLocation"); int locSize = locations.getLength(); NamedNodeMap attrList; int attrLen; String dbID; for (int i = 0; i < locSize; i++) { attrList = locations.item(i).getAttributes(); attrLen = attrList.getLength(); // First, get the key value dbID = attrList.getNamedItem("name").getNodeValue(); Map<String, String> entry = new HashMap<String, String>(); for (int j = 0; j < attrLen; j++) { entry.put(attrList.item(j).getNodeName(), attrList.item(j).getNodeValue()); } marts.put(dbID, new Database(dbID,entry)); } is.close(); is = null; return marts; } /** * Send the XML query to Biomart, and get the result as table. * @param xmlQuery query xml * @return result {@link BufferedReader} * @throws IOException if failed to read webservice */ public BufferedReader sendQuery(String xmlQuery) throws IOException { //System.out.println("=======Query = " + xmlQuery); URL url = new URL(baseURL); URLConnection uc = url.openConnection(); uc.setDoOutput(true); uc.setRequestProperty("User-Agent", "Java URLConnection"); OutputStream os = uc.getOutputStream(); final String postStr = "query=" + xmlQuery; PrintStream ps = new PrintStream(os); // Post the data ps.print(postStr); os.close(); ps.close(); ps = null; os = null; return new BufferedReader(new InputStreamReader(uc.getInputStream()), BUFFER_SIZE); } /** * get Database/mart. * @param dbname database name * @return database */ public Database getMart(final String dbname) { return marts.get(dbname); } }
Expose inputstream from biomart sendQuery git-svn-id: b9aa09681bb449106768a53c71c444e56dcea582@662 e3f1d335-44b1-4163-9530-9b341189ae98
org.bridgedb.webservice.biomart/src/org/bridgedb/webservice/biomart/util/BiomartClient.java
Expose inputstream from biomart sendQuery
<ide><path>rg.bridgedb.webservice.biomart/src/org/bridgedb/webservice/biomart/util/BiomartClient.java <ide> * @return result {@link BufferedReader} <ide> * @throws IOException if failed to read webservice <ide> */ <del> public BufferedReader sendQuery(String xmlQuery) throws IOException { <add> public BufferedReader sendQuery(String xmlQuery) throws IOException <add> { <add> return new BufferedReader(new InputStreamReader(sendQueryAsStream (xmlQuery)), BUFFER_SIZE); <add> } <add> <add> /** <add> * Send the XML query to Biomart, and get the result as table. <add> * @param xmlQuery query xml <add> * @return result {@link BufferedReader} <add> * @throws IOException if failed to read webservice <add> */ <add> public InputStream sendQueryAsStream (String xmlQuery) throws IOException { <ide> <ide> //System.out.println("=======Query = " + xmlQuery); <ide> <ide> ps = null; <ide> os = null; <ide> <del> return new BufferedReader(new InputStreamReader(uc.getInputStream()), BUFFER_SIZE); <add> return uc.getInputStream(); <ide> } <ide> <ide> /**
Java
mit
21b155bb3f32b218c628b1fd0c44c2699372e208
0
SpongePowered/Sponge,SpongePowered/Sponge,SpongePowered/SpongeCommon,SpongePowered/Sponge,SpongePowered/SpongeCommon
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.mixin.core.item.inventory; import net.minecraft.inventory.ContainerRepair; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.common.item.inventory.adapter.InventoryAdapter; import org.spongepowered.common.item.inventory.adapter.impl.slots.InputSlotAdapter; import org.spongepowered.common.item.inventory.adapter.impl.slots.OutputSlotAdapter; import org.spongepowered.common.item.inventory.lens.Fabric; import org.spongepowered.common.item.inventory.lens.Lens; import org.spongepowered.common.item.inventory.lens.LensProvider; import org.spongepowered.common.item.inventory.lens.SlotProvider; import org.spongepowered.common.item.inventory.lens.impl.collections.SlotCollection; import org.spongepowered.common.item.inventory.lens.impl.comp.MainPlayerInventoryLensImpl; import org.spongepowered.common.item.inventory.lens.impl.comp.OrderedInventoryLensImpl; import org.spongepowered.common.item.inventory.lens.impl.minecraft.container.ContainerLens; import org.spongepowered.common.item.inventory.lens.impl.slots.InputSlotLensImpl; import org.spongepowered.common.item.inventory.lens.impl.slots.OutputSlotLensImpl; import java.util.ArrayList; import java.util.List; @Mixin(ContainerRepair.class) public abstract class MixinContainerRepair extends MixinContainer implements LensProvider { @Override public Lens rootLens(Fabric fabric, InventoryAdapter adapter) { List<Lens> lenses = new ArrayList<>(); lenses.add(new OrderedInventoryLensImpl(0, 3, 1, inventory$getSlotProvider())); lenses.add(new MainPlayerInventoryLensImpl(3, inventory$getSlotProvider(), true)); return new ContainerLens(adapter, inventory$getSlotProvider(), lenses); } @SuppressWarnings("unchecked") @Override public SlotProvider slotProvider(Fabric fabric, InventoryAdapter adapter) { SlotCollection.Builder builder = new SlotCollection.Builder() .add(2, InputSlotAdapter.class, i -> new InputSlotLensImpl(i, s -> true, t -> true)) .add(1, OutputSlotAdapter.class, i -> new OutputSlotLensImpl(i, s -> false, t -> false)) .add(36); return builder.build(); } }
src/main/java/org/spongepowered/common/mixin/core/item/inventory/MixinContainerRepair.java
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.mixin.core.item.inventory; import net.minecraft.inventory.ContainerRepair; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.common.item.inventory.adapter.InventoryAdapter; import org.spongepowered.common.item.inventory.adapter.impl.slots.InputSlotAdapter; import org.spongepowered.common.item.inventory.adapter.impl.slots.OutputSlotAdapter; import org.spongepowered.common.item.inventory.lens.Fabric; import org.spongepowered.common.item.inventory.lens.Lens; import org.spongepowered.common.item.inventory.lens.LensProvider; import org.spongepowered.common.item.inventory.lens.SlotProvider; import org.spongepowered.common.item.inventory.lens.impl.collections.SlotCollection; import org.spongepowered.common.item.inventory.lens.impl.comp.MainPlayerInventoryLensImpl; import org.spongepowered.common.item.inventory.lens.impl.comp.OrderedInventoryLensImpl; import org.spongepowered.common.item.inventory.lens.impl.minecraft.container.ContainerLens; import java.util.ArrayList; import java.util.List; @Mixin(ContainerRepair.class) public abstract class MixinContainerRepair extends MixinContainer implements LensProvider { @Override public Lens rootLens(Fabric fabric, InventoryAdapter adapter) { List<Lens> lenses = new ArrayList<>(); lenses.add(new OrderedInventoryLensImpl(0, 3, 1, inventory$getSlotProvider())); lenses.add(new MainPlayerInventoryLensImpl(3, inventory$getSlotProvider(), true)); return new ContainerLens(adapter, inventory$getSlotProvider(), lenses); } @SuppressWarnings("unchecked") @Override public SlotProvider slotProvider(Fabric fabric, InventoryAdapter adapter) { SlotCollection.Builder builder = new SlotCollection.Builder() .add(2, InputSlotAdapter.class) .add(1, OutputSlotAdapter.class) .add(36); return builder.build(); } }
fix Anvil Input and Output slots fixes #2043
src/main/java/org/spongepowered/common/mixin/core/item/inventory/MixinContainerRepair.java
fix Anvil Input and Output slots fixes #2043
<ide><path>rc/main/java/org/spongepowered/common/mixin/core/item/inventory/MixinContainerRepair.java <ide> import org.spongepowered.common.item.inventory.lens.impl.comp.MainPlayerInventoryLensImpl; <ide> import org.spongepowered.common.item.inventory.lens.impl.comp.OrderedInventoryLensImpl; <ide> import org.spongepowered.common.item.inventory.lens.impl.minecraft.container.ContainerLens; <add>import org.spongepowered.common.item.inventory.lens.impl.slots.InputSlotLensImpl; <add>import org.spongepowered.common.item.inventory.lens.impl.slots.OutputSlotLensImpl; <ide> <ide> import java.util.ArrayList; <ide> import java.util.List; <ide> @Override <ide> public SlotProvider slotProvider(Fabric fabric, InventoryAdapter adapter) { <ide> SlotCollection.Builder builder = new SlotCollection.Builder() <del> .add(2, InputSlotAdapter.class) <del> .add(1, OutputSlotAdapter.class) <add> .add(2, InputSlotAdapter.class, i -> new InputSlotLensImpl(i, s -> true, t -> true)) <add> .add(1, OutputSlotAdapter.class, i -> new OutputSlotLensImpl(i, s -> false, t -> false)) <ide> .add(36); <ide> return builder.build(); <ide> }
Java
apache-2.0
d83b87a5a1c6aa2e4542181421213e7b40b6adde
0
Gugli/Openfire,akrherz/Openfire,guusdk/Openfire,GregDThomas/Openfire,guusdk/Openfire,Gugli/Openfire,magnetsystems/message-openfire,akrherz/Openfire,magnetsystems/message-openfire,GregDThomas/Openfire,GregDThomas/Openfire,guusdk/Openfire,speedy01/Openfire,GregDThomas/Openfire,igniterealtime/Openfire,speedy01/Openfire,igniterealtime/Openfire,akrherz/Openfire,guusdk/Openfire,Gugli/Openfire,magnetsystems/message-openfire,akrherz/Openfire,magnetsystems/message-openfire,speedy01/Openfire,speedy01/Openfire,magnetsystems/message-openfire,igniterealtime/Openfire,igniterealtime/Openfire,GregDThomas/Openfire,Gugli/Openfire,Gugli/Openfire,speedy01/Openfire,igniterealtime/Openfire,akrherz/Openfire,guusdk/Openfire
/** * $RCSfile$ * $Revision$ * $Date$ * * Copyright (C) 2004 Jive Software. All rights reserved. * * This software is published under the terms of the GNU Public License (GPL), * a copy of which is included in this distribution. */ package org.jivesoftware.messenger.muc.spi; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import org.dom4j.Element; import org.jivesoftware.messenger.muc.*; import org.jivesoftware.util.*; import org.jivesoftware.messenger.*; import org.jivesoftware.messenger.auth.UnauthorizedException; import org.jivesoftware.messenger.user.UserAlreadyExistsException; import org.jivesoftware.messenger.user.UserNotFoundException; import org.xmpp.packet.*; /** * Implementation of MUCUser. There will be a MUCUser per user that is connected to one or more * rooms. A MUCUser contains a collection of MUCRoles for each room where the user has joined. * * @author Gaston Dombiak */ public class MUCUserImpl implements MUCUser { /** The chat server this user belongs to. */ private MultiUserChatServer server; /** Real system XMPPAddress for the user. */ private JID realjid; /** Table: key roomName.toLowerCase(); value MUCRole. */ private Map<String, MUCRole> roles = new ConcurrentHashMap<String, MUCRole>(); /** Deliver packets to users. */ private PacketRouter router; /** * Time of last packet sent. */ private long lastPacketTime; /** * Create a new chat user. * * @param chatserver the server the user belongs to. * @param packetRouter the router for sending packets from this user. * @param jid the real address of the user */ MUCUserImpl(MultiUserChatServerImpl chatserver, PacketRouter packetRouter, JID jid) { this.realjid = jid; this.router = packetRouter; this.server = chatserver; } public long getID() { return -1; } public MUCRole getRole(String roomName) throws NotFoundException { MUCRole role = roles.get(roomName.toLowerCase()); if (role == null) { throw new NotFoundException(roomName); } return role; } public Iterator<MUCRole> getRoles() { return Collections.unmodifiableCollection(roles.values()).iterator(); } public void removeRole(String roomName) { roles.remove(roomName.toLowerCase()); } public long getLastPacketTime() { return lastPacketTime; } /** * Generate a conflict packet to indicate that the nickname being requested/used is already in * use by another user. * * @param packet the packet to be bounced. */ private void sendErrorPacket(Packet packet, PacketError.Condition error) { if (packet instanceof IQ) { IQ reply = IQ.createResultIQ((IQ) packet); reply.setChildElement(((IQ) packet).getChildElement().createCopy()); reply.setError(error); router.route(reply); } else { Packet reply = packet.createCopy(); reply.setError(error); reply.setFrom(packet.getTo()); reply.setTo(packet.getFrom()); router.route(reply); } } public JID getAddress() { return realjid; } public void process(Packet packet) throws UnauthorizedException, PacketException { if (packet instanceof IQ) { process((IQ)packet); } else if (packet instanceof Message) { process((Message)packet); } else if (packet instanceof Presence) { process((Presence)packet); } } /** * This method does all packet routing in the chat server. Packet routing is actually very * simple: * * <ul> * <li>Discover the room the user is talking to (server packets are dropped)</li> * <li>If the room is not registered and this is a presence "available" packet, try to join the * room</li> * <li>If the room is registered, and presence "unavailable" leave the room</li> * <li>Otherwise, rewrite the sender address and send to the room.</li> * </ul> * * @param packet The packet to route. */ public void process(Message packet) { // Ignore messages of type ERROR sent to a room if (Message.Type.error == packet.getType()) { return; } lastPacketTime = System.currentTimeMillis(); JID recipient = packet.getTo(); String group = recipient.getNode(); if (group == null) { // Ignore packets to the groupchat server // In the future, we'll need to support TYPE_IQ queries to the server for MUC Log.info(LocaleUtils.getLocalizedString("muc.error.not-supported") + " " + packet.toString()); } else { MUCRole role = roles.get(group.toLowerCase()); if (role == null) { if (server.hasChatRoom(group)) { boolean declinedInvitation = false; Element userInfo = null; if (Message.Type.normal == packet.getType()) { // An user that is not an occupant could be declining an invitation userInfo = packet.getChildElement( "x", "http://jabber.org/protocol/muc#user"); if (userInfo != null && userInfo.element("decline") != null) { // A user has declined an invitation to a room // WARNING: Potential fraud if someone fakes the "from" of the // message with the JID of a member and sends a "decline" declinedInvitation = true; } } if (declinedInvitation) { Element info = userInfo.element("decline"); server.getChatRoom(group).sendInvitationRejection( new JID(info.attributeValue("to")), info.elementTextTrim("reason"), packet.getFrom()); } else { // The sender is not an occupant of the room sendErrorPacket(packet, PacketError.Condition.not_acceptable); } } else { // The sender is not an occupant of a NON-EXISTENT room!!! sendErrorPacket(packet, PacketError.Condition.recipient_unavailable); } } else { // Check and reject conflicting packets with conflicting roles // In other words, another user already has this nickname if (!role.getChatUser().getAddress().equals(packet.getFrom())) { sendErrorPacket(packet, PacketError.Condition.conflict); } else { try { if (packet.getSubject() != null && packet.getSubject().trim().length() > 0 && Message.Type.groupchat == packet.getType()) { // An occupant is trying to change the room's subject role.getChatRoom().changeSubject(packet, role); } else { // An occupant is trying to send a private, send public message, // invite someone to the room or reject an invitation Message.Type type = packet.getType(); String resource = packet.getTo().getResource(); if (resource == null || resource.trim().length() == 0) { resource = null; } if (resource == null && Message.Type.groupchat == type) { // An occupant is trying to send a public message role.getChatRoom().sendPublicMessage(packet, role); } else if (resource != null && (Message.Type.chat == type || Message.Type.normal == type)) { // An occupant is trying to send a private message role.getChatRoom().sendPrivatePacket(packet, role); } else if (resource == null && Message.Type.normal == type) { // An occupant could be sending an invitation or declining an // invitation Element userInfo = packet.getChildElement( "x", "http://jabber.org/protocol/muc#user"); // Real real real UGLY TRICK!!! Will and MUST be solved when // persistence will be added. Replace locking with transactions! MUCRoomImpl room = (MUCRoomImpl) role.getChatRoom(); if (userInfo != null && userInfo.element("invite") != null) { // An occupant is sending an invitation Element info = userInfo.element("invite"); // Add the user as a member of the room if the room is // members only if (room.isMembersOnly()) { room.lock.writeLock().lock(); try { room.addMember(info.attributeValue("to"), null, role); } finally { room.lock.writeLock().unlock(); } } // Try to keep the list of extensions sent together with the // message invitation. These extensions will be sent to the // invitee. List<Element> extensions = new ArrayList<Element>(packet .getElement().elements()); extensions.remove(userInfo); // Send the invitation to the user room.sendInvitation(new JID(info.attributeValue("to")), info.elementTextTrim("reason"), role, extensions); } else if (userInfo != null && userInfo.element("decline") != null) { // An occupant has declined an invitation Element info = userInfo.element("decline"); room.sendInvitationRejection(new JID(info.attributeValue("to")), info.elementTextTrim("reason"), packet.getFrom()); } else { sendErrorPacket(packet, PacketError.Condition.bad_request); } } else { sendErrorPacket(packet, PacketError.Condition.bad_request); } } } catch (ForbiddenException e) { sendErrorPacket(packet, PacketError.Condition.forbidden); } catch (NotFoundException e) { sendErrorPacket(packet, PacketError.Condition.recipient_unavailable); } catch (ConflictException e) { sendErrorPacket(packet, PacketError.Condition.conflict); } } } } } public void process(IQ packet) { // Ignore IQs of type ERROR or RESULT sent to a room if (IQ.Type.error == packet.getType()) { return; } lastPacketTime = System.currentTimeMillis(); JID recipient = packet.getTo(); String group = recipient.getNode(); if (group == null) { // Ignore packets to the groupchat server // In the future, we'll need to support TYPE_IQ queries to the server for MUC Log.info(LocaleUtils.getLocalizedString("muc.error.not-supported") + " " + packet.toString()); } else { MUCRole role = roles.get(group.toLowerCase()); if (role == null) { // TODO: send error message to user (can't send packets to group you haven't // joined) } else if (IQ.Type.result == packet.getType()) { // Only process IQ result packet if it's a private packet sent to another // room occupant if (packet.getTo().getResource() != null) { try { // User is sending an IQ result packet to another room occupant role.getChatRoom().sendPrivatePacket(packet, role); } catch (NotFoundException e) { // Do nothing. No error will be sent to the sender of the IQ result packet } } } else { // Check and reject conflicting packets with conflicting roles // In other words, another user already has this nickname if (!role.getChatUser().getAddress().equals(packet.getFrom())) { sendErrorPacket(packet, PacketError.Condition.conflict); } else { try { Element query = packet.getElement().element("query"); if (query != null && "http://jabber.org/protocol/muc#owner".equals(query.getNamespaceURI())) { role.getChatRoom().getIQOwnerHandler().handleIQ(packet, role); } else if (query != null && "http://jabber.org/protocol/muc#admin".equals(query.getNamespaceURI())) { role.getChatRoom().getIQAdminHandler().handleIQ(packet, role); } else { if (packet.getTo().getResource() != null) { // User is sending an IQ packet to another room occupant role.getChatRoom().sendPrivatePacket(packet, role); } else { sendErrorPacket(packet, PacketError.Condition.bad_request); } } } catch (ForbiddenException e) { sendErrorPacket(packet, PacketError.Condition.forbidden); } catch (NotFoundException e) { sendErrorPacket(packet, PacketError.Condition.recipient_unavailable); } catch (ConflictException e) { sendErrorPacket(packet, PacketError.Condition.conflict); } catch (NotAllowedException e) { sendErrorPacket(packet, PacketError.Condition.not_allowed); } } } } } public void process(Presence packet) { // Ignore presences of type ERROR sent to a room if (Presence.Type.error == packet.getType()) { return; } lastPacketTime = System.currentTimeMillis(); JID recipient = packet.getTo(); String group = recipient.getNode(); if (group == null) { if (Presence.Type.unavailable == packet.getType()) { server.removeUser(packet.getFrom()); } } else { MUCRole role = roles.get(group.toLowerCase()); if (role == null) { // If we're not already in a room, we either are joining it or it's not // properly addressed and we drop it silently if (recipient.getResource() != null && recipient.getResource().trim().length() > 0) { if (packet.isAvailable()) { try { // Get or create the room MUCRoom room = server.getChatRoom(group, packet.getFrom()); // User must support MUC in order to create a room Element mucInfo = packet.getChildElement("x", "http://jabber.org/protocol/muc"); HistoryRequest historyRequest = null; String password = null; // Check for password & requested history if client supports MUC if (mucInfo != null) { password = mucInfo.elementTextTrim("password"); if (mucInfo.element("history") != null) { historyRequest = new HistoryRequest(mucInfo); } } // The user joins the room role = room.joinRoom(recipient.getResource().trim(), password, historyRequest, this, packet.createCopy()); roles.put(group.toLowerCase(), role); // If the client that created the room is non-MUC compliant then // unlock the room thus creating an "instant" room if (mucInfo == null && room.isLocked() && !room.isManuallyLocked()) { room.unlock(role); } } catch (UnauthorizedException e) { sendErrorPacket(packet, PacketError.Condition.not_authorized); } catch (ServiceUnavailableException e) { sendErrorPacket(packet, PacketError.Condition.service_unavailable); } catch (UserAlreadyExistsException e) { sendErrorPacket(packet, PacketError.Condition.conflict); } catch (RoomLockedException e) { sendErrorPacket(packet, PacketError.Condition.recipient_unavailable); } catch (ForbiddenException e) { sendErrorPacket(packet, PacketError.Condition.forbidden); } catch (RegistrationRequiredException e) { sendErrorPacket(packet, PacketError.Condition.registration_required); } catch (ConflictException e) { sendErrorPacket(packet, PacketError.Condition.conflict); } catch (NotAcceptableException e) { sendErrorPacket(packet, PacketError.Condition.not_acceptable); } catch (NotAllowedException e) { sendErrorPacket(packet, PacketError.Condition.not_allowed); } } else { // TODO: send error message to user (can't send presence to group you // haven't joined) } } else { if (packet.isAvailable()) { // A resource is required in order to join a room sendErrorPacket(packet, PacketError.Condition.bad_request); } // TODO: send error message to user (can't send packets to group you haven't // joined) } } else { // Check and reject conflicting packets with conflicting roles // In other words, another user already has this nickname if (!role.getChatUser().getAddress().equals(packet.getFrom())) { sendErrorPacket(packet, PacketError.Condition.conflict); } else { if (Presence.Type.unavailable == packet.getType()) { try { roles.remove(group.toLowerCase()); role.getChatRoom().leaveRoom(role.getNickname()); } catch (UserNotFoundException e) { // Do nothing since the users has already left the room } catch (Exception e) { Log.error(e); } } else { try { String resource = (recipient.getResource() == null || recipient.getResource().trim().length() == 0 ? null : recipient.getResource().trim()); if (resource == null || role.getNickname().equalsIgnoreCase(resource)) { // Occupant has changed his availability status role.setPresence(packet.createCopy()); role.getChatRoom().send(role.getPresence().createCopy()); } else { // Occupant has changed his nickname. Send two presences // to each room occupant // Check if occupants are allowed to change their nicknames if (!role.getChatRoom().canChangeNickname()) { sendErrorPacket(packet, PacketError.Condition.not_acceptable); } // Answer a conflic error if the new nickname is taken else if (role.getChatRoom().hasOccupant(resource)) { sendErrorPacket(packet, PacketError.Condition.conflict); } else { // Send "unavailable" presence for the old nickname Presence presence = role.getPresence().createCopy(); // Switch the presence to OFFLINE presence.setType(Presence.Type.unavailable); presence.setStatus(null); // Add the new nickname and status 303 as properties Element frag = presence.getChildElement("x", "http://jabber.org/protocol/muc#user"); frag.element("item").addAttribute("nick", resource); frag.addElement("status").addAttribute("code", "303"); role.getChatRoom().send(presence); // Send availability presence for the new nickname String oldNick = role.getNickname(); role.setPresence(packet.createCopy()); role.changeNickname(resource); role.getChatRoom().nicknameChanged(oldNick, resource); role.getChatRoom().send(role.getPresence().createCopy()); } } } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } } } } } } }
src/java/org/jivesoftware/messenger/muc/spi/MUCUserImpl.java
/** * $RCSfile$ * $Revision$ * $Date$ * * Copyright (C) 2004 Jive Software. All rights reserved. * * This software is published under the terms of the GNU Public License (GPL), * a copy of which is included in this distribution. */ package org.jivesoftware.messenger.muc.spi; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import org.dom4j.Element; import org.jivesoftware.messenger.muc.*; import org.jivesoftware.util.*; import org.jivesoftware.messenger.*; import org.jivesoftware.messenger.auth.UnauthorizedException; import org.jivesoftware.messenger.user.UserAlreadyExistsException; import org.jivesoftware.messenger.user.UserNotFoundException; import org.xmpp.packet.*; /** * Implementation of MUCUser. There will be a MUCUser per user that is connected to one or more * rooms. A MUCUser contains a collection of MUCRoles for each room where the user has joined. * * @author Gaston Dombiak */ public class MUCUserImpl implements MUCUser { /** The chat server this user belongs to. */ private MultiUserChatServer server; /** Real system XMPPAddress for the user. */ private JID realjid; /** Table: key roomName.toLowerCase(); value MUCRole. */ private Map<String, MUCRole> roles = new ConcurrentHashMap<String, MUCRole>(); /** Deliver packets to users. */ private PacketRouter router; /** * Time of last packet sent. */ private long lastPacketTime; /** * Create a new chat user. * * @param chatserver the server the user belongs to. * @param packetRouter the router for sending packets from this user. * @param jid the real address of the user */ MUCUserImpl(MultiUserChatServerImpl chatserver, PacketRouter packetRouter, JID jid) { this.realjid = jid; this.router = packetRouter; this.server = chatserver; } public long getID() { return -1; } public MUCRole getRole(String roomName) throws NotFoundException { MUCRole role = roles.get(roomName.toLowerCase()); if (role == null) { throw new NotFoundException(roomName); } return role; } public Iterator<MUCRole> getRoles() { return Collections.unmodifiableCollection(roles.values()).iterator(); } public void removeRole(String roomName) { roles.remove(roomName.toLowerCase()); } public long getLastPacketTime() { return lastPacketTime; } /** * Generate a conflict packet to indicate that the nickname being requested/used is already in * use by another user. * * @param packet the packet to be bounced. */ private void sendErrorPacket(Packet packet, PacketError.Condition error) { if (packet instanceof IQ) { IQ reply = IQ.createResultIQ((IQ) packet); reply.setChildElement(((IQ) packet).getChildElement().createCopy()); reply.setError(error); router.route(reply); } else { Packet reply = packet.createCopy(); reply.setError(error); reply.setFrom(packet.getTo()); reply.setTo(packet.getFrom()); router.route(reply); } } public JID getAddress() { return realjid; } public void process(Packet packet) throws UnauthorizedException, PacketException { if (packet instanceof IQ) { process((IQ)packet); } else if (packet instanceof Message) { process((Message)packet); } else if (packet instanceof Presence) { process((Presence)packet); } } /** * This method does all packet routing in the chat server. Packet routing is actually very * simple: * * <ul> * <li>Discover the room the user is talking to (server packets are dropped)</li> * <li>If the room is not registered and this is a presence "available" packet, try to join the * room</li> * <li>If the room is registered, and presence "unavailable" leave the room</li> * <li>Otherwise, rewrite the sender address and send to the room.</li> * </ul> * * @param packet The packet to route. */ public void process(Message packet) { // Ignore messages of type ERROR sent to a room if (Message.Type.error == packet.getType()) { return; } lastPacketTime = System.currentTimeMillis(); JID recipient = packet.getTo(); String group = recipient.getNode(); if (group == null) { // Ignore packets to the groupchat server // In the future, we'll need to support TYPE_IQ queries to the server for MUC Log.info(LocaleUtils.getLocalizedString("muc.error.not-supported") + " " + packet.toString()); } else { MUCRole role = roles.get(group.toLowerCase()); if (role == null) { if (server.hasChatRoom(group)) { boolean declinedInvitation = false; Element userInfo = null; if (Message.Type.normal == packet.getType()) { // An user that is not an occupant could be declining an invitation userInfo = packet.getChildElement( "x", "http://jabber.org/protocol/muc#user"); if (userInfo != null && userInfo.element("decline") != null) { // A user has declined an invitation to a room // WARNING: Potential fraud if someone fakes the "from" of the // message with the JID of a member and sends a "decline" declinedInvitation = true; } } if (declinedInvitation) { Element info = userInfo.element("decline"); server.getChatRoom(group).sendInvitationRejection( new JID(info.attributeValue("to")), info.elementTextTrim("reason"), packet.getFrom()); } else { // The sender is not an occupant of the room sendErrorPacket(packet, PacketError.Condition.not_acceptable); } } else { // The sender is not an occupant of a NON-EXISTENT room!!! sendErrorPacket(packet, PacketError.Condition.recipient_unavailable); } } else { // Check and reject conflicting packets with conflicting roles // In other words, another user already has this nickname if (!role.getChatUser().getAddress().equals(packet.getFrom())) { sendErrorPacket(packet, PacketError.Condition.conflict); } else { try { if (packet.getSubject() != null && packet.getSubject().trim().length() > 0 && Message.Type.groupchat == packet.getType()) { // An occupant is trying to change the room's subject role.getChatRoom().changeSubject(packet, role); } else { // An occupant is trying to send a private, send public message, // invite someone to the room or reject an invitation Message.Type type = packet.getType(); String resource = packet.getTo().getResource(); if (resource == null || resource.trim().length() == 0) { resource = null; } if (resource == null && Message.Type.groupchat == type) { // An occupant is trying to send a public message role.getChatRoom().sendPublicMessage(packet, role); } else if (resource != null && (Message.Type.chat == type || Message.Type.normal == type)) { // An occupant is trying to send a private message role.getChatRoom().sendPrivatePacket(packet, role); } else if (resource == null && Message.Type.normal == type) { // An occupant could be sending an invitation or declining an // invitation Element userInfo = packet.getChildElement( "x", "http://jabber.org/protocol/muc#user"); // Real real real UGLY TRICK!!! Will and MUST be solved when // persistence will be added. Replace locking with transactions! MUCRoomImpl room = (MUCRoomImpl) role.getChatRoom(); if (userInfo != null && userInfo.element("invite") != null) { // An occupant is sending an invitation Element info = userInfo.element("invite"); // Add the user as a member of the room if the room is // members only if (room.isMembersOnly()) { room.lock.writeLock().lock(); try { room.addMember(info.attributeValue("to"), null, role); } finally { room.lock.writeLock().unlock(); } } // Try to keep the list of extensions sent together with the // message invitation. These extensions will be sent to the // invitee. List<Element> extensions = new ArrayList<Element>(packet .getElement().elements()); extensions.remove(userInfo); // Send the invitation to the user room.sendInvitation(new JID(info.attributeValue("to")), info.elementTextTrim("reason"), role, extensions); } else if (userInfo != null && userInfo.element("decline") != null) { // An occupant has declined an invitation Element info = userInfo.element("decline"); room.sendInvitationRejection(new JID(info.attributeValue("to")), info.elementTextTrim("reason"), packet.getFrom()); } else { sendErrorPacket(packet, PacketError.Condition.bad_request); } } else { sendErrorPacket(packet, PacketError.Condition.bad_request); } } } catch (ForbiddenException e) { sendErrorPacket(packet, PacketError.Condition.forbidden); } catch (NotFoundException e) { sendErrorPacket(packet, PacketError.Condition.recipient_unavailable); } catch (ConflictException e) { sendErrorPacket(packet, PacketError.Condition.conflict); } } } } } public void process(IQ packet) { // Ignore IQs of type ERROR or RESULT sent to a room if (IQ.Type.error == packet.getType() || IQ.Type.result == packet.getType()) { return; } lastPacketTime = System.currentTimeMillis(); JID recipient = packet.getTo(); String group = recipient.getNode(); if (group == null) { // Ignore packets to the groupchat server // In the future, we'll need to support TYPE_IQ queries to the server for MUC Log.info(LocaleUtils.getLocalizedString("muc.error.not-supported") + " " + packet.toString()); } else { MUCRole role = roles.get(group.toLowerCase()); if (role == null) { // TODO: send error message to user (can't send packets to group you haven't // joined) } else { // Check and reject conflicting packets with conflicting roles // In other words, another user already has this nickname if (!role.getChatUser().getAddress().equals(packet.getFrom())) { sendErrorPacket(packet, PacketError.Condition.conflict); } else { try { Element query = packet.getElement().element("query"); if (query != null && "http://jabber.org/protocol/muc#owner".equals(query.getNamespaceURI())) { role.getChatRoom().getIQOwnerHandler().handleIQ(packet, role); } else if (query != null && "http://jabber.org/protocol/muc#admin".equals(query.getNamespaceURI())) { role.getChatRoom().getIQAdminHandler().handleIQ(packet, role); } else { if (packet.getTo().getResource() != null) { // User is sending an IQ packet to another room occupant role.getChatRoom().sendPrivatePacket(packet, role); } else { sendErrorPacket(packet, PacketError.Condition.bad_request); } } } catch (ForbiddenException e) { sendErrorPacket(packet, PacketError.Condition.forbidden); } catch (NotFoundException e) { sendErrorPacket(packet, PacketError.Condition.recipient_unavailable); } catch (ConflictException e) { sendErrorPacket(packet, PacketError.Condition.conflict); } catch (NotAllowedException e) { sendErrorPacket(packet, PacketError.Condition.not_allowed); } } } } } public void process(Presence packet) { // Ignore presences of type ERROR sent to a room if (Presence.Type.error == packet.getType()) { return; } lastPacketTime = System.currentTimeMillis(); JID recipient = packet.getTo(); String group = recipient.getNode(); if (group == null) { if (Presence.Type.unavailable == packet.getType()) { server.removeUser(packet.getFrom()); } } else { MUCRole role = roles.get(group.toLowerCase()); if (role == null) { // If we're not already in a room, we either are joining it or it's not // properly addressed and we drop it silently if (recipient.getResource() != null && recipient.getResource().trim().length() > 0) { if (packet.isAvailable()) { try { // Get or create the room MUCRoom room = server.getChatRoom(group, packet.getFrom()); // User must support MUC in order to create a room Element mucInfo = packet.getChildElement("x", "http://jabber.org/protocol/muc"); HistoryRequest historyRequest = null; String password = null; // Check for password & requested history if client supports MUC if (mucInfo != null) { password = mucInfo.elementTextTrim("password"); if (mucInfo.element("history") != null) { historyRequest = new HistoryRequest(mucInfo); } } // The user joins the room role = room.joinRoom(recipient.getResource().trim(), password, historyRequest, this, packet.createCopy()); roles.put(group.toLowerCase(), role); // If the client that created the room is non-MUC compliant then // unlock the room thus creating an "instant" room if (mucInfo == null && room.isLocked() && !room.isManuallyLocked()) { room.unlock(role); } } catch (UnauthorizedException e) { sendErrorPacket(packet, PacketError.Condition.not_authorized); } catch (ServiceUnavailableException e) { sendErrorPacket(packet, PacketError.Condition.service_unavailable); } catch (UserAlreadyExistsException e) { sendErrorPacket(packet, PacketError.Condition.conflict); } catch (RoomLockedException e) { sendErrorPacket(packet, PacketError.Condition.recipient_unavailable); } catch (ForbiddenException e) { sendErrorPacket(packet, PacketError.Condition.forbidden); } catch (RegistrationRequiredException e) { sendErrorPacket(packet, PacketError.Condition.registration_required); } catch (ConflictException e) { sendErrorPacket(packet, PacketError.Condition.conflict); } catch (NotAcceptableException e) { sendErrorPacket(packet, PacketError.Condition.not_acceptable); } catch (NotAllowedException e) { sendErrorPacket(packet, PacketError.Condition.not_allowed); } } else { // TODO: send error message to user (can't send presence to group you // haven't joined) } } else { if (packet.isAvailable()) { // A resource is required in order to join a room sendErrorPacket(packet, PacketError.Condition.bad_request); } // TODO: send error message to user (can't send packets to group you haven't // joined) } } else { // Check and reject conflicting packets with conflicting roles // In other words, another user already has this nickname if (!role.getChatUser().getAddress().equals(packet.getFrom())) { sendErrorPacket(packet, PacketError.Condition.conflict); } else { if (Presence.Type.unavailable == packet.getType()) { try { roles.remove(group.toLowerCase()); role.getChatRoom().leaveRoom(role.getNickname()); } catch (UserNotFoundException e) { // Do nothing since the users has already left the room } catch (Exception e) { Log.error(e); } } else { try { String resource = (recipient.getResource() == null || recipient.getResource().trim().length() == 0 ? null : recipient.getResource().trim()); if (resource == null || role.getNickname().equalsIgnoreCase(resource)) { // Occupant has changed his availability status role.setPresence(packet.createCopy()); role.getChatRoom().send(role.getPresence().createCopy()); } else { // Occupant has changed his nickname. Send two presences // to each room occupant // Check if occupants are allowed to change their nicknames if (!role.getChatRoom().canChangeNickname()) { sendErrorPacket(packet, PacketError.Condition.not_acceptable); } // Answer a conflic error if the new nickname is taken else if (role.getChatRoom().hasOccupant(resource)) { sendErrorPacket(packet, PacketError.Condition.conflict); } else { // Send "unavailable" presence for the old nickname Presence presence = role.getPresence().createCopy(); // Switch the presence to OFFLINE presence.setType(Presence.Type.unavailable); presence.setStatus(null); // Add the new nickname and status 303 as properties Element frag = presence.getChildElement("x", "http://jabber.org/protocol/muc#user"); frag.element("item").addAttribute("nick", resource); frag.addElement("status").addAttribute("code", "303"); role.getChatRoom().send(presence); // Send availability presence for the new nickname String oldNick = role.getNickname(); role.setPresence(packet.createCopy()); role.changeNickname(resource); role.getChatRoom().nicknameChanged(oldNick, resource); role.getChatRoom().send(role.getPresence().createCopy()); } } } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } } } } } } }
Only ignore IQ result packets sent to the room itself. IQ result packets sent between room occupants should be processed. git-svn-id: 036f06d8526d2d198eab1b7c5596fd12295db076@3039 b35dd754-fafc-0310-a699-88a17e54d16e
src/java/org/jivesoftware/messenger/muc/spi/MUCUserImpl.java
Only ignore IQ result packets sent to the room itself. IQ result packets sent between room occupants should be processed.
<ide><path>rc/java/org/jivesoftware/messenger/muc/spi/MUCUserImpl.java <ide> <ide> public void process(IQ packet) { <ide> // Ignore IQs of type ERROR or RESULT sent to a room <del> if (IQ.Type.error == packet.getType() || IQ.Type.result == packet.getType()) { <add> if (IQ.Type.error == packet.getType()) { <ide> return; <ide> } <ide> lastPacketTime = System.currentTimeMillis(); <ide> if (role == null) { <ide> // TODO: send error message to user (can't send packets to group you haven't <ide> // joined) <add> } <add> else if (IQ.Type.result == packet.getType()) { <add> // Only process IQ result packet if it's a private packet sent to another <add> // room occupant <add> if (packet.getTo().getResource() != null) { <add> try { <add> // User is sending an IQ result packet to another room occupant <add> role.getChatRoom().sendPrivatePacket(packet, role); <add> } <add> catch (NotFoundException e) { <add> // Do nothing. No error will be sent to the sender of the IQ result packet <add> } <add> } <ide> } <ide> else { <ide> // Check and reject conflicting packets with conflicting roles
Java
apache-2.0
a8de4747a5bbc6f7f01ab6a4331f03a40cfa654b
0
OpenConext/OpenConext-dashboard,cybera/OpenConext-dashboard,cybera/OpenConext-dashboard,OpenConext/OpenConext-dashboard,cybera/OpenConext-dashboard,OpenConext/OpenConext-dashboard,OpenConext/OpenConext-dashboard,cybera/OpenConext-dashboard
/* * Copyright 2012 SURFnet bv, The Netherlands * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.surfnet.coin.selfservice.provisioner; import java.util.List; import javax.annotation.Resource; import nl.surfnet.coin.janus.Janus; import nl.surfnet.coin.janus.domain.JanusEntity; import nl.surfnet.coin.selfservice.domain.CoinAuthority; import nl.surfnet.coin.selfservice.domain.CoinUser; import nl.surfnet.coin.selfservice.domain.IdentityProvider; import nl.surfnet.coin.selfservice.service.IdentityProviderService; import nl.surfnet.coin.selfservice.util.PersonAttributeUtil; import nl.surfnet.spring.security.opensaml.Provisioner; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.opensaml.saml2.core.Assertion; import org.opensaml.saml2.core.Attribute; import org.opensaml.saml2.core.AttributeStatement; import org.opensaml.saml2.core.AuthenticatingAuthority; import org.opensaml.saml2.core.AuthnStatement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.userdetails.UserDetails; import static nl.surfnet.coin.selfservice.domain.CoinAuthority.Authority.ROLE_USER; /** * implementation to return UserDetails from a SAML Assertion */ public class SAMLProvisioner implements Provisioner { private static final String DISPLAY_NAME = "urn:mace:dir:attribute-def:displayName"; private static final String EMAIL = "urn:mace:dir:attribute-def:mail"; private static final String SCHAC_HOME = "urn:mace:terena.org:attribute-def:schacHomeOrganization"; private String uuidAttribute = "urn:oid:1.3.6.1.4.1.1076.20.40.40.1"; private static final Logger LOG = LoggerFactory.getLogger(SAMLProvisioner.class); private IdentityProviderService identityProviderService; @Resource(name = "janusClient") private Janus janusClient; @Override public UserDetails provisionUser(Assertion assertion) { CoinUser coinUser = new CoinUser(); final String idpId = getAuthenticatingAuthority(assertion); coinUser.setIdp(idpId); coinUser.setInstitutionId(getInstitutionId(idpId)); for (IdentityProvider idp : identityProviderService.getInstituteIdentityProviders(coinUser.getInstitutionId())) { coinUser.addInstitutionIdp(idp); } // Add the one the user is currently identified by if it's not in the list // already. if (coinUser.getInstitutionIdps().isEmpty()) { IdentityProvider idp = getInstitutionIdP(idpId); coinUser.addInstitutionIdp(idp); } coinUser.setUid(getValueFromAttributeStatements(assertion, uuidAttribute)); coinUser.setDisplayName(getValueFromAttributeStatements(assertion, DISPLAY_NAME)); coinUser.setEmail(getValueFromAttributeStatements(assertion, EMAIL)); coinUser.setSchacHomeOrganization(getValueFromAttributeStatements(assertion, SCHAC_HOME)); coinUser.addAuthority(new CoinAuthority(ROLE_USER)); coinUser.setAttributeMap(PersonAttributeUtil.getAttributesAsMap(assertion)); return coinUser; } private String getInstitutionId(String idpId) { final IdentityProvider identityProvider = identityProviderService.getIdentityProvider(idpId); if (identityProvider != null) { final String institutionId = identityProvider.getInstitutionId(); if (!StringUtils.isBlank(institutionId)) { return institutionId; } } //corner case, but possible return null; } private IdentityProvider getInstitutionIdP(String idpId) { IdentityProvider idp = identityProviderService.getIdentityProvider(idpId); if (idp == null) { final JanusEntity entity = janusClient.getEntity(idpId); if (entity == null) { idp = new IdentityProvider(idpId, null, idpId); } else { idp = new IdentityProvider(entity.getEntityId(), null, entity.getPrettyName()); } } return idp; } private String getAuthenticatingAuthority(final Assertion assertion) { final List<AuthnStatement> authnStatements = assertion.getAuthnStatements(); for (AuthnStatement as : authnStatements) { final List<AuthenticatingAuthority> authorities = as.getAuthnContext().getAuthenticatingAuthorities(); for (AuthenticatingAuthority aa : authorities) { if (StringUtils.isNotBlank(aa.getURI())) { return aa.getURI(); } } } throw new RuntimeException("No AuthenticatingAuthority present in the Assertion:" + ToStringBuilder.reflectionToString(assertion)); } private String getValueFromAttributeStatements(final Assertion assertion, final String name) { final List<AttributeStatement> attributeStatements = assertion.getAttributeStatements(); for (AttributeStatement attributeStatement : attributeStatements) { final List<Attribute> attributes = attributeStatement.getAttributes(); for (Attribute attribute : attributes) { if (name.equals(attribute.getName())) { return attribute.getAttributeValues().get(0).getDOM().getFirstChild().getNodeValue(); } } } return ""; } public void setIdentityProviderService(IdentityProviderService identityProviderService) { this.identityProviderService = identityProviderService; } public void setUuidAttribute(String uuidAttribute) { this.uuidAttribute = uuidAttribute; } }
coin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/provisioner/SAMLProvisioner.java
/* * Copyright 2012 SURFnet bv, The Netherlands * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.surfnet.coin.selfservice.provisioner; import static nl.surfnet.coin.selfservice.domain.CoinAuthority.Authority.ROLE_USER; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.List; import javax.annotation.Resource; import nl.surfnet.coin.janus.Janus; import nl.surfnet.coin.janus.domain.JanusEntity; import nl.surfnet.coin.selfservice.domain.CoinAuthority; import nl.surfnet.coin.selfservice.domain.CoinUser; import nl.surfnet.coin.selfservice.domain.IdentityProvider; import nl.surfnet.coin.selfservice.service.IdentityProviderService; import nl.surfnet.coin.selfservice.util.PersonAttributeUtil; import nl.surfnet.spring.security.opensaml.Provisioner; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.opensaml.saml2.core.Assertion; import org.opensaml.saml2.core.Attribute; import org.opensaml.saml2.core.AttributeStatement; import org.opensaml.saml2.core.AuthenticatingAuthority; import org.opensaml.saml2.core.AuthnStatement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.userdetails.UserDetails; /** * implementation to return UserDetails from a SAML Assertion */ public class SAMLProvisioner implements Provisioner { private static final String DISPLAY_NAME = "urn:mace:dir:attribute-def:displayName"; private static final String EMAIL = "urn:mace:dir:attribute-def:mail"; private static final String SCHAC_HOME = "urn:mace:terena.org:attribute-def:schacHomeOrganization"; private String uuidAttribute = "urn:oid:1.3.6.1.4.1.1076.20.40.40.1"; private static final Logger LOG = LoggerFactory.getLogger(SAMLProvisioner.class); private IdentityProviderService identityProviderService; @Resource(name = "janusClient") private Janus janusClient; @Override public UserDetails provisionUser(Assertion assertion) { CoinUser coinUser = new CoinUser(); final String idpId = getAuthenticatingAuthority(assertion); coinUser.setIdp(idpId); coinUser.setInstitutionId(getInstitutionId(idpId)); for (IdentityProvider idp : identityProviderService.getInstituteIdentityProviders(coinUser.getInstitutionId())) { coinUser.addInstitutionIdp(idp); } // Add the one the user is currently identified by if it's not in the list // already. if (coinUser.getInstitutionIdps().isEmpty()) { IdentityProvider idp = getInstitutionIdP(idpId); coinUser.addInstitutionIdp(idp); } coinUser.setUid(getValueFromAttributeStatements(assertion, uuidAttribute)); coinUser.setDisplayName(getValueFromAttributeStatements(assertion, DISPLAY_NAME)); coinUser.setEmail(getValueFromAttributeStatements(assertion, EMAIL)); coinUser.setSchacHomeOrganization(getValueFromAttributeStatements(assertion, SCHAC_HOME)); coinUser.addAuthority(new CoinAuthority(ROLE_USER)); coinUser.setAttributeMap(PersonAttributeUtil.getAttributesAsMap(assertion)); return coinUser; } private String getInstitutionId(String idpId) { final IdentityProvider identityProvider = identityProviderService.getIdentityProvider(idpId); if (identityProvider != null) { final String institutionId = identityProvider.getInstitutionId(); if (!StringUtils.isBlank(institutionId)) { return institutionId; } } //corner case, but possible return null; } private IdentityProvider getInstitutionIdP(String idpId) { IdentityProvider idp = identityProviderService.getIdentityProvider(idpId); if (idp == null) { final JanusEntity entity = janusClient.getEntity(idpId); if (entity == null) { idp = new IdentityProvider(idpId, null, idpId); } else { idp = new IdentityProvider(entity.getEntityId(), null, entity.getPrettyName()); } } return idp; } private String getAuthenticatingAuthority(final Assertion assertion) { final List<AuthnStatement> authnStatements = assertion.getAuthnStatements(); for (AuthnStatement as : authnStatements) { final List<AuthenticatingAuthority> authorities = as.getAuthnContext().getAuthenticatingAuthorities(); for (AuthenticatingAuthority aa : authorities) { if (StringUtils.isNotBlank(aa.getURI())) { try { return URLDecoder.decode(aa.getURI(), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Machine does not support UTF-8", e); } } } } throw new RuntimeException("No AuthenticatingAuthority present in the Assertion:" + ToStringBuilder.reflectionToString(assertion)); } private String getValueFromAttributeStatements(final Assertion assertion, final String name) { final List<AttributeStatement> attributeStatements = assertion.getAttributeStatements(); for (AttributeStatement attributeStatement : attributeStatements) { final List<Attribute> attributes = attributeStatement.getAttributes(); for (Attribute attribute : attributes) { if (name.equals(attribute.getName())) { return attribute.getAttributeValues().get(0).getDOM().getFirstChild().getNodeValue(); } } } return ""; } public void setIdentityProviderService(IdentityProviderService identityProviderService) { this.identityProviderService = identityProviderService; } public void setUuidAttribute(String uuidAttribute) { this.uuidAttribute = uuidAttribute; } }
Do not decode authenticating authority ('SURFnet%20BV' is a real value)
coin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/provisioner/SAMLProvisioner.java
Do not decode authenticating authority ('SURFnet%20BV' is a real value)
<ide><path>oin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/provisioner/SAMLProvisioner.java <ide> <ide> package nl.surfnet.coin.selfservice.provisioner; <ide> <del>import static nl.surfnet.coin.selfservice.domain.CoinAuthority.Authority.ROLE_USER; <del> <del>import java.io.UnsupportedEncodingException; <del>import java.net.URLDecoder; <ide> import java.util.List; <ide> <ide> import javax.annotation.Resource; <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> import org.springframework.security.core.userdetails.UserDetails; <add> <add>import static nl.surfnet.coin.selfservice.domain.CoinAuthority.Authority.ROLE_USER; <ide> <ide> /** <ide> * implementation to return UserDetails from a SAML Assertion <ide> final List<AuthenticatingAuthority> authorities = as.getAuthnContext().getAuthenticatingAuthorities(); <ide> for (AuthenticatingAuthority aa : authorities) { <ide> if (StringUtils.isNotBlank(aa.getURI())) { <del> try { <del> return URLDecoder.decode(aa.getURI(), "UTF-8"); <del> } catch (UnsupportedEncodingException e) { <del> throw new RuntimeException("Machine does not support UTF-8", e); <del> } <add> return aa.getURI(); <ide> } <ide> } <ide> }
JavaScript
mit
9dfad450650d1ccbb638f7d672bc86466846f033
0
TheGlycerine/Nux
// This shared resource should be implemented as the // required components header within the boot. // It's currently here to assist in development ease. NuxComponentHeader = function __self(){ if(!window.hasOwnProperty('Nux')) { function assign(obj, keyPath, value) { lastKeyIndex = keyPath.length-1; for (var i = 0; i < lastKeyIndex; ++ i) { key = keyPath[i]; if (!(key in obj)) obj[key] = {} obj = obj[key]; } obj[keyPath[lastKeyIndex]] = value; return obj } NuxImplement(arguments); } else { Nux.implement.apply(this, arguments); } // Return an entity used to extend this after import return (function(){ var options = arg(arguments, 0, {}); var method = arg(arguments, 1, null); return { options: options, method: method, chain: function(map, obj) { return NuxComponentHeader.apply(this, arguments) }, meta: function(name, v){ /* Apply meta data about your nux component to add context when in use */ if(!window.hasOwnProperty('Nux')) { console.error('meta method not implemented') } else { Nux.errors.throw(04, 'meta', name); } } }; }).apply(this, arguments); };
src/js/nux/requires/NuxComponentHeader.js
// This shared resource should be implemented as the // required components header within the boot. // It's currently here to assist in development ease. NuxComponentHeader = function(){ if(!window.hasOwnProperty('Nux')) { function assign(obj, keyPath, value) { lastKeyIndex = keyPath.length-1; for (var i = 0; i < lastKeyIndex; ++ i) { key = keyPath[i]; if (!(key in obj)) obj[key] = {} obj = obj[key]; } obj[keyPath[lastKeyIndex]] = value; return obj } NuxImplement(arguments); } else { Nux.implement(arguments); } };
conceptual meta() method
src/js/nux/requires/NuxComponentHeader.js
conceptual meta() method
<ide><path>rc/js/nux/requires/NuxComponentHeader.js <ide> // This shared resource should be implemented as the <ide> // required components header within the boot. <ide> // It's currently here to assist in development ease. <del>NuxComponentHeader = function(){ <add>NuxComponentHeader = function __self(){ <ide> <ide> if(!window.hasOwnProperty('Nux')) { <ide> <ide> obj[key] = {} <ide> obj = obj[key]; <ide> } <add> <ide> obj[keyPath[lastKeyIndex]] = value; <ide> return obj <ide> } <ide> <ide> NuxImplement(arguments); <ide> } else { <del> Nux.implement(arguments); <add> Nux.implement.apply(this, arguments); <ide> } <ide> <add> // Return an entity used to extend this after import <add> return (function(){ <add> var options = arg(arguments, 0, {}); <add> var method = arg(arguments, 1, null); <add> <add> return { <add> options: options, <add> method: method, <add> chain: function(map, obj) { <add> return NuxComponentHeader.apply(this, arguments) <add> <add> }, <add> meta: function(name, v){ <add> /* <add> Apply meta data about your nux component to add <add> context when in use <add> */ <add> if(!window.hasOwnProperty('Nux')) { <add> console.error('meta method not implemented') <add> } else { <add> Nux.errors.throw(04, 'meta', name); <add> } <add> } <add> }; <add> <add> }).apply(this, arguments); <add> <ide> };
JavaScript
mit
7e5322ccf2971dca90fa0cb9d7db91e60e877314
0
camsong/react,facebook/react,camsong/react,facebook/react,facebook/react,facebook/react,facebook/react,camsong/react,camsong/react,camsong/react,camsong/react,facebook/react,facebook/react,camsong/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import LRU from 'lru-cache'; import { isElement, typeOf, ContextConsumer, ContextProvider, ForwardRef, Fragment, Lazy, Memo, Portal, Profiler, StrictMode, Suspense, } from 'react-is'; import { REACT_SUSPENSE_LIST_TYPE as SuspenseList, REACT_TRACING_MARKER_TYPE as TracingMarker, } from 'shared/ReactSymbols'; import { TREE_OPERATION_ADD, TREE_OPERATION_REMOVE, TREE_OPERATION_REMOVE_ROOT, TREE_OPERATION_REORDER_CHILDREN, TREE_OPERATION_SET_SUBTREE_MODE, TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS, TREE_OPERATION_UPDATE_TREE_BASE_DURATION, } from './constants'; import {ElementTypeRoot} from 'react-devtools-shared/src/types'; import { LOCAL_STORAGE_FILTER_PREFERENCES_KEY, LOCAL_STORAGE_OPEN_IN_EDITOR_URL, LOCAL_STORAGE_SHOULD_BREAK_ON_CONSOLE_ERRORS, LOCAL_STORAGE_SHOULD_APPEND_COMPONENT_STACK_KEY, LOCAL_STORAGE_SHOW_INLINE_WARNINGS_AND_ERRORS_KEY, LOCAL_STORAGE_HIDE_CONSOLE_LOGS_IN_STRICT_MODE, } from './constants'; import {ComponentFilterElementType, ElementTypeHostComponent} from './types'; import { ElementTypeClass, ElementTypeForwardRef, ElementTypeFunction, ElementTypeMemo, } from 'react-devtools-shared/src/types'; import {localStorageGetItem, localStorageSetItem} from './storage'; import {meta} from './hydration'; import isArray from './isArray'; import type {ComponentFilter, ElementType} from './types'; import type {LRUCache} from 'react-devtools-shared/src/types'; const cachedDisplayNames: WeakMap<Function, string> = new WeakMap(); // On large trees, encoding takes significant time. // Try to reuse the already encoded strings. const encodedStringCache: LRUCache<string, Array<number>> = new LRU({ max: 1000, }); export function alphaSortKeys( a: string | number | Symbol, b: string | number | Symbol, ): number { if (a.toString() > b.toString()) { return 1; } else if (b.toString() > a.toString()) { return -1; } else { return 0; } } export function getAllEnumerableKeys( obj: Object, ): Set<string | number | Symbol> { const keys = new Set(); let current = obj; while (current != null) { const currentKeys = [ ...Object.keys(current), ...Object.getOwnPropertySymbols(current), ]; const descriptors = Object.getOwnPropertyDescriptors(current); currentKeys.forEach(key => { // $FlowFixMe: key can be a Symbol https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor if (descriptors[key].enumerable) { keys.add(key); } }); current = Object.getPrototypeOf(current); } return keys; } // Mirror https://github.com/facebook/react/blob/7c21bf72ace77094fd1910cc350a548287ef8350/packages/shared/getComponentName.js#L27-L37 export function getWrappedDisplayName( outerType: mixed, innerType: any, wrapperName: string, fallbackName?: string, ): string { const displayName = (outerType: any).displayName; return ( displayName || `${wrapperName}(${getDisplayName(innerType, fallbackName)})` ); } export function getDisplayName( type: Function, fallbackName: string = 'Anonymous', ): string { const nameFromCache = cachedDisplayNames.get(type); if (nameFromCache != null) { return nameFromCache; } let displayName = fallbackName; // The displayName property is not guaranteed to be a string. // It's only safe to use for our purposes if it's a string. // github.com/facebook/react-devtools/issues/803 if (typeof type.displayName === 'string') { displayName = type.displayName; } else if (typeof type.name === 'string' && type.name !== '') { displayName = type.name; } cachedDisplayNames.set(type, displayName); return displayName; } let uidCounter: number = 0; export function getUID(): number { return ++uidCounter; } export function utfDecodeString(array: Array<number>): string { // Avoid spreading the array (e.g. String.fromCodePoint(...array)) // Functions arguments are first placed on the stack before the function is called // which throws a RangeError for large arrays. // See github.com/facebook/react/issues/22293 let string = ''; for (let i = 0; i < array.length; i++) { const char = array[i]; string += String.fromCodePoint(char); } return string; } function surrogatePairToCodePoint( charCode1: number, charCode2: number, ): number { return ((charCode1 & 0x3ff) << 10) + (charCode2 & 0x3ff) + 0x10000; } // Credit for this encoding approach goes to Tim Down: // https://stackoverflow.com/questions/4877326/how-can-i-tell-if-a-string-contains-multibyte-characters-in-javascript export function utfEncodeString(string: string): Array<number> { const cached = encodedStringCache.get(string); if (cached !== undefined) { return cached; } const encoded = []; let i = 0; let charCode; while (i < string.length) { charCode = string.charCodeAt(i); // Handle multibyte unicode characters (like emoji). if ((charCode & 0xf800) === 0xd800) { encoded.push(surrogatePairToCodePoint(charCode, string.charCodeAt(++i))); } else { encoded.push(charCode); } ++i; } encodedStringCache.set(string, encoded); return encoded; } export function printOperationsArray(operations: Array<number>) { // The first two values are always rendererID and rootID const rendererID = operations[0]; const rootID = operations[1]; const logs = [`operations for renderer:${rendererID} and root:${rootID}`]; let i = 2; // Reassemble the string table. const stringTable = [ null, // ID = 0 corresponds to the null string. ]; const stringTableSize = operations[i++]; const stringTableEnd = i + stringTableSize; while (i < stringTableEnd) { const nextLength = operations[i++]; const nextString = utfDecodeString( (operations.slice(i, i + nextLength): any), ); stringTable.push(nextString); i += nextLength; } while (i < operations.length) { const operation = operations[i]; switch (operation) { case TREE_OPERATION_ADD: { const id = ((operations[i + 1]: any): number); const type = ((operations[i + 2]: any): ElementType); i += 3; if (type === ElementTypeRoot) { logs.push(`Add new root node ${id}`); i++; // isStrictModeCompliant i++; // supportsProfiling i++; // supportsStrictMode i++; // hasOwnerMetadata } else { const parentID = ((operations[i]: any): number); i++; i++; // ownerID const displayNameStringID = operations[i]; const displayName = stringTable[displayNameStringID]; i++; i++; // key logs.push( `Add node ${id} (${displayName || 'null'}) as child of ${parentID}`, ); } break; } case TREE_OPERATION_REMOVE: { const removeLength = ((operations[i + 1]: any): number); i += 2; for (let removeIndex = 0; removeIndex < removeLength; removeIndex++) { const id = ((operations[i]: any): number); i += 1; logs.push(`Remove node ${id}`); } break; } case TREE_OPERATION_REMOVE_ROOT: { i += 1; logs.push(`Remove root ${rootID}`); break; } case TREE_OPERATION_SET_SUBTREE_MODE: { const id = operations[i + 1]; const mode = operations[i + 1]; i += 3; logs.push(`Mode ${mode} set for subtree with root ${id}`); break; } case TREE_OPERATION_REORDER_CHILDREN: { const id = ((operations[i + 1]: any): number); const numChildren = ((operations[i + 2]: any): number); i += 3; const children = operations.slice(i, i + numChildren); i += numChildren; logs.push(`Re-order node ${id} children ${children.join(',')}`); break; } case TREE_OPERATION_UPDATE_TREE_BASE_DURATION: // Base duration updates are only sent while profiling is in progress. // We can ignore them at this point. // The profiler UI uses them lazily in order to generate the tree. i += 3; break; case TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS: const id = operations[i + 1]; const numErrors = operations[i + 2]; const numWarnings = operations[i + 3]; i += 4; logs.push( `Node ${id} has ${numErrors} errors and ${numWarnings} warnings`, ); break; default: throw Error(`Unsupported Bridge operation "${operation}"`); } } console.log(logs.join('\n ')); } export function getDefaultComponentFilters(): Array<ComponentFilter> { return [ { type: ComponentFilterElementType, value: ElementTypeHostComponent, isEnabled: true, }, ]; } export function getSavedComponentFilters(): Array<ComponentFilter> { try { const raw = localStorageGetItem(LOCAL_STORAGE_FILTER_PREFERENCES_KEY); if (raw != null) { return JSON.parse(raw); } } catch (error) {} return getDefaultComponentFilters(); } export function saveComponentFilters( componentFilters: Array<ComponentFilter>, ): void { localStorageSetItem( LOCAL_STORAGE_FILTER_PREFERENCES_KEY, JSON.stringify(componentFilters), ); } export function getAppendComponentStack(): boolean { try { const raw = localStorageGetItem( LOCAL_STORAGE_SHOULD_APPEND_COMPONENT_STACK_KEY, ); if (raw != null) { return JSON.parse(raw); } } catch (error) {} return true; } export function setAppendComponentStack(value: boolean): void { localStorageSetItem( LOCAL_STORAGE_SHOULD_APPEND_COMPONENT_STACK_KEY, JSON.stringify(value), ); } export function getBreakOnConsoleErrors(): boolean { try { const raw = localStorageGetItem( LOCAL_STORAGE_SHOULD_BREAK_ON_CONSOLE_ERRORS, ); if (raw != null) { return JSON.parse(raw); } } catch (error) {} return false; } export function setBreakOnConsoleErrors(value: boolean): void { localStorageSetItem( LOCAL_STORAGE_SHOULD_BREAK_ON_CONSOLE_ERRORS, JSON.stringify(value), ); } export function getHideConsoleLogsInStrictMode(): boolean { try { const raw = localStorageGetItem( LOCAL_STORAGE_HIDE_CONSOLE_LOGS_IN_STRICT_MODE, ); if (raw != null) { return JSON.parse(raw); } } catch (error) {} return false; } export function sethideConsoleLogsInStrictMode(value: boolean): void { localStorageSetItem( LOCAL_STORAGE_HIDE_CONSOLE_LOGS_IN_STRICT_MODE, JSON.stringify(value), ); } export function getShowInlineWarningsAndErrors(): boolean { try { const raw = localStorageGetItem( LOCAL_STORAGE_SHOW_INLINE_WARNINGS_AND_ERRORS_KEY, ); if (raw != null) { return JSON.parse(raw); } } catch (error) {} return true; } export function setShowInlineWarningsAndErrors(value: boolean): void { localStorageSetItem( LOCAL_STORAGE_SHOW_INLINE_WARNINGS_AND_ERRORS_KEY, JSON.stringify(value), ); } export function getDefaultOpenInEditorURL(): string { return typeof process.env.EDITOR_URL === 'string' ? process.env.EDITOR_URL : ''; } export function getOpenInEditorURL(): string { try { const raw = localStorageGetItem(LOCAL_STORAGE_OPEN_IN_EDITOR_URL); if (raw != null) { return JSON.parse(raw); } } catch (error) {} return getDefaultOpenInEditorURL(); } export function separateDisplayNameAndHOCs( displayName: string | null, type: ElementType, ): [string | null, Array<string> | null] { if (displayName === null) { return [null, null]; } let hocDisplayNames = null; switch (type) { case ElementTypeClass: case ElementTypeForwardRef: case ElementTypeFunction: case ElementTypeMemo: if (displayName.indexOf('(') >= 0) { const matches = displayName.match(/[^()]+/g); if (matches != null) { displayName = matches.pop(); hocDisplayNames = matches; } } break; default: break; } return [displayName, hocDisplayNames]; } // Pulled from react-compat // https://github.com/developit/preact-compat/blob/7c5de00e7c85e2ffd011bf3af02899b63f699d3a/src/index.js#L349 export function shallowDiffers(prev: Object, next: Object): boolean { for (const attribute in prev) { if (!(attribute in next)) { return true; } } for (const attribute in next) { if (prev[attribute] !== next[attribute]) { return true; } } return false; } export function getInObject(object: Object, path: Array<string | number>): any { return path.reduce((reduced: Object, attr: any): any => { if (reduced) { if (hasOwnProperty.call(reduced, attr)) { return reduced[attr]; } if (typeof reduced[Symbol.iterator] === 'function') { // Convert iterable to array and return array[index] // // TRICKY // Don't use [...spread] syntax for this purpose. // This project uses @babel/plugin-transform-spread in "loose" mode which only works with Array values. // Other types (e.g. typed arrays, Sets) will not spread correctly. return Array.from(reduced)[attr]; } } return null; }, object); } export function deletePathInObject( object: Object, path: Array<string | number>, ) { const length = path.length; const last = path[length - 1]; if (object != null) { const parent = getInObject(object, path.slice(0, length - 1)); if (parent) { if (isArray(parent)) { parent.splice(((last: any): number), 1); } else { delete parent[last]; } } } } export function renamePathInObject( object: Object, oldPath: Array<string | number>, newPath: Array<string | number>, ) { const length = oldPath.length; if (object != null) { const parent = getInObject(object, oldPath.slice(0, length - 1)); if (parent) { const lastOld = oldPath[length - 1]; const lastNew = newPath[length - 1]; parent[lastNew] = parent[lastOld]; if (isArray(parent)) { parent.splice(((lastOld: any): number), 1); } else { delete parent[lastOld]; } } } } export function setInObject( object: Object, path: Array<string | number>, value: any, ) { const length = path.length; const last = path[length - 1]; if (object != null) { const parent = getInObject(object, path.slice(0, length - 1)); if (parent) { parent[last] = value; } } } export type DataType = | 'array' | 'array_buffer' | 'bigint' | 'boolean' | 'data_view' | 'date' | 'function' | 'html_all_collection' | 'html_element' | 'infinity' | 'iterator' | 'opaque_iterator' | 'nan' | 'null' | 'number' | 'object' | 'react_element' | 'regexp' | 'string' | 'symbol' | 'typed_array' | 'undefined' | 'unknown'; /** * Get a enhanced/artificial type string based on the object instance */ export function getDataType(data: Object): DataType { if (data === null) { return 'null'; } else if (data === undefined) { return 'undefined'; } if (isElement(data)) { return 'react_element'; } if (typeof HTMLElement !== 'undefined' && data instanceof HTMLElement) { return 'html_element'; } const type = typeof data; switch (type) { case 'bigint': return 'bigint'; case 'boolean': return 'boolean'; case 'function': return 'function'; case 'number': if (Number.isNaN(data)) { return 'nan'; } else if (!Number.isFinite(data)) { return 'infinity'; } else { return 'number'; } case 'object': if (isArray(data)) { return 'array'; } else if (ArrayBuffer.isView(data)) { return hasOwnProperty.call(data.constructor, 'BYTES_PER_ELEMENT') ? 'typed_array' : 'data_view'; } else if (data.constructor && data.constructor.name === 'ArrayBuffer') { // HACK This ArrayBuffer check is gross; is there a better way? // We could try to create a new DataView with the value. // If it doesn't error, we know it's an ArrayBuffer, // but this seems kind of awkward and expensive. return 'array_buffer'; } else if (typeof data[Symbol.iterator] === 'function') { const iterator = data[Symbol.iterator](); if (!iterator) { // Proxies might break assumptoins about iterators. // See github.com/facebook/react/issues/21654 } else { return iterator === data ? 'opaque_iterator' : 'iterator'; } } else if (data.constructor && data.constructor.name === 'RegExp') { return 'regexp'; } else { const toStringValue = Object.prototype.toString.call(data); if (toStringValue === '[object Date]') { return 'date'; } else if (toStringValue === '[object HTMLAllCollection]') { return 'html_all_collection'; } } return 'object'; case 'string': return 'string'; case 'symbol': return 'symbol'; case 'undefined': if ( Object.prototype.toString.call(data) === '[object HTMLAllCollection]' ) { return 'html_all_collection'; } return 'undefined'; default: return 'unknown'; } } export function getDisplayNameForReactElement( element: React$Element<any>, ): string | null { const elementType = typeOf(element); switch (elementType) { case ContextConsumer: return 'ContextConsumer'; case ContextProvider: return 'ContextProvider'; case ForwardRef: return 'ForwardRef'; case Fragment: return 'Fragment'; case Lazy: return 'Lazy'; case Memo: return 'Memo'; case Portal: return 'Portal'; case Profiler: return 'Profiler'; case StrictMode: return 'StrictMode'; case Suspense: return 'Suspense'; case SuspenseList: return 'SuspenseList'; case TracingMarker: return 'TracingMarker'; default: const {type} = element; if (typeof type === 'string') { return type; } else if (typeof type === 'function') { return getDisplayName(type, 'Anonymous'); } else if (type != null) { return 'NotImplementedInDevtools'; } else { return 'Element'; } } } const MAX_PREVIEW_STRING_LENGTH = 50; function truncateForDisplay( string: string, length: number = MAX_PREVIEW_STRING_LENGTH, ) { if (string.length > length) { return string.substr(0, length) + '…'; } else { return string; } } // Attempts to mimic Chrome's inline preview for values. // For example, the following value... // { // foo: 123, // bar: "abc", // baz: [true, false], // qux: { ab: 1, cd: 2 } // }; // // Would show a preview of... // {foo: 123, bar: "abc", baz: Array(2), qux: {…}} // // And the following value... // [ // 123, // "abc", // [true, false], // { foo: 123, bar: "abc" } // ]; // // Would show a preview of... // [123, "abc", Array(2), {…}] export function formatDataForPreview( data: any, showFormattedValue: boolean, ): string { if (data != null && hasOwnProperty.call(data, meta.type)) { return showFormattedValue ? data[meta.preview_long] : data[meta.preview_short]; } const type = getDataType(data); switch (type) { case 'html_element': return `<${truncateForDisplay(data.tagName.toLowerCase())} />`; case 'function': return truncateForDisplay( `ƒ ${typeof data.name === 'function' ? '' : data.name}() {}`, ); case 'string': return `"${data}"`; case 'bigint': return truncateForDisplay(data.toString() + 'n'); case 'regexp': return truncateForDisplay(data.toString()); case 'symbol': return truncateForDisplay(data.toString()); case 'react_element': return `<${truncateForDisplay( getDisplayNameForReactElement(data) || 'Unknown', )} />`; case 'array_buffer': return `ArrayBuffer(${data.byteLength})`; case 'data_view': return `DataView(${data.buffer.byteLength})`; case 'array': if (showFormattedValue) { let formatted = ''; for (let i = 0; i < data.length; i++) { if (i > 0) { formatted += ', '; } formatted += formatDataForPreview(data[i], false); if (formatted.length > MAX_PREVIEW_STRING_LENGTH) { // Prevent doing a lot of unnecessary iteration... break; } } return `[${truncateForDisplay(formatted)}]`; } else { const length = hasOwnProperty.call(data, meta.size) ? data[meta.size] : data.length; return `Array(${length})`; } case 'typed_array': const shortName = `${data.constructor.name}(${data.length})`; if (showFormattedValue) { let formatted = ''; for (let i = 0; i < data.length; i++) { if (i > 0) { formatted += ', '; } formatted += data[i]; if (formatted.length > MAX_PREVIEW_STRING_LENGTH) { // Prevent doing a lot of unnecessary iteration... break; } } return `${shortName} [${truncateForDisplay(formatted)}]`; } else { return shortName; } case 'iterator': const name = data.constructor.name; if (showFormattedValue) { // TRICKY // Don't use [...spread] syntax for this purpose. // This project uses @babel/plugin-transform-spread in "loose" mode which only works with Array values. // Other types (e.g. typed arrays, Sets) will not spread correctly. const array = Array.from(data); let formatted = ''; for (let i = 0; i < array.length; i++) { const entryOrEntries = array[i]; if (i > 0) { formatted += ', '; } // TRICKY // Browsers display Maps and Sets differently. // To mimic their behavior, detect if we've been given an entries tuple. // Map(2) {"abc" => 123, "def" => 123} // Set(2) {"abc", 123} if (isArray(entryOrEntries)) { const key = formatDataForPreview(entryOrEntries[0], true); const value = formatDataForPreview(entryOrEntries[1], false); formatted += `${key} => ${value}`; } else { formatted += formatDataForPreview(entryOrEntries, false); } if (formatted.length > MAX_PREVIEW_STRING_LENGTH) { // Prevent doing a lot of unnecessary iteration... break; } } return `${name}(${data.size}) {${truncateForDisplay(formatted)}}`; } else { return `${name}(${data.size})`; } case 'opaque_iterator': { return data[Symbol.toStringTag]; } case 'date': return data.toString(); case 'object': if (showFormattedValue) { const keys = Array.from(getAllEnumerableKeys(data)).sort(alphaSortKeys); let formatted = ''; for (let i = 0; i < keys.length; i++) { const key = keys[i]; if (i > 0) { formatted += ', '; } formatted += `${key.toString()}: ${formatDataForPreview( data[key], false, )}`; if (formatted.length > MAX_PREVIEW_STRING_LENGTH) { // Prevent doing a lot of unnecessary iteration... break; } } return `{${truncateForDisplay(formatted)}}`; } else { return '{…}'; } case 'boolean': case 'number': case 'infinity': case 'nan': case 'null': case 'undefined': return data; default: try { return truncateForDisplay(String(data)); } catch (error) { return 'unserializable'; } } }
packages/react-devtools-shared/src/utils.js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import LRU from 'lru-cache'; import { isElement, typeOf, ContextConsumer, ContextProvider, ForwardRef, Fragment, Lazy, Memo, Portal, Profiler, StrictMode, Suspense, } from 'react-is'; import { REACT_SUSPENSE_LIST_TYPE as SuspenseList, REACT_TRACING_MARKER_TYPE as TracingMarker, } from 'shared/ReactSymbols'; import { TREE_OPERATION_ADD, TREE_OPERATION_REMOVE, TREE_OPERATION_REMOVE_ROOT, TREE_OPERATION_REORDER_CHILDREN, TREE_OPERATION_SET_SUBTREE_MODE, TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS, TREE_OPERATION_UPDATE_TREE_BASE_DURATION, } from './constants'; import {ElementTypeRoot} from 'react-devtools-shared/src/types'; import { LOCAL_STORAGE_FILTER_PREFERENCES_KEY, LOCAL_STORAGE_OPEN_IN_EDITOR_URL, LOCAL_STORAGE_SHOULD_BREAK_ON_CONSOLE_ERRORS, LOCAL_STORAGE_SHOULD_APPEND_COMPONENT_STACK_KEY, LOCAL_STORAGE_SHOW_INLINE_WARNINGS_AND_ERRORS_KEY, LOCAL_STORAGE_HIDE_CONSOLE_LOGS_IN_STRICT_MODE, } from './constants'; import {ComponentFilterElementType, ElementTypeHostComponent} from './types'; import { ElementTypeClass, ElementTypeForwardRef, ElementTypeFunction, ElementTypeMemo, } from 'react-devtools-shared/src/types'; import {localStorageGetItem, localStorageSetItem} from './storage'; import {meta} from './hydration'; import isArray from './isArray'; import type {ComponentFilter, ElementType} from './types'; import type {LRUCache} from 'react-devtools-shared/src/types'; const cachedDisplayNames: WeakMap<Function, string> = new WeakMap(); // On large trees, encoding takes significant time. // Try to reuse the already encoded strings. const encodedStringCache: LRUCache<string, Array<number>> = new LRU({ max: 1000, }); export function alphaSortKeys( a: string | number | Symbol, b: string | number | Symbol, ): number { if (a.toString() > b.toString()) { return 1; } else if (b.toString() > a.toString()) { return -1; } else { return 0; } } export function getAllEnumerableKeys( obj: Object, ): Set<string | number | Symbol> { const keys = new Set(); let current = obj; while (current != null) { const currentKeys = [ ...Object.keys(current), ...Object.getOwnPropertySymbols(current), ]; const descriptors = Object.getOwnPropertyDescriptors(current); currentKeys.forEach(key => { // $FlowFixMe: key can be a Symbol https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor if (descriptors[key].enumerable) { keys.add(key); } }); current = Object.getPrototypeOf(current); } return keys; } // Mirror https://github.com/facebook/react/blob/7c21bf72ace77094fd1910cc350a548287ef8350/packages/shared/getComponentName.js#L27-L37 export function getWrappedDisplayName( outerType: mixed, innerType: any, wrapperName: string, fallbackName?: string, ): string { const displayName = (outerType: any).displayName; return ( displayName || `${wrapperName}(${getDisplayName(innerType, fallbackName)})` ); } export function getDisplayName( type: Function, fallbackName: string = 'Anonymous', ): string { const nameFromCache = cachedDisplayNames.get(type); if (nameFromCache != null) { return nameFromCache; } let displayName = fallbackName; // The displayName property is not guaranteed to be a string. // It's only safe to use for our purposes if it's a string. // github.com/facebook/react-devtools/issues/803 if (typeof type.displayName === 'string') { displayName = type.displayName; } else if (typeof type.name === 'string' && type.name !== '') { displayName = type.name; } cachedDisplayNames.set(type, displayName); return displayName; } let uidCounter: number = 0; export function getUID(): number { return ++uidCounter; } export function utfDecodeString(array: Array<number>): string { // Avoid spreading the array (e.g. String.fromCodePoint(...array)) // Functions arguments are first placed on the stack before the function is called // which throws a RangeError for large arrays. // See github.com/facebook/react/issues/22293 let string = ''; for (let i = 0; i < array.length; i++) { const char = array[i]; string += String.fromCodePoint(char); } return string; } function surrogatePairToCodePoint( charCode1: number, charCode2: number, ): number { return ((charCode1 & 0x3ff) << 10) + (charCode2 & 0x3ff) + 0x10000; } // Credit for this encoding approach goes to Tim Down: // https://stackoverflow.com/questions/4877326/how-can-i-tell-if-a-string-contains-multibyte-characters-in-javascript export function utfEncodeString(string: string): Array<number> { const cached = encodedStringCache.get(string); if (cached !== undefined) { return cached; } const encoded = []; let i = 0; let charCode; while (i < string.length) { charCode = string.charCodeAt(i); // Handle multibyte unicode characters (like emoji). if ((charCode & 0xf800) === 0xd800) { encoded.push(surrogatePairToCodePoint(charCode, string.charCodeAt(++i))); } else { encoded.push(charCode); } ++i; } encodedStringCache.set(string, encoded); return encoded; } export function printOperationsArray(operations: Array<number>) { // The first two values are always rendererID and rootID const rendererID = operations[0]; const rootID = operations[1]; const logs = [`operations for renderer:${rendererID} and root:${rootID}`]; let i = 2; // Reassemble the string table. const stringTable = [ null, // ID = 0 corresponds to the null string. ]; const stringTableSize = operations[i++]; const stringTableEnd = i + stringTableSize; while (i < stringTableEnd) { const nextLength = operations[i++]; const nextString = utfDecodeString( (operations.slice(i, i + nextLength): any), ); stringTable.push(nextString); i += nextLength; } while (i < operations.length) { const operation = operations[i]; switch (operation) { case TREE_OPERATION_ADD: { const id = ((operations[i + 1]: any): number); const type = ((operations[i + 2]: any): ElementType); i += 3; if (type === ElementTypeRoot) { logs.push(`Add new root node ${id}`); i++; // isStrictModeCompliant i++; // supportsProfiling i++; // supportsStrictMode i++; // hasOwnerMetadata } else { const parentID = ((operations[i]: any): number); i++; i++; // ownerID const displayNameStringID = operations[i]; const displayName = stringTable[displayNameStringID]; i++; i++; // key logs.push( `Add node ${id} (${displayName || 'null'}) as child of ${parentID}`, ); } break; } case TREE_OPERATION_REMOVE: { const removeLength = ((operations[i + 1]: any): number); i += 2; for (let removeIndex = 0; removeIndex < removeLength; removeIndex++) { const id = ((operations[i]: any): number); i += 1; logs.push(`Remove node ${id}`); } break; } case TREE_OPERATION_REMOVE_ROOT: { i += 1; logs.push(`Remove root ${rootID}`); break; } case TREE_OPERATION_SET_SUBTREE_MODE: { const id = operations[i + 1]; const mode = operations[i + 1]; i += 3; logs.push(`Mode ${mode} set for subtree with root ${id}`); break; } case TREE_OPERATION_REORDER_CHILDREN: { const id = ((operations[i + 1]: any): number); const numChildren = ((operations[i + 2]: any): number); i += 3; const children = operations.slice(i, i + numChildren); i += numChildren; logs.push(`Re-order node ${id} children ${children.join(',')}`); break; } case TREE_OPERATION_UPDATE_TREE_BASE_DURATION: // Base duration updates are only sent while profiling is in progress. // We can ignore them at this point. // The profiler UI uses them lazily in order to generate the tree. i += 3; break; case TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS: const id = operations[i + 1]; const numErrors = operations[i + 2]; const numWarnings = operations[i + 3]; i += 4; logs.push( `Node ${id} has ${numErrors} errors and ${numWarnings} warnings`, ); break; default: throw Error(`Unsupported Bridge operation "${operation}"`); } } console.log(logs.join('\n ')); } export function getDefaultComponentFilters(): Array<ComponentFilter> { return [ { type: ComponentFilterElementType, value: ElementTypeHostComponent, isEnabled: true, }, ]; } export function getSavedComponentFilters(): Array<ComponentFilter> { try { const raw = localStorageGetItem(LOCAL_STORAGE_FILTER_PREFERENCES_KEY); if (raw != null) { return JSON.parse(raw); } } catch (error) {} return getDefaultComponentFilters(); } export function saveComponentFilters( componentFilters: Array<ComponentFilter>, ): void { localStorageSetItem( LOCAL_STORAGE_FILTER_PREFERENCES_KEY, JSON.stringify(componentFilters), ); } export function getAppendComponentStack(): boolean { try { const raw = localStorageGetItem( LOCAL_STORAGE_SHOULD_APPEND_COMPONENT_STACK_KEY, ); if (raw != null) { return JSON.parse(raw); } } catch (error) {} return true; } export function setAppendComponentStack(value: boolean): void { localStorageSetItem( LOCAL_STORAGE_SHOULD_APPEND_COMPONENT_STACK_KEY, JSON.stringify(value), ); } export function getBreakOnConsoleErrors(): boolean { try { const raw = localStorageGetItem( LOCAL_STORAGE_SHOULD_BREAK_ON_CONSOLE_ERRORS, ); if (raw != null) { return JSON.parse(raw); } } catch (error) {} return false; } export function setBreakOnConsoleErrors(value: boolean): void { localStorageSetItem( LOCAL_STORAGE_SHOULD_BREAK_ON_CONSOLE_ERRORS, JSON.stringify(value), ); } export function getHideConsoleLogsInStrictMode(): boolean { try { const raw = localStorageGetItem( LOCAL_STORAGE_HIDE_CONSOLE_LOGS_IN_STRICT_MODE, ); if (raw != null) { return JSON.parse(raw); } } catch (error) {} return false; } export function sethideConsoleLogsInStrictMode(value: boolean): void { localStorageSetItem( LOCAL_STORAGE_HIDE_CONSOLE_LOGS_IN_STRICT_MODE, JSON.stringify(value), ); } export function getShowInlineWarningsAndErrors(): boolean { try { const raw = localStorageGetItem( LOCAL_STORAGE_SHOW_INLINE_WARNINGS_AND_ERRORS_KEY, ); if (raw != null) { return JSON.parse(raw); } } catch (error) {} return true; } export function setShowInlineWarningsAndErrors(value: boolean): void { localStorageSetItem( LOCAL_STORAGE_SHOW_INLINE_WARNINGS_AND_ERRORS_KEY, JSON.stringify(value), ); } export function getDefaultOpenInEditorURL(): string { return typeof process.env.EDITOR_URL === 'string' ? process.env.EDITOR_URL : ''; } export function getOpenInEditorURL(): string { try { const raw = localStorageGetItem(LOCAL_STORAGE_OPEN_IN_EDITOR_URL); if (raw != null) { return JSON.parse(raw); } } catch (error) {} return getDefaultOpenInEditorURL(); } export function separateDisplayNameAndHOCs( displayName: string | null, type: ElementType, ): [string | null, Array<string> | null] { if (displayName === null) { return [null, null]; } let hocDisplayNames = null; switch (type) { case ElementTypeClass: case ElementTypeForwardRef: case ElementTypeFunction: case ElementTypeMemo: if (displayName.indexOf('(') >= 0) { const matches = displayName.match(/[^()]+/g); if (matches != null) { displayName = matches.pop(); hocDisplayNames = matches; } } break; default: break; } return [displayName, hocDisplayNames]; } // Pulled from react-compat // https://github.com/developit/preact-compat/blob/7c5de00e7c85e2ffd011bf3af02899b63f699d3a/src/index.js#L349 export function shallowDiffers(prev: Object, next: Object): boolean { for (const attribute in prev) { if (!(attribute in next)) { return true; } } for (const attribute in next) { if (prev[attribute] !== next[attribute]) { return true; } } return false; } export function getInObject(object: Object, path: Array<string | number>): any { return path.reduce((reduced: Object, attr: any): any => { if (reduced) { if (hasOwnProperty.call(reduced, attr)) { return reduced[attr]; } if (typeof reduced[Symbol.iterator] === 'function') { // Convert iterable to array and return array[index] // // TRICKY // Don't use [...spread] syntax for this purpose. // This project uses @babel/plugin-transform-spread in "loose" mode which only works with Array values. // Other types (e.g. typed arrays, Sets) will not spread correctly. return Array.from(reduced)[attr]; } } return null; }, object); } export function deletePathInObject( object: Object, path: Array<string | number>, ) { const length = path.length; const last = path[length - 1]; if (object != null) { const parent = getInObject(object, path.slice(0, length - 1)); if (parent) { if (isArray(parent)) { parent.splice(((last: any): number), 1); } else { delete parent[last]; } } } } export function renamePathInObject( object: Object, oldPath: Array<string | number>, newPath: Array<string | number>, ) { const length = oldPath.length; if (object != null) { const parent = getInObject(object, oldPath.slice(0, length - 1)); if (parent) { const lastOld = oldPath[length - 1]; const lastNew = newPath[length - 1]; parent[lastNew] = parent[lastOld]; if (isArray(parent)) { parent.splice(((lastOld: any): number), 1); } else { delete parent[lastOld]; } } } } export function setInObject( object: Object, path: Array<string | number>, value: any, ) { const length = path.length; const last = path[length - 1]; if (object != null) { const parent = getInObject(object, path.slice(0, length - 1)); if (parent) { parent[last] = value; } } } export type DataType = | 'array' | 'array_buffer' | 'bigint' | 'boolean' | 'data_view' | 'date' | 'function' | 'html_all_collection' | 'html_element' | 'infinity' | 'iterator' | 'opaque_iterator' | 'nan' | 'null' | 'number' | 'object' | 'react_element' | 'regexp' | 'string' | 'symbol' | 'typed_array' | 'undefined' | 'unknown'; /** * Get a enhanced/artificial type string based on the object instance */ export function getDataType(data: Object): DataType { if (data === null) { return 'null'; } else if (data === undefined) { return 'undefined'; } if (isElement(data)) { return 'react_element'; } if (typeof HTMLElement !== 'undefined' && data instanceof HTMLElement) { return 'html_element'; } const type = typeof data; switch (type) { case 'bigint': return 'bigint'; case 'boolean': return 'boolean'; case 'function': return 'function'; case 'number': if (Number.isNaN(data)) { return 'nan'; } else if (!Number.isFinite(data)) { return 'infinity'; } else { return 'number'; } case 'object': if (isArray(data)) { return 'array'; } else if (ArrayBuffer.isView(data)) { return hasOwnProperty.call(data.constructor, 'BYTES_PER_ELEMENT') ? 'typed_array' : 'data_view'; } else if (data.constructor && data.constructor.name === 'ArrayBuffer') { // HACK This ArrayBuffer check is gross; is there a better way? // We could try to create a new DataView with the value. // If it doesn't error, we know it's an ArrayBuffer, // but this seems kind of awkward and expensive. return 'array_buffer'; } else if (typeof data[Symbol.iterator] === 'function') { const iterator = data[Symbol.iterator](); if (!iterator) { // Proxies might break assumptoins about iterators. // See github.com/facebook/react/issues/21654 } else { return iterator === data ? 'opaque_iterator' : 'iterator'; } } else if (data.constructor && data.constructor.name === 'RegExp') { return 'regexp'; } else { const toStringValue = Object.prototype.toString.call(data); if (toStringValue === '[object Date]') { return 'date'; } else if (toStringValue === '[object HTMLAllCollection]') { return 'html_all_collection'; } } return 'object'; case 'string': return 'string'; case 'symbol': return 'symbol'; case 'undefined': if ( Object.prototype.toString.call(data) === '[object HTMLAllCollection]' ) { return 'html_all_collection'; } return 'undefined'; default: return 'unknown'; } } export function getDisplayNameForReactElement( element: React$Element<any>, ): string | null { const elementType = typeOf(element); switch (elementType) { case ContextConsumer: return 'ContextConsumer'; case ContextProvider: return 'ContextProvider'; case ForwardRef: return 'ForwardRef'; case Fragment: return 'Fragment'; case Lazy: return 'Lazy'; case Memo: return 'Memo'; case Portal: return 'Portal'; case Profiler: return 'Profiler'; case StrictMode: return 'StrictMode'; case Suspense: return 'Suspense'; case SuspenseList: return 'SuspenseList'; case TracingMarker: return 'TracingMarker'; default: const {type} = element; if (typeof type === 'string') { return type; } else if (typeof type === 'function') { return getDisplayName(type, 'Anonymous'); } else if (type != null) { return 'NotImplementedInDevtools'; } else { return 'Element'; } } } const MAX_PREVIEW_STRING_LENGTH = 50; function truncateForDisplay( string: string, length: number = MAX_PREVIEW_STRING_LENGTH, ) { if (string.length > length) { return string.substr(0, length) + '…'; } else { return string; } } // Attempts to mimic Chrome's inline preview for values. // For example, the following value... // { // foo: 123, // bar: "abc", // baz: [true, false], // qux: { ab: 1, cd: 2 } // }; // // Would show a preview of... // {foo: 123, bar: "abc", baz: Array(2), qux: {…}} // // And the following value... // [ // 123, // "abc", // [true, false], // { foo: 123, bar: "abc" } // ]; // // Would show a preview of... // [123, "abc", Array(2), {…}] export function formatDataForPreview( data: any, showFormattedValue: boolean, ): string { if (data != null && hasOwnProperty.call(data, meta.type)) { return showFormattedValue ? data[meta.preview_long] : data[meta.preview_short]; } const type = getDataType(data); switch (type) { case 'html_element': return `<${truncateForDisplay(data.tagName.toLowerCase())} />`; case 'function': return truncateForDisplay( `ƒ ${typeof data.name === 'function' ? '' : data.name}() {}`, ); case 'string': return `"${data}"`; case 'bigint': return truncateForDisplay(data.toString() + 'n'); case 'regexp': return truncateForDisplay(data.toString()); case 'symbol': return truncateForDisplay(data.toString()); case 'react_element': return `<${truncateForDisplay( getDisplayNameForReactElement(data) || 'Unknown', )} />`; case 'array_buffer': return `ArrayBuffer(${data.byteLength})`; case 'data_view': return `DataView(${data.buffer.byteLength})`; case 'array': if (showFormattedValue) { let formatted = ''; for (let i = 0; i < data.length; i++) { if (i > 0) { formatted += ', '; } formatted += formatDataForPreview(data[i], false); if (formatted.length > MAX_PREVIEW_STRING_LENGTH) { // Prevent doing a lot of unnecessary iteration... break; } } return `[${truncateForDisplay(formatted)}]`; } else { const length = hasOwnProperty.call(data, meta.size) ? data[meta.size] : data.length; return `Array(${length})`; } case 'typed_array': const shortName = `${data.constructor.name}(${data.length})`; if (showFormattedValue) { let formatted = ''; for (let i = 0; i < data.length; i++) { if (i > 0) { formatted += ', '; } formatted += data[i]; if (formatted.length > MAX_PREVIEW_STRING_LENGTH) { // Prevent doing a lot of unnecessary iteration... break; } } return `${shortName} [${truncateForDisplay(formatted)}]`; } else { return shortName; } case 'iterator': const name = data.constructor.name; if (showFormattedValue) { // TRICKY // Don't use [...spread] syntax for this purpose. // This project uses @babel/plugin-transform-spread in "loose" mode which only works with Array values. // Other types (e.g. typed arrays, Sets) will not spread correctly. const array = Array.from(data); let formatted = ''; for (let i = 0; i < array.length; i++) { const entryOrEntries = array[i]; if (i > 0) { formatted += ', '; } // TRICKY // Browsers display Maps and Sets differently. // To mimic their behavior, detect if we've been given an entries tuple. // Map(2) {"abc" => 123, "def" => 123} // Set(2) {"abc", 123} if (isArray(entryOrEntries)) { const key = formatDataForPreview(entryOrEntries[0], true); const value = formatDataForPreview(entryOrEntries[1], false); formatted += `${key} => ${value}`; } else { formatted += formatDataForPreview(entryOrEntries, false); } if (formatted.length > MAX_PREVIEW_STRING_LENGTH) { // Prevent doing a lot of unnecessary iteration... break; } } return `${name}(${data.size}) {${truncateForDisplay(formatted)}}`; } else { return `${name}(${data.size})`; } case 'opaque_iterator': { return data[Symbol.toStringTag]; } case 'date': return data.toString(); case 'object': if (showFormattedValue) { const keys = Array.from(getAllEnumerableKeys(data)).sort(alphaSortKeys); let formatted = ''; for (let i = 0; i < keys.length; i++) { const key = keys[i]; if (i > 0) { formatted += ', '; } formatted += `${key.toString()}: ${formatDataForPreview( data[key], false, )}`; if (formatted.length > MAX_PREVIEW_STRING_LENGTH) { // Prevent doing a lot of unnecessary iteration... break; } } return `{${truncateForDisplay(formatted)}}`; } else { return '{…}'; } case 'boolean': case 'number': case 'infinity': case 'nan': case 'null': case 'undefined': return data; default: try { return truncateForDisplay(String(data)); } catch (error) { return 'unserializable'; } } }
run prettier (#25164)
packages/react-devtools-shared/src/utils.js
run prettier (#25164)
<ide><path>ackages/react-devtools-shared/src/utils.js <ide> ): string { <ide> const displayName = (outerType: any).displayName; <ide> return ( <del> displayName || <del> `${wrapperName}(${getDisplayName(innerType, fallbackName)})` <add> displayName || `${wrapperName}(${getDisplayName(innerType, fallbackName)})` <ide> ); <ide> } <ide>
JavaScript
mit
221e1fb33bca26f6d095b5ef5924e23db8388bdb
0
JeroenVinke/templating,aurelia/templating,davismj/templating,aurelia/templating,PWKad/templating,AshleyGrant/templating,shanonvl/aurelia-templating
import {relativeToFile} from 'aurelia-path'; import {HtmlBehaviorResource} from './html-behavior'; import {ValueConverter} from 'aurelia-binding'; import {BindingLanguage} from './binding-language'; import {PLATFORM} from 'aurelia-pal'; import {ViewCompileInstruction, ViewCreateInstruction} from './instructions'; function register(lookup, name, resource, type) { if (!name) { return; } let existing = lookup[name]; if (existing) { if (existing !== resource) { throw new Error(`Attempted to register ${type} when one with the same name already exists. Name: ${name}.`); } return; } lookup[name] = resource; } interface ViewEngineHooks { beforeCompile?: (content: DocumentFragment, resources: ViewResources, instruction: ViewCompileInstruction) => void; afterCompile?: (viewFactory: ViewFactory) => void; beforeCreate?: (viewFactory: ViewFactory, container: Container, content: DocumentFragment, instruction: ViewCreateInstruction, bindingContext?:Object) => void; afterCreate?: (view: View) => void; } export class ViewResources { constructor(parent?: ViewResources, viewUrl?: string) { this.parent = parent || null; this.hasParent = this.parent !== null; this.viewUrl = viewUrl || ''; this.valueConverterLookupFunction = this.getValueConverter.bind(this); this.attributes = {}; this.elements = {}; this.valueConverters = {}; this.attributeMap = {}; this.bindingLanguage = null; this.hook1 = null; this.hook2 = null; this.hook3 = null; this.additionalHooks = null; } onBeforeCompile(content: DocumentFragment, resources: ViewResources, instruction: ViewCompileInstruction): void { if (this.hasParent) { this.parent.onBeforeCompile(content, resources, instruction); } if (this.hook1 !== null) { this.hook1.beforeCompile(content, resources, instruction); if (this.hook2 !== null) { this.hook2.beforeCompile(content, resources, instruction); if (this.hook3 !== null) { this.hook3.beforeCompile(content, resources, instruction); if (this.additionalHooks !== null) { let hooks = this.additionalHooks; for (let i = 0, length = hooks.length; i < length; ++i) { hooks[i].beforeCompile(content, resources, instruction); } } } } } } onAfterCompile(viewFactory: ViewFactory): void { if (this.hasParent) { this.parent.onAfterCompile(viewFactory); } if (this.hook1 !== null) { this.hook1.afterCompile(viewFactory); if (this.hook2 !== null) { this.hook2.afterCompile(viewFactory); if (this.hook3 !== null) { this.hook3.afterCompile(viewFactory); if (this.additionalHooks !== null) { let hooks = this.additionalHooks; for (let i = 0, length = hooks.length; i < length; ++i) { hooks[i].afterCompile(viewFactory); } } } } } } onBeforeCreate(viewFactory: ViewFactory, container: Container, content: DocumentFragment, instruction: ViewCreateInstruction, bindingContext?:Object): void { if (this.hasParent) { this.parent.onBeforeCreate(viewFactory, container, content, instruction, bindingContext); } if (this.hook1 !== null) { this.hook1.beforeCreate(viewFactory, container, content, instruction, bindingContext); if (this.hook2 !== null) { this.hook2.beforeCreate(viewFactory, container, content, instruction, bindingContext); if (this.hook3 !== null) { this.hook3.beforeCreate(viewFactory, container, content, instruction, bindingContext); if (this.additionalHooks !== null) { let hooks = this.additionalHooks; for (let i = 0, length = hooks.length; i < length; ++i) { hooks[i].beforeCreate(viewFactory, container, content, instruction, bindingContext); } } } } } } onAfterCreate(view: View): void { if (this.hasParent) { this.parent.onAfterCreate(view); } if (this.hook1 !== null) { this.hook1.afterCreate(view); if (this.hook2 !== null) { this.hook2.afterCreate(view); if (this.hook3 !== null) { this.hook3.afterCreate(view); if (this.additionalHooks !== null) { let hooks = this.additionalHooks; for (let i = 0, length = hooks.length; i < length; ++i) { hooks[i].afterCreate(view); } } } } } } registerViewEngineHooks(hooks:ViewEngineHooks): void { if (hooks.beforeCompile === undefined) hooks.beforeCompile = PLATFORM.noop; if (hooks.afterCompile === undefined) hooks.afterCompile = PLATFORM.noop; if (hooks.beforeCreate === undefined) hooks.beforeCreate = PLATFORM.noop; if (hooks.afterCreate === undefined) hooks.afterCreate = PLATFORM.noop; if (this.hook1 === null) this.hook1 = hooks; else if (this.hook2 === null) this.hook2 = hooks; else if (this.hook3 === null) this.hook3 = hooks; else { if (this.additionalHooks === null) { this.additionalHooks = []; } this.additionalHooks.push(hooks); } } getBindingLanguage(bindingLanguageFallback: BindingLanguage): BindingLanguage { return this.bindingLanguage || (this.bindingLanguage = bindingLanguageFallback); } patchInParent(newParent: ViewResources): void { let originalParent = this.parent; this.parent = newParent || null; this.hasParent = this.parent !== null; if (newParent.parent === null) { newParent.parent = originalParent; newParent.hasParent = originalParent !== null; } } relativeToView(path: string): string { return relativeToFile(path, this.viewUrl); } registerElement(tagName: string, behavior: HtmlBehaviorResource): void { register(this.elements, tagName, behavior, 'an Element'); } getElement(tagName: string): HtmlBehaviorResource { return this.elements[tagName] || (this.hasParent ? this.parent.getElement(tagName) : null); } mapAttribute(attribute: string): string { return this.attributeMap[attribute] || (this.hasParent ? this.parent.mapAttribute(attribute) : null); } registerAttribute(attribute: string, behavior: HtmlBehaviorResource, knownAttribute: string): void { this.attributeMap[attribute] = knownAttribute; register(this.attributes, attribute, behavior, 'an Attribute'); } getAttribute(attribute: string): HtmlBehaviorResource { return this.attributes[attribute] || (this.hasParent ? this.parent.getAttribute(attribute) : null); } registerValueConverter(name: string, valueConverter: ValueConverter): void { register(this.valueConverters, name, valueConverter, 'a ValueConverter'); } getValueConverter(name: string): ValueConverter { return this.valueConverters[name] || (this.hasParent ? this.parent.getValueConverter(name) : null); } }
src/view-resources.js
import {relativeToFile} from 'aurelia-path'; import {HtmlBehaviorResource} from './html-behavior'; import {ValueConverter} from 'aurelia-binding'; import {BindingLanguage} from './binding-language'; import {Metadata} from 'aurelia-metadata'; import {ViewCompileInstruction, ViewCreateInstruction} from './instructions'; function register(lookup, name, resource, type) { if (!name) { return; } let existing = lookup[name]; if (existing) { if (existing !== resource) { throw new Error(`Attempted to register ${type} when one with the same name already exists. Name: ${name}.`); } return; } lookup[name] = resource; } interface ViewEngineHooks { beforeCompile?: (content: DocumentFragment, resources: ViewResources, instruction: ViewCompileInstruction) => void; afterCompile?: (viewFactory: ViewFactory) => void; beforeCreate?: (viewFactory: ViewFactory, container: Container, content: DocumentFragment, instruction: ViewCreateInstruction, bindingContext?:Object) => void; afterCreate?: (view: View) => void; } export class ViewResources { constructor(parent?: ViewResources, viewUrl?: string) { this.parent = parent || null; this.hasParent = this.parent !== null; this.viewUrl = viewUrl || ''; this.valueConverterLookupFunction = this.getValueConverter.bind(this); this.attributes = {}; this.elements = {}; this.valueConverters = {}; this.attributeMap = {}; this.bindingLanguage = null; this.hook1 = null; this.hook2 = null; this.hook3 = null; this.additionalHooks = null; } onBeforeCompile(content: DocumentFragment, resources: ViewResources, instruction: ViewCompileInstruction): void { if (this.hasParent) { this.parent.onBeforeCompile(content, resources, instruction); } if (this.hook1 !== null) { this.hook1.beforeCompile(content, resources, instruction); if (this.hook2 !== null) { this.hook2.beforeCompile(content, resources, instruction); if (this.hook3 !== null) { this.hook3.beforeCompile(content, resources, instruction); if (this.additionalHooks !== null) { let hooks = this.additionalHooks; for (let i = 0, length = hooks.length; i < length; ++i) { hooks[i].beforeCompile(content, resources, instruction); } } } } } } onAfterCompile(viewFactory: ViewFactory): void { if (this.hasParent) { this.parent.onAfterCompile(viewFactory); } if (this.hook1 !== null) { this.hook1.afterCompile(viewFactory); if (this.hook2 !== null) { this.hook2.afterCompile(viewFactory); if (this.hook3 !== null) { this.hook3.afterCompile(viewFactory); if (this.additionalHooks !== null) { let hooks = this.additionalHooks; for (let i = 0, length = hooks.length; i < length; ++i) { hooks[i].afterCompile(viewFactory); } } } } } } onBeforeCreate(viewFactory: ViewFactory, container: Container, content: DocumentFragment, instruction: ViewCreateInstruction, bindingContext?:Object): void { if (this.hasParent) { this.parent.onBeforeCreate(viewFactory, container, content, instruction, bindingContext); } if (this.hook1 !== null) { this.hook1.beforeCreate(viewFactory, container, content, instruction, bindingContext); if (this.hook2 !== null) { this.hook2.beforeCreate(viewFactory, container, content, instruction, bindingContext); if (this.hook3 !== null) { this.hook3.beforeCreate(viewFactory, container, content, instruction, bindingContext); if (this.additionalHooks !== null) { let hooks = this.additionalHooks; for (let i = 0, length = hooks.length; i < length; ++i) { hooks[i].beforeCreate(viewFactory, container, content, instruction, bindingContext); } } } } } } onAfterCreate(view: View): void { if (this.hasParent) { this.parent.onAfterCreate(view); } if (this.hook1 !== null) { this.hook1.afterCreate(view); if (this.hook2 !== null) { this.hook2.afterCreate(view); if (this.hook3 !== null) { this.hook3.afterCreate(view); if (this.additionalHooks !== null) { let hooks = this.additionalHooks; for (let i = 0, length = hooks.length; i < length; ++i) { hooks[i].afterCreate(view); } } } } } } registerViewEngineHooks(hooks:ViewEngineHooks): void { if (hooks.beforeCompile === undefined) hooks.beforeCompile = Metadata.noop; if (hooks.afterCompile === undefined) hooks.afterCompile = Metadata.noop; if (hooks.beforeCreate === undefined) hooks.beforeCreate = Metadata.noop; if (hooks.afterCreate === undefined) hooks.afterCreate = Metadata.noop; if (this.hook1 === null) this.hook1 = hooks; else if (this.hook2 === null) this.hook2 = hooks; else if (this.hook3 === null) this.hook3 = hooks; else { if (this.additionalHooks === null) { this.additionalHooks = []; } this.additionalHooks.push(hooks); } } getBindingLanguage(bindingLanguageFallback: BindingLanguage): BindingLanguage { return this.bindingLanguage || (this.bindingLanguage = bindingLanguageFallback); } patchInParent(newParent: ViewResources): void { let originalParent = this.parent; this.parent = newParent || null; this.hasParent = this.parent !== null; if (newParent.parent === null) { newParent.parent = originalParent; newParent.hasParent = originalParent !== null; } } relativeToView(path: string): string { return relativeToFile(path, this.viewUrl); } registerElement(tagName: string, behavior: HtmlBehaviorResource): void { register(this.elements, tagName, behavior, 'an Element'); } getElement(tagName: string): HtmlBehaviorResource { return this.elements[tagName] || (this.hasParent ? this.parent.getElement(tagName) : null); } mapAttribute(attribute: string): string { return this.attributeMap[attribute] || (this.hasParent ? this.parent.mapAttribute(attribute) : null); } registerAttribute(attribute: string, behavior: HtmlBehaviorResource, knownAttribute: string): void { this.attributeMap[attribute] = knownAttribute; register(this.attributes, attribute, behavior, 'an Attribute'); } getAttribute(attribute: string): HtmlBehaviorResource { return this.attributes[attribute] || (this.hasParent ? this.parent.getAttribute(attribute) : null); } registerValueConverter(name: string, valueConverter: ValueConverter): void { register(this.valueConverters, name, valueConverter, 'a ValueConverter'); } getValueConverter(name: string): ValueConverter { return this.valueConverters[name] || (this.hasParent ? this.parent.getValueConverter(name) : null); } }
fix(view-resources): switch to PLATFORM.noop from Metadata
src/view-resources.js
fix(view-resources): switch to PLATFORM.noop from Metadata
<ide><path>rc/view-resources.js <ide> import {HtmlBehaviorResource} from './html-behavior'; <ide> import {ValueConverter} from 'aurelia-binding'; <ide> import {BindingLanguage} from './binding-language'; <del>import {Metadata} from 'aurelia-metadata'; <add>import {PLATFORM} from 'aurelia-pal'; <ide> import {ViewCompileInstruction, ViewCreateInstruction} from './instructions'; <ide> <ide> function register(lookup, name, resource, type) { <ide> } <ide> <ide> registerViewEngineHooks(hooks:ViewEngineHooks): void { <del> if (hooks.beforeCompile === undefined) hooks.beforeCompile = Metadata.noop; <del> if (hooks.afterCompile === undefined) hooks.afterCompile = Metadata.noop; <del> if (hooks.beforeCreate === undefined) hooks.beforeCreate = Metadata.noop; <del> if (hooks.afterCreate === undefined) hooks.afterCreate = Metadata.noop; <add> if (hooks.beforeCompile === undefined) hooks.beforeCompile = PLATFORM.noop; <add> if (hooks.afterCompile === undefined) hooks.afterCompile = PLATFORM.noop; <add> if (hooks.beforeCreate === undefined) hooks.beforeCreate = PLATFORM.noop; <add> if (hooks.afterCreate === undefined) hooks.afterCreate = PLATFORM.noop; <ide> <ide> if (this.hook1 === null) this.hook1 = hooks; <ide> else if (this.hook2 === null) this.hook2 = hooks;
Java
mit
4abf2d9954ecaf68e338c37c45759c765f8c70c4
0
SpongePowered/Sponge,SpongePowered/Sponge,SpongePowered/Sponge
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.mixin.api.mcp.tileentity; import org.spongepowered.api.block.entity.CommandBlock; import org.spongepowered.api.data.persistence.DataContainer; import org.spongepowered.api.data.value.Value; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.common.adventure.SpongeAdventure; import org.spongepowered.common.util.Constants; import net.minecraft.tileentity.CommandBlockLogic; import net.minecraft.tileentity.CommandBlockTileEntity; import java.util.Set; @Mixin(CommandBlockTileEntity.class) public abstract class CommandBlockTileEntityMixin_API extends TileEntityMixin_API implements CommandBlock { @Shadow public abstract CommandBlockLogic getCommandBlockLogic(); @Override public void execute() { this.getCommandBlockLogic().trigger(this.world); } @Override public String getName() { return this.getCommandBlockLogic().getName().getString(); } @Override public DataContainer toContainer() { final DataContainer container = super.toContainer(); container.set(Constants.TileEntity.CommandBlock.STORED_COMMAND, this.getCommandBlockLogic().getCommand()); container.set(Constants.TileEntity.CommandBlock.SUCCESS_COUNT, this.getCommandBlockLogic().getSuccessCount()); container.set(Constants.TileEntity.CUSTOM_NAME, this.getCommandBlockLogic().getName()); container.set(Constants.TileEntity.CommandBlock.DOES_TRACK_OUTPUT, this.getCommandBlockLogic().shouldReceiveErrors()); if (this.getCommandBlockLogic().shouldReceiveErrors()) { container.set(Constants.TileEntity.CommandBlock.TRACKED_OUTPUT, SpongeAdventure.legacySection(SpongeAdventure.asAdventure(this.getCommandBlockLogic().getLastOutput()))); } return container; } @Override protected Set<Value.Immutable<?>> api$getVanillaValues() { final Set<Value.Immutable<?>> values = super.api$getVanillaValues(); values.add(this.storedCommand().asImmutable()); values.add(this.successCount().asImmutable()); values.add(this.doesTrackOutput().asImmutable()); this.lastOutput().map(Value::asImmutable).ifPresent(values::add); return values; } @Override public String getIdentifier() { return this.getCommandBlockLogic().getName().getString(); } }
src/mixins/java/org/spongepowered/common/mixin/api/mcp/tileentity/CommandBlockTileEntityMixin_API.java
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.mixin.api.mcp.tileentity; import org.spongepowered.api.block.entity.CommandBlock; import org.spongepowered.api.data.persistence.DataContainer; import org.spongepowered.api.data.value.Value; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.common.adventure.SpongeAdventure; import org.spongepowered.common.util.Constants; import net.minecraft.tileentity.CommandBlockLogic; import net.minecraft.tileentity.CommandBlockTileEntity; import java.util.Set; @Mixin(CommandBlockTileEntity.class) public abstract class CommandBlockTileEntityMixin_API extends TileEntityMixin_API implements CommandBlock { @Shadow public abstract CommandBlockLogic getCommandBlockLogic(); @Override public void execute() { this.getCommandBlockLogic().trigger(this.world); } @Override public String getName() { return this.getCommandBlockLogic().getName().getString(); } @Override public DataContainer toContainer() { final DataContainer container = super.toContainer(); container.set(Constants.TileEntity.CommandBlock.STORED_COMMAND, this.getCommandBlockLogic().getCommand()); container.set(Constants.TileEntity.CommandBlock.SUCCESS_COUNT, this.getCommandBlockLogic().getSuccessCount()); container.set(Constants.TileEntity.CUSTOM_NAME, this.getCommandBlockLogic().getName()); container.set(Constants.TileEntity.CommandBlock.DOES_TRACK_OUTPUT, this.getCommandBlockLogic().shouldReceiveErrors()); if (this.getCommandBlockLogic().shouldReceiveErrors()) { container.set(Constants.TileEntity.CommandBlock.TRACKED_OUTPUT, SpongeAdventure.legacySection(SpongeAdventure.asAdventure(this.getCommandBlockLogic().getLastOutput()))); } return container; } @Override protected Set<Value.Immutable<?>> api$getVanillaValues() { final Set<Value.Immutable<?>> values = super.api$getVanillaValues(); values.add(this.storedCommand().asImmutable()); values.add(this.successCount().asImmutable()); values.add(this.doesTrackOutput().asImmutable()); this.lastOutput().map(Value::asImmutable).ifPresent(values::add); return values; } @Override public String getIdentifier() { return ""; } }
Use the name. Signed-off-by: Chris Sanders <[email protected]>
src/mixins/java/org/spongepowered/common/mixin/api/mcp/tileentity/CommandBlockTileEntityMixin_API.java
Use the name.
<ide><path>rc/mixins/java/org/spongepowered/common/mixin/api/mcp/tileentity/CommandBlockTileEntityMixin_API.java <ide> <ide> @Override <ide> public String getIdentifier() { <del> return ""; <add> return this.getCommandBlockLogic().getName().getString(); <ide> } <ide> }
Java
apache-2.0
0ed477419e24856909e36520510a67cb841a8c69
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.messages; import com.intellij.BundleBase; import com.intellij.icons.AllIcons; import com.intellij.openapi.Disposable; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.ui.Gray; import com.intellij.ui.JBColor; import com.intellij.ui.mac.TouchbarDataKeys; import com.intellij.util.ArrayUtil; import com.intellij.util.ui.UIUtil; import org.jdesktop.swingx.graphics.GraphicsUtilities; import org.jdesktop.swingx.graphics.ShadowRenderer; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.border.Border; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import static com.intellij.openapi.wm.IdeFocusManager.getGlobalInstance; /** * Created by Denis Fokin */ public class SheetController implements Disposable { private static final KeyStroke VK_ESC_KEYSTROKE = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); private static final Logger LOG = Logger.getInstance(SheetController.class); private static final int SHEET_MINIMUM_HEIGHT = 143; private final DialogWrapper.DoNotAskOption myDoNotAskOption; private boolean myDoNotAskResult; private BufferedImage myShadowImage; private final JButton[] buttons; private final JButton myDefaultButton; private JComponent myFocusedComponent; private final JCheckBox doNotAskCheckBox = new JCheckBox(); public static final int SHADOW_BORDER = 5; private static final int RIGHT_OFFSET = 10 - SHADOW_BORDER; private final static int TOP_SHEET_PADDING = 20; private final static int GAP_BETWEEN_LINES = 10; private final static int LEFT_SHEET_PADDING = 35; private final static int LEFT_SHEET_OFFSET = 120; private static final int GAP_BETWEEN_BUTTONS = 5; private static final String SPACE_OR_LINE_SEPARATOR_PATTERN = "([\\s" + System.getProperty("line.separator") + "]|(<br\\s*/?>))+"; // SHEET public int SHEET_WIDTH = 400; public int SHEET_HEIGHT = 143; // SHEET + shadow int SHEET_NC_WIDTH = SHEET_WIDTH + SHADOW_BORDER * 2; int SHEET_NC_HEIGHT = SHEET_HEIGHT + SHADOW_BORDER ; private Icon myIcon = UIUtil.getInformationIcon(); private String myResult; private final JPanel mySheetPanel; private SheetMessage mySheetMessage; private final JEditorPane messageTextPane = new JEditorPane(); private final Dimension messageArea = new Dimension(250, Short.MAX_VALUE); SheetController(final SheetMessage sheetMessage, final String title, final String message, final Icon icon, final String[] buttonTitles, final String defaultButtonTitle, final DialogWrapper.DoNotAskOption doNotAskOption, final String focusedButtonTitle) { if (icon != null) { myIcon = icon; } myDoNotAskOption = doNotAskOption; myDoNotAskResult = (doNotAskOption != null) && !doNotAskOption.isToBeShown(); mySheetMessage = sheetMessage; buttons = new JButton[buttonTitles.length]; myResult = null; int defaultButtonIndex = -1; int focusedButtonIndex = -1; for (int i = 0; i < buttons.length; i++) { String buttonTitle = buttonTitles[i]; buttons[i] = new JButton(); buttons[i].setOpaque(false); handleMnemonics(i, buttonTitle); final TouchbarDataKeys.DlgButtonDesc bdesc = TouchbarDataKeys.putDialogButtonDescriptor(buttons[i], buttons.length - i).setMainGroup(true); if (buttonTitle.equals(defaultButtonTitle)) { defaultButtonIndex = i; bdesc.setDefault(true); } if (buttonTitle.equals(focusedButtonTitle) && !focusedButtonTitle.equals("Cancel")) { focusedButtonIndex = i; } } defaultButtonIndex = (focusedButtonIndex == defaultButtonIndex) || defaultButtonTitle == null ? 0 : defaultButtonIndex; if (focusedButtonIndex != -1 && defaultButtonIndex != focusedButtonIndex) { myFocusedComponent = buttons[focusedButtonIndex]; } else if (doNotAskOption != null) { myFocusedComponent = doNotAskCheckBox; } else if (buttons.length > 1) { myFocusedComponent = buttons[buttons.length - 1]; } myDefaultButton = (defaultButtonIndex == -1) ? buttons[0] : buttons[defaultButtonIndex]; if (myResult == null) { myResult = Messages.CANCEL_BUTTON; } mySheetPanel = createSheetPanel(title, message, buttons); initShadowImage(); } private void initShadowImage() { final BufferedImage mySheetStencil = GraphicsUtilities.createCompatibleTranslucentImage(SHEET_WIDTH, SHEET_HEIGHT); Graphics2D g2 = mySheetStencil.createGraphics(); g2.setColor(new JBColor(Gray._255, Gray._0)); g2.fillRect(0, 0, SHEET_WIDTH, SHEET_HEIGHT); g2.dispose(); ShadowRenderer renderer = new ShadowRenderer(); renderer.setSize(SHADOW_BORDER); renderer.setOpacity(.80f); renderer.setColor(new JBColor(JBColor.BLACK, Gray._10)); myShadowImage = renderer.createShadow(mySheetStencil); } private void handleMnemonics(int i, String title) { buttons[i].setName(title); if (!setButtonTextAndMnemonic(i, title, '_') && !setButtonTextAndMnemonic(i, title, '&') && !setButtonTextAndMnemonic(i, title, BundleBase.MNEMONIC)) { buttons[i].setText(title); } } private boolean setButtonTextAndMnemonic(int i, String title, char mnemonics) { int mIdx; if ((mIdx = title.indexOf(mnemonics)) >= 0) { String text = title.substring(0, mIdx) + title.substring(mIdx + 1); buttons[i].setText(text); buttons[i].setDisplayedMnemonicIndex(mIdx); return true; } else { return false; } } void requestFocus() { getGlobalInstance().doWhenFocusSettlesDown(() -> { if (myFocusedComponent != null) { getGlobalInstance().doWhenFocusSettlesDown(() -> getGlobalInstance().requestFocus(myFocusedComponent, true)); } else { LOG.debug("My focused component is null for the next message: " + messageTextPane.getText()); } }); } void setDefaultResult () { myResult = myDefaultButton.getName(); } void setFocusedResult () { if (myFocusedComponent instanceof JButton) { JButton focusedButton = (JButton)myFocusedComponent; myResult = focusedButton.getName(); } } void setResultAndStartClose(String result) { if (result != null) myResult = result; mySheetMessage.startAnimation(false); } JPanel getPanel(final JDialog w) { w.getRootPane().setDefaultButton(myDefaultButton); ActionListener actionListener = new ActionListener() { @Override public void actionPerformed(@NotNull ActionEvent e) { final String res = e.getSource() instanceof JButton ? ((JButton)e.getSource()).getName() : null; setResultAndStartClose(res); } }; mySheetPanel.registerKeyboardAction(actionListener, VK_ESC_KEYSTROKE, JComponent.WHEN_IN_FOCUSED_WINDOW); for (JButton button: buttons) { button.addActionListener(actionListener); } return mySheetPanel; } private static float getSheetAlpha() { return .95f; } private JPanel createSheetPanel(String title, String message, JButton[] buttons) { JPanel sheetPanel = new JPanel() { @Override protected void paintComponent(@NotNull Graphics g2d) { final Graphics2D g = (Graphics2D) g2d.create(); super.paintComponent(g); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getSheetAlpha())); g.setColor(new JBColor(Gray._230, UIUtil.getPanelBackground())); Rectangle dialog = new Rectangle(SHADOW_BORDER, 0, SHEET_WIDTH, SHEET_HEIGHT); paintShadow(g); // draw the sheet background if (UIUtil.isUnderDarcula()) { g.fillRoundRect((int)dialog.getX(), (int)dialog.getY() - 5, (int)dialog.getWidth(), (int)(5 + dialog.getHeight()), 5, 5); } else { //todo make bottom corners g.fill(dialog); } Border border = UIManager.getBorder("Window.border"); if (border != null) { border.paintBorder(this, g, dialog.x, dialog.y, dialog.width, dialog.height); } paintShadowFromParent(g); } }; sheetPanel.setOpaque(false); sheetPanel.setLayout(null); JPanel ico = new JPanel() { @Override protected void paintComponent(@NotNull Graphics g) { super.paintComponent(g); myIcon.paintIcon(this, g, 0, 0); } }; JEditorPane headerLabel = new JEditorPane(); headerLabel.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE); headerLabel.setFont(UIUtil.getLabelFont().deriveFont(Font.BOLD)); headerLabel.setEditable(false); headerLabel.setContentType("text/html"); headerLabel.setSize(250, Short.MAX_VALUE); headerLabel.setText(title); headerLabel.setSize(250, headerLabel.getPreferredSize().height); headerLabel.setOpaque(false); headerLabel.setFocusable(false); sheetPanel.add(headerLabel); headerLabel.repaint(); messageTextPane.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE); Font font = UIUtil.getLabelFont(UIUtil.FontSize.SMALL); messageTextPane.setFont(font); messageTextPane.setEditable(false); messageTextPane.setContentType("text/html"); messageTextPane.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent he) { if(he.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { if(Desktop.isDesktopSupported()) { try { URL url = he.getURL(); if (url != null) { Desktop.getDesktop().browse(url.toURI()); } else { LOG.warn("URL is null; HyperlinkEvent: " + he.toString()); } } catch (IOException | URISyntaxException e) { LOG.error(e); } } } } }); FontMetrics fontMetrics = sheetPanel.getFontMetrics(font); int widestWordWidth = 250; String [] words = (message == null) ? ArrayUtil.EMPTY_STRING_ARRAY : message.split(SPACE_OR_LINE_SEPARATOR_PATTERN); for (String word : words) { widestWordWidth = Math.max(fontMetrics.stringWidth(word), widestWordWidth); } messageTextPane.setSize(widestWordWidth, Short.MAX_VALUE); messageTextPane.setText(handleBreaks(message)); messageArea.setSize(widestWordWidth, messageTextPane.getPreferredSize().height); SHEET_WIDTH = Math.max(LEFT_SHEET_OFFSET + widestWordWidth + RIGHT_OFFSET, SHEET_WIDTH); messageTextPane.setSize(messageArea); messageTextPane.setOpaque(false); messageTextPane.setFocusable(false); sheetPanel.add(messageTextPane); messageTextPane.repaint(); ico.setOpaque(false); ico.setSize(new Dimension(AllIcons.Logo_welcomeScreen.getIconWidth(), AllIcons.Logo_welcomeScreen.getIconHeight())); ico.setLocation(LEFT_SHEET_PADDING, TOP_SHEET_PADDING); sheetPanel.add(ico); headerLabel.setLocation(LEFT_SHEET_OFFSET, TOP_SHEET_PADDING); messageTextPane.setLocation(LEFT_SHEET_OFFSET, TOP_SHEET_PADDING + headerLabel.getPreferredSize().height + GAP_BETWEEN_LINES); SHEET_HEIGHT = TOP_SHEET_PADDING + headerLabel.getPreferredSize().height + GAP_BETWEEN_LINES + messageArea.height + GAP_BETWEEN_LINES; if (myDoNotAskOption != null) { layoutDoNotAskCheckbox(sheetPanel); } layoutWithAbsoluteLayout(buttons, sheetPanel); int BOTTOM_SHEET_PADDING = 10; SHEET_HEIGHT += BOTTOM_SHEET_PADDING; if (SHEET_HEIGHT < SHEET_MINIMUM_HEIGHT) { SHEET_HEIGHT = SHEET_MINIMUM_HEIGHT; shiftButtonsToTheBottom(SHEET_MINIMUM_HEIGHT - SHEET_HEIGHT); } sheetPanel.setFocusCycleRoot(true); recalculateShadow(); sheetPanel.setSize(SHEET_NC_WIDTH, SHEET_NC_HEIGHT); return sheetPanel; } private static String handleBreaks(final String message) { return message == null ? "" : message.replaceAll("(\r\n|\n)", "<br/>"); } private void shiftButtonsToTheBottom(int shiftDistance) { for (JButton b : buttons) { b.setLocation(b.getX(), b.getY() + shiftDistance); } } private void recalculateShadow() { SHEET_NC_WIDTH = SHEET_WIDTH + SHADOW_BORDER * 2; SHEET_NC_HEIGHT = SHEET_HEIGHT + SHADOW_BORDER; } private void layoutWithAbsoluteLayout(JButton[] buttons, JPanel sheetPanel) { layoutButtons(buttons, sheetPanel); } private void paintShadow(Graphics2D g2d) { g2d.setBackground(new JBColor(new Color(255, 255, 255, 0), new Color(110, 110, 110, 0))); g2d.clearRect(0, 0, SHEET_NC_WIDTH, SHEET_HEIGHT); g2d.drawImage(myShadowImage, 0, -SHADOW_BORDER, null); g2d.clearRect(SHADOW_BORDER, 0, SHEET_WIDTH, SHEET_HEIGHT); } private static float getShadowAlpha() { return ((UIUtil.isUnderDarcula())) ? .85f : .35f; } private void paintShadowFromParent(Graphics2D g2d) { g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getShadowAlpha())); g2d.drawImage(myShadowImage, 0, - SHEET_HEIGHT - SHADOW_BORDER, null); } private void layoutButtons(final JButton[] buttons, JPanel panel) { //int widestButtonWidth = 0; int buttonWidth = 0; SHEET_HEIGHT += GAP_BETWEEN_LINES; for (int i = 0; i < buttons.length; i ++) { buttons[i].repaint(); buttons[i].setSize(buttons[i].getPreferredSize()); buttonWidth += buttons[i].getWidth(); if (i == buttons.length - 1) break; buttonWidth += GAP_BETWEEN_BUTTONS; } int buttonsRowWidth = LEFT_SHEET_OFFSET + buttonWidth + RIGHT_OFFSET; // update the pane if the sheet is going to be wider messageTextPane.setSize(Math.max(messageTextPane.getWidth(), buttonWidth), messageTextPane.getHeight()); SHEET_WIDTH = Math.max(buttonsRowWidth, SHEET_WIDTH); int buttonShift = RIGHT_OFFSET; for (JButton button : buttons) { Dimension size = button.getSize(); buttonShift += size.width; button.setBounds(SHEET_WIDTH - buttonShift, SHEET_HEIGHT, size.width, size.height); panel.add(button); buttonShift += GAP_BETWEEN_BUTTONS; } SHEET_HEIGHT += buttons[0].getHeight(); } private void layoutDoNotAskCheckbox(JPanel sheetPanel) { doNotAskCheckBox.setText(myDoNotAskOption.getDoNotShowMessage()); doNotAskCheckBox.setVisible(myDoNotAskOption.canBeHidden()); doNotAskCheckBox.setSelected(!myDoNotAskOption.isToBeShown()); doNotAskCheckBox.setOpaque(false); doNotAskCheckBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(@NotNull ItemEvent e) { myDoNotAskResult = (e.getStateChange() == ItemEvent.SELECTED); } }); doNotAskCheckBox.repaint(); doNotAskCheckBox.setSize(doNotAskCheckBox.getPreferredSize()); doNotAskCheckBox.setLocation(LEFT_SHEET_OFFSET, SHEET_HEIGHT); sheetPanel.add(doNotAskCheckBox); if (myFocusedComponent == null) { myFocusedComponent = doNotAskCheckBox; } SHEET_HEIGHT += doNotAskCheckBox.getHeight(); } /** * This method is used to show an image during message showing * @return image to show */ Image getStaticImage() { final JFrame myOffScreenFrame = new JFrame() ; myOffScreenFrame.add(mySheetPanel); myOffScreenFrame.getRootPane().setDefaultButton(myDefaultButton); BufferedImage image = UIUtil.createImage(SHEET_NC_WIDTH, SHEET_NC_HEIGHT, BufferedImage.TYPE_INT_ARGB); Graphics g = image.createGraphics(); mySheetPanel.paint(g); g.dispose(); myOffScreenFrame.remove(mySheetPanel); myOffScreenFrame.dispose(); return image; } JPanel getSheetPanel() { return mySheetPanel; } public boolean getDoNotAskResult () { return myDoNotAskResult; } public String getResult() { return myResult; } @Override public void dispose() { mySheetPanel.unregisterKeyboardAction(VK_ESC_KEYSTROKE); mySheetMessage = null; } }
platform/platform-impl/src/com/intellij/ui/messages/SheetController.java
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.messages; import com.intellij.icons.AllIcons; import com.intellij.openapi.Disposable; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.ui.Gray; import com.intellij.ui.JBColor; import com.intellij.ui.mac.TouchbarDataKeys; import com.intellij.util.ArrayUtil; import com.intellij.util.ui.UIUtil; import org.jdesktop.swingx.graphics.GraphicsUtilities; import org.jdesktop.swingx.graphics.ShadowRenderer; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.border.Border; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import static com.intellij.openapi.wm.IdeFocusManager.getGlobalInstance; /** * Created by Denis Fokin */ public class SheetController implements Disposable { private static final KeyStroke VK_ESC_KEYSTROKE = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); private static final Logger LOG = Logger.getInstance(SheetController.class); private static final int SHEET_MINIMUM_HEIGHT = 143; private final DialogWrapper.DoNotAskOption myDoNotAskOption; private boolean myDoNotAskResult; private BufferedImage myShadowImage; private final JButton[] buttons; private final JButton myDefaultButton; private JComponent myFocusedComponent; private final JCheckBox doNotAskCheckBox = new JCheckBox(); public static final int SHADOW_BORDER = 5; private static final int RIGHT_OFFSET = 10 - SHADOW_BORDER; private final static int TOP_SHEET_PADDING = 20; private final static int GAP_BETWEEN_LINES = 10; private final static int LEFT_SHEET_PADDING = 35; private final static int LEFT_SHEET_OFFSET = 120; private static final int GAP_BETWEEN_BUTTONS = 5; private static final String SPACE_OR_LINE_SEPARATOR_PATTERN = "([\\s" + System.getProperty("line.separator") + "]|(<br\\s*/?>))+"; // SHEET public int SHEET_WIDTH = 400; public int SHEET_HEIGHT = 143; // SHEET + shadow int SHEET_NC_WIDTH = SHEET_WIDTH + SHADOW_BORDER * 2; int SHEET_NC_HEIGHT = SHEET_HEIGHT + SHADOW_BORDER ; private Icon myIcon = UIUtil.getInformationIcon(); private String myResult; private final JPanel mySheetPanel; private SheetMessage mySheetMessage; private final JEditorPane messageTextPane = new JEditorPane(); private final Dimension messageArea = new Dimension(250, Short.MAX_VALUE); SheetController(final SheetMessage sheetMessage, final String title, final String message, final Icon icon, final String[] buttonTitles, final String defaultButtonTitle, final DialogWrapper.DoNotAskOption doNotAskOption, final String focusedButtonTitle) { if (icon != null) { myIcon = icon; } myDoNotAskOption = doNotAskOption; myDoNotAskResult = (doNotAskOption != null) && !doNotAskOption.isToBeShown(); mySheetMessage = sheetMessage; buttons = new JButton[buttonTitles.length]; myResult = null; int defaultButtonIndex = -1; int focusedButtonIndex = -1; for (int i = 0; i < buttons.length; i++) { String buttonTitle = buttonTitles[i]; buttons[i] = new JButton(); buttons[i].setOpaque(false); handleMnemonics(i, buttonTitle); final TouchbarDataKeys.DlgButtonDesc bdesc = TouchbarDataKeys.putDialogButtonDescriptor(buttons[i], buttons.length - i).setMainGroup(true); if (buttonTitle.equals(defaultButtonTitle)) { defaultButtonIndex = i; bdesc.setDefault(true); } if (buttonTitle.equals(focusedButtonTitle) && !focusedButtonTitle.equals("Cancel")) { focusedButtonIndex = i; } } defaultButtonIndex = (focusedButtonIndex == defaultButtonIndex) || defaultButtonTitle == null ? 0 : defaultButtonIndex; if (focusedButtonIndex != -1 && defaultButtonIndex != focusedButtonIndex) { myFocusedComponent = buttons[focusedButtonIndex]; } else if (doNotAskOption != null) { myFocusedComponent = doNotAskCheckBox; } else if (buttons.length > 1) { myFocusedComponent = buttons[buttons.length - 1]; } myDefaultButton = (defaultButtonIndex == -1) ? buttons[0] : buttons[defaultButtonIndex]; if (myResult == null) { myResult = Messages.CANCEL_BUTTON; } mySheetPanel = createSheetPanel(title, message, buttons); initShadowImage(); } private void initShadowImage() { final BufferedImage mySheetStencil = GraphicsUtilities.createCompatibleTranslucentImage(SHEET_WIDTH, SHEET_HEIGHT); Graphics2D g2 = mySheetStencil.createGraphics(); g2.setColor(new JBColor(Gray._255, Gray._0)); g2.fillRect(0, 0, SHEET_WIDTH, SHEET_HEIGHT); g2.dispose(); ShadowRenderer renderer = new ShadowRenderer(); renderer.setSize(SHADOW_BORDER); renderer.setOpacity(.80f); renderer.setColor(new JBColor(JBColor.BLACK, Gray._10)); myShadowImage = renderer.createShadow(mySheetStencil); } private void handleMnemonics(int i, String buttonTitle) { buttons[i].setName(buttonTitle); buttons[i].setText(buttonTitle); setMnemonicsFromChar('&', buttons[i]); setMnemonicsFromChar('_', buttons[i]); } private static void setMnemonicsFromChar(char mnemonicChar, JButton button) { String buttonTitle = button.getText(); if (buttonTitle.indexOf(mnemonicChar) != -1) { button.setMnemonic(buttonTitle.charAt(buttonTitle.indexOf(mnemonicChar) + 1)); button.setText(buttonTitle.replace(Character.toString(mnemonicChar), "")); } } void requestFocus() { getGlobalInstance().doWhenFocusSettlesDown(() -> { if (myFocusedComponent != null) { getGlobalInstance().doWhenFocusSettlesDown(() -> getGlobalInstance().requestFocus(myFocusedComponent, true)); } else { LOG.debug("My focused component is null for the next message: " + messageTextPane.getText()); } }); } void setDefaultResult () { myResult = myDefaultButton.getName(); } void setFocusedResult () { if (myFocusedComponent instanceof JButton) { JButton focusedButton = (JButton)myFocusedComponent; myResult = focusedButton.getName(); } } void setResultAndStartClose(String result) { if (result != null) myResult = result; mySheetMessage.startAnimation(false); } JPanel getPanel(final JDialog w) { w.getRootPane().setDefaultButton(myDefaultButton); ActionListener actionListener = new ActionListener() { @Override public void actionPerformed(@NotNull ActionEvent e) { final String res = e.getSource() instanceof JButton ? ((JButton)e.getSource()).getName() : null; setResultAndStartClose(res); } }; mySheetPanel.registerKeyboardAction(actionListener, VK_ESC_KEYSTROKE, JComponent.WHEN_IN_FOCUSED_WINDOW); for (JButton button: buttons) { button.addActionListener(actionListener); } return mySheetPanel; } private static float getSheetAlpha() { return .95f; } private JPanel createSheetPanel(String title, String message, JButton[] buttons) { JPanel sheetPanel = new JPanel() { @Override protected void paintComponent(@NotNull Graphics g2d) { final Graphics2D g = (Graphics2D) g2d.create(); super.paintComponent(g); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getSheetAlpha())); g.setColor(new JBColor(Gray._230, UIUtil.getPanelBackground())); Rectangle dialog = new Rectangle(SHADOW_BORDER, 0, SHEET_WIDTH, SHEET_HEIGHT); paintShadow(g); // draw the sheet background if (UIUtil.isUnderDarcula()) { g.fillRoundRect((int)dialog.getX(), (int)dialog.getY() - 5, (int)dialog.getWidth(), (int)(5 + dialog.getHeight()), 5, 5); } else { //todo make bottom corners g.fill(dialog); } Border border = UIManager.getBorder("Window.border"); if (border != null) { border.paintBorder(this, g, dialog.x, dialog.y, dialog.width, dialog.height); } paintShadowFromParent(g); } }; sheetPanel.setOpaque(false); sheetPanel.setLayout(null); JPanel ico = new JPanel() { @Override protected void paintComponent(@NotNull Graphics g) { super.paintComponent(g); myIcon.paintIcon(this, g, 0, 0); } }; JEditorPane headerLabel = new JEditorPane(); headerLabel.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE); headerLabel.setFont(UIUtil.getLabelFont().deriveFont(Font.BOLD)); headerLabel.setEditable(false); headerLabel.setContentType("text/html"); headerLabel.setSize(250, Short.MAX_VALUE); headerLabel.setText(title); headerLabel.setSize(250, headerLabel.getPreferredSize().height); headerLabel.setOpaque(false); headerLabel.setFocusable(false); sheetPanel.add(headerLabel); headerLabel.repaint(); messageTextPane.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE); Font font = UIUtil.getLabelFont(UIUtil.FontSize.SMALL); messageTextPane.setFont(font); messageTextPane.setEditable(false); messageTextPane.setContentType("text/html"); messageTextPane.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent he) { if(he.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { if(Desktop.isDesktopSupported()) { try { URL url = he.getURL(); if (url != null) { Desktop.getDesktop().browse(url.toURI()); } else { LOG.warn("URL is null; HyperlinkEvent: " + he.toString()); } } catch (IOException | URISyntaxException e) { LOG.error(e); } } } } }); FontMetrics fontMetrics = sheetPanel.getFontMetrics(font); int widestWordWidth = 250; String [] words = (message == null) ? ArrayUtil.EMPTY_STRING_ARRAY : message.split(SPACE_OR_LINE_SEPARATOR_PATTERN); for (String word : words) { widestWordWidth = Math.max(fontMetrics.stringWidth(word), widestWordWidth); } messageTextPane.setSize(widestWordWidth, Short.MAX_VALUE); messageTextPane.setText(handleBreaks(message)); messageArea.setSize(widestWordWidth, messageTextPane.getPreferredSize().height); SHEET_WIDTH = Math.max(LEFT_SHEET_OFFSET + widestWordWidth + RIGHT_OFFSET, SHEET_WIDTH); messageTextPane.setSize(messageArea); messageTextPane.setOpaque(false); messageTextPane.setFocusable(false); sheetPanel.add(messageTextPane); messageTextPane.repaint(); ico.setOpaque(false); ico.setSize(new Dimension(AllIcons.Logo_welcomeScreen.getIconWidth(), AllIcons.Logo_welcomeScreen.getIconHeight())); ico.setLocation(LEFT_SHEET_PADDING, TOP_SHEET_PADDING); sheetPanel.add(ico); headerLabel.setLocation(LEFT_SHEET_OFFSET, TOP_SHEET_PADDING); messageTextPane.setLocation(LEFT_SHEET_OFFSET, TOP_SHEET_PADDING + headerLabel.getPreferredSize().height + GAP_BETWEEN_LINES); SHEET_HEIGHT = TOP_SHEET_PADDING + headerLabel.getPreferredSize().height + GAP_BETWEEN_LINES + messageArea.height + GAP_BETWEEN_LINES; if (myDoNotAskOption != null) { layoutDoNotAskCheckbox(sheetPanel); } layoutWithAbsoluteLayout(buttons, sheetPanel); int BOTTOM_SHEET_PADDING = 10; SHEET_HEIGHT += BOTTOM_SHEET_PADDING; if (SHEET_HEIGHT < SHEET_MINIMUM_HEIGHT) { SHEET_HEIGHT = SHEET_MINIMUM_HEIGHT; shiftButtonsToTheBottom(SHEET_MINIMUM_HEIGHT - SHEET_HEIGHT); } sheetPanel.setFocusCycleRoot(true); recalculateShadow(); sheetPanel.setSize(SHEET_NC_WIDTH, SHEET_NC_HEIGHT); return sheetPanel; } private static String handleBreaks(final String message) { return message == null ? "" : message.replaceAll("(\r\n|\n)", "<br/>"); } private void shiftButtonsToTheBottom(int shiftDistance) { for (JButton b : buttons) { b.setLocation(b.getX(), b.getY() + shiftDistance); } } private void recalculateShadow() { SHEET_NC_WIDTH = SHEET_WIDTH + SHADOW_BORDER * 2; SHEET_NC_HEIGHT = SHEET_HEIGHT + SHADOW_BORDER; } private void layoutWithAbsoluteLayout(JButton[] buttons, JPanel sheetPanel) { layoutButtons(buttons, sheetPanel); } private void paintShadow(Graphics2D g2d) { g2d.setBackground(new JBColor(new Color(255, 255, 255, 0), new Color(110, 110, 110, 0))); g2d.clearRect(0, 0, SHEET_NC_WIDTH, SHEET_HEIGHT); g2d.drawImage(myShadowImage, 0, -SHADOW_BORDER, null); g2d.clearRect(SHADOW_BORDER, 0, SHEET_WIDTH, SHEET_HEIGHT); } private static float getShadowAlpha() { return ((UIUtil.isUnderDarcula())) ? .85f : .35f; } private void paintShadowFromParent(Graphics2D g2d) { g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getShadowAlpha())); g2d.drawImage(myShadowImage, 0, - SHEET_HEIGHT - SHADOW_BORDER, null); } private void layoutButtons(final JButton[] buttons, JPanel panel) { //int widestButtonWidth = 0; int buttonWidth = 0; SHEET_HEIGHT += GAP_BETWEEN_LINES; for (int i = 0; i < buttons.length; i ++) { buttons[i].repaint(); buttons[i].setSize(buttons[i].getPreferredSize()); buttonWidth += buttons[i].getWidth(); if (i == buttons.length - 1) break; buttonWidth += GAP_BETWEEN_BUTTONS; } int buttonsRowWidth = LEFT_SHEET_OFFSET + buttonWidth + RIGHT_OFFSET; // update the pane if the sheet is going to be wider messageTextPane.setSize(Math.max(messageTextPane.getWidth(), buttonWidth), messageTextPane.getHeight()); SHEET_WIDTH = Math.max(buttonsRowWidth, SHEET_WIDTH); int buttonShift = RIGHT_OFFSET; for (JButton button : buttons) { Dimension size = button.getSize(); buttonShift += size.width; button.setBounds(SHEET_WIDTH - buttonShift, SHEET_HEIGHT, size.width, size.height); panel.add(button); buttonShift += GAP_BETWEEN_BUTTONS; } SHEET_HEIGHT += buttons[0].getHeight(); } private void layoutDoNotAskCheckbox(JPanel sheetPanel) { doNotAskCheckBox.setText(myDoNotAskOption.getDoNotShowMessage()); doNotAskCheckBox.setVisible(myDoNotAskOption.canBeHidden()); doNotAskCheckBox.setSelected(!myDoNotAskOption.isToBeShown()); doNotAskCheckBox.setOpaque(false); doNotAskCheckBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(@NotNull ItemEvent e) { myDoNotAskResult = (e.getStateChange() == ItemEvent.SELECTED); } }); doNotAskCheckBox.repaint(); doNotAskCheckBox.setSize(doNotAskCheckBox.getPreferredSize()); doNotAskCheckBox.setLocation(LEFT_SHEET_OFFSET, SHEET_HEIGHT); sheetPanel.add(doNotAskCheckBox); if (myFocusedComponent == null) { myFocusedComponent = doNotAskCheckBox; } SHEET_HEIGHT += doNotAskCheckBox.getHeight(); } /** * This method is used to show an image during message showing * @return image to show */ Image getStaticImage() { final JFrame myOffScreenFrame = new JFrame() ; myOffScreenFrame.add(mySheetPanel); myOffScreenFrame.getRootPane().setDefaultButton(myDefaultButton); BufferedImage image = UIUtil.createImage(SHEET_NC_WIDTH, SHEET_NC_HEIGHT, BufferedImage.TYPE_INT_ARGB); Graphics g = image.createGraphics(); mySheetPanel.paint(g); g.dispose(); myOffScreenFrame.remove(mySheetPanel); myOffScreenFrame.dispose(); return image; } JPanel getSheetPanel() { return mySheetPanel; } public boolean getDoNotAskResult () { return myDoNotAskResult; } public String getResult() { return myResult; } @Override public void dispose() { mySheetPanel.unregisterKeyboardAction(VK_ESC_KEYSTROKE); mySheetMessage = null; } }
Handle mnemonics correctly in SheetMessage
platform/platform-impl/src/com/intellij/ui/messages/SheetController.java
Handle mnemonics correctly in SheetMessage
<ide><path>latform/platform-impl/src/com/intellij/ui/messages/SheetController.java <ide> // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. <ide> package com.intellij.ui.messages; <ide> <add>import com.intellij.BundleBase; <ide> import com.intellij.icons.AllIcons; <ide> import com.intellij.openapi.Disposable; <ide> import com.intellij.openapi.diagnostic.Logger; <ide> myShadowImage = renderer.createShadow(mySheetStencil); <ide> } <ide> <del> private void handleMnemonics(int i, String buttonTitle) { <del> buttons[i].setName(buttonTitle); <del> buttons[i].setText(buttonTitle); <del> setMnemonicsFromChar('&', buttons[i]); <del> setMnemonicsFromChar('_', buttons[i]); <del> } <del> <del> private static void setMnemonicsFromChar(char mnemonicChar, JButton button) { <del> String buttonTitle = button.getText(); <del> if (buttonTitle.indexOf(mnemonicChar) != -1) { <del> button.setMnemonic(buttonTitle.charAt(buttonTitle.indexOf(mnemonicChar) + 1)); <del> button.setText(buttonTitle.replace(Character.toString(mnemonicChar), "")); <add> private void handleMnemonics(int i, String title) { <add> buttons[i].setName(title); <add> <add> if (!setButtonTextAndMnemonic(i, title, '_') && <add> !setButtonTextAndMnemonic(i, title, '&') && <add> !setButtonTextAndMnemonic(i, title, BundleBase.MNEMONIC)) { <add> buttons[i].setText(title); <add> } <add> } <add> <add> private boolean setButtonTextAndMnemonic(int i, String title, char mnemonics) { <add> int mIdx; <add> if ((mIdx = title.indexOf(mnemonics)) >= 0) { <add> String text = title.substring(0, mIdx) + title.substring(mIdx + 1); <add> <add> buttons[i].setText(text); <add> buttons[i].setDisplayedMnemonicIndex(mIdx); <add> return true; <add> } <add> else { <add> return false; <ide> } <ide> } <ide>
Java
lgpl-2.1
d35d9fb4e64ea29e74f40ad9c18c90d037643504
0
drhee/toxoMine,zebrafishmine/intermine,JoeCarlson/intermine,JoeCarlson/intermine,drhee/toxoMine,zebrafishmine/intermine,tomck/intermine,justincc/intermine,zebrafishmine/intermine,joshkh/intermine,elsiklab/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,kimrutherford/intermine,elsiklab/intermine,justincc/intermine,drhee/toxoMine,elsiklab/intermine,kimrutherford/intermine,tomck/intermine,kimrutherford/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,tomck/intermine,drhee/toxoMine,zebrafishmine/intermine,JoeCarlson/intermine,tomck/intermine,elsiklab/intermine,kimrutherford/intermine,tomck/intermine,drhee/toxoMine,joshkh/intermine,elsiklab/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,JoeCarlson/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,justincc/intermine,zebrafishmine/intermine,justincc/intermine,drhee/toxoMine,drhee/toxoMine,JoeCarlson/intermine,zebrafishmine/intermine,justincc/intermine,elsiklab/intermine,zebrafishmine/intermine,tomck/intermine,joshkh/intermine,tomck/intermine,kimrutherford/intermine,elsiklab/intermine,tomck/intermine,drhee/toxoMine,kimrutherford/intermine,kimrutherford/intermine,JoeCarlson/intermine,joshkh/intermine,tomck/intermine,joshkh/intermine,elsiklab/intermine,kimrutherford/intermine,justincc/intermine,joshkh/intermine,joshkh/intermine,JoeCarlson/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine
package org.flymine.postprocess; /* * Copyright (C) 2002-2005 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.objectstore.query.ConstraintSet; import org.intermine.objectstore.query.ContainsConstraint; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.QueryField; import org.intermine.objectstore.query.QueryObjectReference; import org.intermine.objectstore.query.Results; import org.intermine.objectstore.query.ResultsRow; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.ObjectStoreWriter; import org.intermine.objectstore.intermine.ObjectStoreInterMineImpl; import org.intermine.objectstore.proxy.ProxyReference; import org.intermine.util.DynamicUtil; import org.flymine.model.genomic.Assembly; import org.flymine.model.genomic.Chromosome; import org.flymine.model.genomic.ChromosomeBand; import org.flymine.model.genomic.Exon; import org.flymine.model.genomic.Gene; import org.flymine.model.genomic.LocatedSequenceFeature; import org.flymine.model.genomic.Location; import org.flymine.model.genomic.RankedRelation; import org.flymine.model.genomic.Sequence; import org.flymine.model.genomic.Supercontig; import org.flymine.model.genomic.Transcript; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import org.apache.log4j.Logger; import org.biojava.bio.seq.DNATools; import org.biojava.bio.symbol.IllegalAlphabetException; import org.biojava.bio.symbol.IllegalSymbolException; import org.biojava.bio.symbol.SymbolList; /** * Transfer sequences from the Assembly objects to the other objects that are located on the * Assemblys and to the objects that the Assemblys are located on (eg. Chromosomes). * * @author Kim Rutherford */ public class TransferSequences { protected ObjectStoreWriter osw; private static final Logger LOG = Logger.getLogger(TransferSequences.class); /** * Create a new TransferSequences object from the given ObjectStoreWriter * @param osw writer on genomic ObjectStore */ public TransferSequences (ObjectStoreWriter osw) { this.osw = osw; } /** * Copy the Assembly sequences to the appropriate place in the chromosome sequences and store a * Sequence object for each Chromosome. Uses the ObjectStoreWriter that was passed to the * constructor * @throws Exception if there are problems with the transfer */ public void transferToChromosome() throws Exception { ObjectStore os = osw.getObjectStore(); Results results = PostProcessUtil.findLocationAndObjects(os, Chromosome.class, Assembly.class, false); // could try reducing further if still OutOfMemeory problems results.setBatchSize(20); results.setNoPrefetch(); Map chromosomeTempFiles = new HashMap(); Iterator resIter = results.iterator(); Chromosome currentChr = null; RandomAccessFile currentChrBases = null; while (resIter.hasNext()) { ResultsRow rr = (ResultsRow) resIter.next(); Integer chrId = (Integer) rr.get(0); Chromosome chr = (Chromosome) os.getObjectById(chrId); Assembly assembly = (Assembly) rr.get(1); Location assemblyOnChrLocation = (Location) rr.get(2); if (assembly instanceof Supercontig) { continue; } if (currentChr == null || !chr.equals(currentChr)) { if (currentChr != null) { currentChrBases.close(); LOG.info("finished writing temp file for Chromosome: " + currentChr.getIdentifier()); } File tempFile = getTempFile(chr); currentChrBases = getChromosomeTempSeqFile(chr, tempFile); chromosomeTempFiles.put(chr, tempFile); currentChr = chr; } copySeqArray(currentChrBases, assembly.getSequence().getResidues(), assemblyOnChrLocation.getStart().intValue(), assemblyOnChrLocation.getStrand().intValue()); } if (currentChrBases == null) { LOG.error("in transferToChromosome(): no Assembly sequences found"); } else { currentChrBases.close(); storeTempSequences(chromosomeTempFiles); LOG.info("finished writing temp file for Chromosome: " + currentChr.getIdentifier()); } } private File getTempFile(Chromosome chr) throws IOException { String prefix = "transfer_sequences_temp_" + chr.getId() + "_" + chr.getIdentifier(); return File.createTempFile(prefix, null, new File ("build")); } /** * Initialise the given File by setting it's length to the length of the Chromosome and * initialising it with "." characters. * @throws IOException */ private RandomAccessFile getChromosomeTempSeqFile(Chromosome chr, File tempFile) throws IOException { RandomAccessFile raf = new RandomAccessFile(tempFile, "rw"); byte[] bytes; try { bytes = ("......................................................................." + ".............................................").getBytes("US-ASCII"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("unexpected exception", e); } int writeCount = chr.getLength().intValue() / bytes.length + 1; // fill with '.' so we can see the parts of the Chromosome sequence that haven't // been set for (int i = 0; i < writeCount; i++) { raf.write(bytes); } raf.setLength(chr.getLength().longValue()); return raf; } private void storeTempSequences(Map chromosomeTempFiles) throws ObjectStoreException, IOException { Iterator chromosomeTempFilesIter = chromosomeTempFiles.keySet().iterator(); while (chromosomeTempFilesIter.hasNext()) { Chromosome chr = (Chromosome) chromosomeTempFilesIter.next(); File file = (File) chromosomeTempFiles.get(chr); FileReader reader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(reader); String sequenceString = bufferedReader.readLine(); osw.beginTransaction(); storeNewSequence(chr, sequenceString); osw.commitTransaction(); } } private void storeNewSequence(LocatedSequenceFeature feature, String sequenceString) throws ObjectStoreException { Sequence sequence = (Sequence) DynamicUtil.createObject(Collections.singleton(Sequence.class)); sequence.setResidues(sequenceString); sequence.setLength(sequenceString.length()); osw.store(sequence); feature.proxySequence(new ProxyReference(osw.getObjectStore(), sequence.getId(), Sequence.class)); feature.setLength(new Integer(sequenceString.length())); osw.store(feature); } /** * Use the Location relations to copy the sequence from the Chromosomes to every * LocatedSequenceFeature that is located on a Chromosome and which doesn't already have a * sequence (ie. don't copy to Assembly). Uses the ObjectStoreWriter that was passed to the * constructor * @throws Exception if there are problems with the transfer */ public void transferToLocatedSequenceFeatures() throws Exception { ObjectStore os = osw.getObjectStore(); osw.beginTransaction(); Results results = PostProcessUtil.findLocationAndObjects(os, Chromosome.class, LocatedSequenceFeature.class, true); results.setBatchSize(500); Iterator resIter = results.iterator(); long start = System.currentTimeMillis(); int i = 0; while (resIter.hasNext()) { ResultsRow rr = (ResultsRow) resIter.next(); Integer chrId = (Integer) rr.get(0); LocatedSequenceFeature feature = (LocatedSequenceFeature) rr.get(1); Location locationOnChr = (Location) rr.get(2); if (feature instanceof Assembly) { LOG.error("in transferToLocatedSequenceFeatures() ignoring: " + feature); continue; } if (feature instanceof ChromosomeBand) { LOG.error("in transferToLocatedSequenceFeatures() ignoring: " + feature); continue; } if (feature instanceof Transcript) { LOG.error("in transferToLocatedSequenceFeatures() ignoring: " + feature); continue; } if (feature instanceof Gene) { Gene gene = (Gene) feature; if (gene.getLength().intValue() > 2000000) { LOG.error("gene too long in transferToLocatedSequenceFeatures() ignoring: " + gene); continue; } } Chromosome chr = (Chromosome) os.getObjectById(chrId); Sequence chromosomeSequence = chr.getSequence(); if (chromosomeSequence == null) { throw new Exception("no sequence found for: " + chr.getIdentifier() + " id: " + chr.getId()); } String featureSeq = getSubSequence(chromosomeSequence, locationOnChr); if (featureSeq == null) { // probably the locationOnChr is out of range continue; } Sequence sequence = (Sequence) DynamicUtil.createObject(Collections.singleton(Sequence.class)); sequence.setResidues(featureSeq); sequence.setLength(featureSeq.length()); osw.store(sequence); feature.proxySequence(new ProxyReference(osw.getObjectStore(), sequence.getId(), Sequence.class)); osw.store(feature); i++; if (i % 1000 == 0) { long now = System.currentTimeMillis(); LOG.info("Set sequences for " + i + " features" + " (avg = " + ((60000L * i) / (now - start)) + " per minute)"); } } osw.commitTransaction(); } private String getSubSequence(Sequence chromosomeSequence, Location locationOnChr) throws IllegalSymbolException, IllegalAlphabetException { int charsToCopy = locationOnChr.getEnd().intValue() - locationOnChr.getStart().intValue() + 1; String chromosomeSequenceString = chromosomeSequence.getResidues(); if (charsToCopy > chromosomeSequenceString.length()) { LOG.error("LocatedSequenceFeature too long, ignoring - Location: " + locationOnChr.getId() + " LSF id: " + locationOnChr.getObject()); return null; } int startPos = locationOnChr.getStart().intValue() - 1; int endPos = startPos + charsToCopy; if (startPos < 0 || endPos < 0) { return ""; // TODO XXX FIXME - uncomment this // throw new RuntimeException("in TransferSequences.getSubSequence(): locationOnChr " // + locationOnChr // + "\n startPos: " + startPos + " endPos " + endPos // + "\n chromosomeSequence.substr(0,1000) " + // chromosomeSequenceString.substring(0,1000) // + "\n location.getObject() " // + locationOnChr.getObject().toString() // + " location.getSubject() " + // locationOnChr.getSubject().toString() + " " // + "\n location.getSubject().getId() " + // locationOnChr.getSubject().getId() + // "\n location.getObject().getId() "); } String subSeqString = new String(chromosomeSequenceString.substring(startPos, endPos)); if (locationOnChr.getStrand().intValue() == -1) { SymbolList symbolList = DNATools.createDNA(subSeqString); symbolList = DNATools.reverseComplement(symbolList); subSeqString = symbolList.seqString(); } return subSeqString; } private void copySeqArray(RandomAccessFile raf, String sourceSequence, int start, int strand) throws IllegalSymbolException, IllegalAlphabetException, IOException { byte[] byteArray = new byte[sourceSequence.length()]; if (strand == -1) { SymbolList symbolList = DNATools.createDNA(sourceSequence); symbolList = DNATools.reverseComplement(symbolList); byteArray = symbolList.seqString().getBytes("US-ASCII"); } else { byteArray = sourceSequence.toLowerCase().getBytes("US-ASCII"); } raf.seek(start - 1); raf.write(byteArray); } /** * For each Transcript, join and transfer the sequences from the child Exons to a new Sequence * object for the Transcript. Uses the ObjectStoreWriter that was passed to the constructor * @throws Exception if there are problems with the transfer */ public void transferToTranscripts() throws Exception { osw.beginTransaction(); ObjectStore os = osw.getObjectStore(); Query q = new Query(); q.setDistinct(false); QueryClass qcTranscript = new QueryClass(Transcript.class); q.addFrom(qcTranscript); q.addToSelect(qcTranscript); q.addToOrderBy(qcTranscript); QueryClass qcRankedRelation = new QueryClass(RankedRelation.class); q.addFrom(qcRankedRelation); q.addToSelect(qcRankedRelation); QueryField qfObj = new QueryField(qcRankedRelation, "rank"); q.addToOrderBy(qfObj); QueryClass qcExon = new QueryClass(Exon.class); q.addFrom(qcExon); q.addToSelect(qcExon); QueryClass qcExonSequence = new QueryClass(Sequence.class); q.addFrom(qcExonSequence); q.addToSelect(qcExonSequence); ConstraintSet cs = new ConstraintSet(ConstraintOp.AND); QueryObjectReference rankTransRef = new QueryObjectReference(qcRankedRelation, "object"); ContainsConstraint cc1 = new ContainsConstraint(rankTransRef, ConstraintOp.CONTAINS, qcTranscript); cs.addConstraint(cc1); QueryObjectReference rankExonRef = new QueryObjectReference(qcRankedRelation, "subject"); ContainsConstraint cc2 = new ContainsConstraint(rankExonRef, ConstraintOp.CONTAINS, qcExon); cs.addConstraint(cc2); QueryObjectReference sequenceRef = new QueryObjectReference(qcExon, "sequence"); ContainsConstraint cc3 = new ContainsConstraint(sequenceRef, ConstraintOp.CONTAINS, qcExonSequence); cs.addConstraint(cc3); q.setConstraint(cs); ((ObjectStoreInterMineImpl) os).precompute(q, PostProcessTask.PRECOMPUTE_CATEGORY); Results res = new Results(q, os, os.getSequence()); res.setBatchSize(200); Iterator resIter = res.iterator(); Transcript currentTranscript = null; StringBuffer currentTranscriptBases = new StringBuffer(); long start = System.currentTimeMillis(); int i = 0; while (resIter.hasNext()) { ResultsRow rr = (ResultsRow) resIter.next(); Transcript transcript = (Transcript) rr.get(0); Exon exon = (Exon) rr.get(2); if (currentTranscript == null || !transcript.equals(currentTranscript)) { if (currentTranscript != null) { storeNewSequence(currentTranscript, currentTranscriptBases.toString()); i++; } currentTranscriptBases = new StringBuffer(); currentTranscript = transcript; } currentTranscriptBases.append(exon.getSequence().getResidues()); if (i % 100 == 0) { long now = System.currentTimeMillis(); LOG.info("Set sequences for " + i + " Transcripts" + " (avg = " + ((60000L * i) / (now - start)) + " per minute)"); } } if (currentTranscript == null) { LOG.error("in transferToTranscripts(): no Transcripts found"); } else { storeNewSequence(currentTranscript, currentTranscriptBases.toString()); } osw.commitTransaction(); } }
flymine/model/genomic/src/java/org/flymine/postprocess/TransferSequences.java
package org.flymine.postprocess; /* * Copyright (C) 2002-2005 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.objectstore.query.ConstraintSet; import org.intermine.objectstore.query.ContainsConstraint; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.QueryField; import org.intermine.objectstore.query.QueryObjectReference; import org.intermine.objectstore.query.Results; import org.intermine.objectstore.query.ResultsRow; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.ObjectStoreWriter; import org.intermine.objectstore.intermine.ObjectStoreInterMineImpl; import org.intermine.util.DynamicUtil; import org.flymine.model.genomic.Assembly; import org.flymine.model.genomic.Chromosome; import org.flymine.model.genomic.ChromosomeBand; import org.flymine.model.genomic.Exon; import org.flymine.model.genomic.Gene; import org.flymine.model.genomic.LocatedSequenceFeature; import org.flymine.model.genomic.Location; import org.flymine.model.genomic.RankedRelation; import org.flymine.model.genomic.Sequence; import org.flymine.model.genomic.Supercontig; import org.flymine.model.genomic.Transcript; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import org.apache.log4j.Logger; import org.biojava.bio.seq.DNATools; import org.biojava.bio.symbol.IllegalAlphabetException; import org.biojava.bio.symbol.IllegalSymbolException; import org.biojava.bio.symbol.SymbolList; /** * Transfer sequences from the Assembly objects to the other objects that are located on the * Assemblys and to the objects that the Assemblys are located on (eg. Chromosomes). * * @author Kim Rutherford */ public class TransferSequences { protected ObjectStoreWriter osw; private static final Logger LOG = Logger.getLogger(TransferSequences.class); /** * Create a new TransferSequences object from the given ObjectStoreWriter * @param osw writer on genomic ObjectStore */ public TransferSequences (ObjectStoreWriter osw) { this.osw = osw; } /** * Copy the Assembly sequences to the appropriate place in the chromosome sequences and store a * Sequence object for each Chromosome. Uses the ObjectStoreWriter that was passed to the * constructor * @throws Exception if there are problems with the transfer */ public void transferToChromosome() throws Exception { ObjectStore os = osw.getObjectStore(); Results results = PostProcessUtil.findLocationAndObjects(os, Chromosome.class, Assembly.class, false); // could try reducing further if still OutOfMemeory problems results.setBatchSize(20); results.setNoPrefetch(); Map chromosomeTempFiles = new HashMap(); Iterator resIter = results.iterator(); Chromosome currentChr = null; RandomAccessFile currentChrBases = null; while (resIter.hasNext()) { ResultsRow rr = (ResultsRow) resIter.next(); Integer chrId = (Integer) rr.get(0); Chromosome chr = (Chromosome) os.getObjectById(chrId); Assembly assembly = (Assembly) rr.get(1); Location assemblyOnChrLocation = (Location) rr.get(2); if (assembly instanceof Supercontig) { continue; } if (currentChr == null || !chr.equals(currentChr)) { if (currentChr != null) { currentChrBases.close(); LOG.info("finished writing temp file for Chromosome: " + currentChr.getIdentifier()); } File tempFile = getTempFile(chr); currentChrBases = getChromosomeTempSeqFile(chr, tempFile); chromosomeTempFiles.put(chr, tempFile); currentChr = chr; } copySeqArray(currentChrBases, assembly.getSequence().getResidues(), assemblyOnChrLocation.getStart().intValue(), assemblyOnChrLocation.getStrand().intValue()); } if (currentChrBases == null) { LOG.error("in transferToChromosome(): no Assembly sequences found"); } else { currentChrBases.close(); storeTempSequences(chromosomeTempFiles); LOG.info("finished writing temp file for Chromosome: " + currentChr.getIdentifier()); } } private File getTempFile(Chromosome chr) throws IOException { String prefix = "transfer_sequences_temp_" + chr.getId() + "_" + chr.getIdentifier(); return File.createTempFile(prefix, null, new File ("build")); } /** * Initialise the given File by setting it's length to the length of the Chromosome and * initialising it with "." characters. * @throws IOException */ private RandomAccessFile getChromosomeTempSeqFile(Chromosome chr, File tempFile) throws IOException { RandomAccessFile raf = new RandomAccessFile(tempFile, "rw"); byte[] bytes; try { bytes = ("......................................................................." + ".............................................").getBytes("US-ASCII"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("unexpected exception", e); } int writeCount = chr.getLength().intValue() / bytes.length + 1; // fill with '.' so we can see the parts of the Chromosome sequence that haven't // been set for (int i = 0; i < writeCount ; i++) { raf.write(bytes); } raf.setLength(chr.getLength().longValue()); return raf; } private void storeTempSequences(Map chromosomeTempFiles) throws ObjectStoreException, IOException { Iterator chromosomeTempFilesIter = chromosomeTempFiles.keySet().iterator(); while (chromosomeTempFilesIter.hasNext()) { Chromosome chr = (Chromosome) chromosomeTempFilesIter.next(); File file = (File) chromosomeTempFiles.get(chr); FileReader reader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(reader); String sequenceString = bufferedReader.readLine(); osw.beginTransaction(); storeNewSequence(chr, sequenceString); osw.commitTransaction(); } } private void storeNewSequence(LocatedSequenceFeature feature, String sequenceString) throws ObjectStoreException { Sequence sequence = (Sequence) DynamicUtil.createObject(Collections.singleton(Sequence.class)); sequence.setResidues(sequenceString); sequence.setLength(sequenceString.length()); feature.setSequence(sequence); feature.setLength(new Integer(sequenceString.length())); osw.store(feature); osw.store(sequence); } /** * Use the Location relations to copy the sequence from the Chromosomes to every * LocatedSequenceFeature that is located on a Chromosome and which doesn't already have a * sequence (ie. don't copy to Assembly). Uses the ObjectStoreWriter that was passed to the * constructor * @throws Exception if there are problems with the transfer */ public void transferToLocatedSequenceFeatures() throws Exception { ObjectStore os = osw.getObjectStore(); osw.beginTransaction(); Results results = PostProcessUtil.findLocationAndObjects(os, Chromosome.class, LocatedSequenceFeature.class, true); results.setBatchSize(500); Iterator resIter = results.iterator(); long start = System.currentTimeMillis(); int i = 0; while (resIter.hasNext()) { ResultsRow rr = (ResultsRow) resIter.next(); Integer chrId = (Integer) rr.get(0); LocatedSequenceFeature feature = (LocatedSequenceFeature) rr.get(1); Location locationOnChr = (Location) rr.get(2); if (feature instanceof Assembly) { LOG.error("in transferToLocatedSequenceFeatures() ignoring: " + feature); continue; } if (feature instanceof ChromosomeBand) { LOG.error("in transferToLocatedSequenceFeatures() ignoring: " + feature); continue; } if (feature instanceof Transcript) { LOG.error("in transferToLocatedSequenceFeatures() ignoring: " + feature); continue; } if (feature instanceof Gene) { Gene gene = (Gene) feature; if (gene.getLength().intValue() > 2000000) { LOG.error("gene too long in transferToLocatedSequenceFeatures() ignoring: " + gene); continue; } } Chromosome chr = (Chromosome) os.getObjectById(chrId); Sequence chromosomeSequence = chr.getSequence(); if (chromosomeSequence == null) { throw new Exception("no sequence found for: " + chr.getIdentifier() + " id: " + chr.getId()); } String featureSeq = getSubSequence(chromosomeSequence, locationOnChr); if (featureSeq == null) { // probably the locationOnChr is out of range continue; } Sequence sequence = (Sequence) DynamicUtil.createObject(Collections.singleton(Sequence.class)); sequence.setResidues(featureSeq); sequence.setLength(featureSeq.length()); feature.setSequence(sequence); osw.store(feature); osw.store(sequence); i++; if (i % 1000 == 0) { long now = System.currentTimeMillis(); LOG.info("Set sequences for " + i + " features" + " (avg = " + ((60000L * i) / (now - start)) + " per minute)"); } } osw.commitTransaction(); } private String getSubSequence(Sequence chromosomeSequence, Location locationOnChr) throws IllegalSymbolException, IllegalAlphabetException { int charsToCopy = locationOnChr.getEnd().intValue() - locationOnChr.getStart().intValue() + 1; String chromosomeSequenceString = chromosomeSequence.getResidues(); if (charsToCopy > chromosomeSequenceString.length()) { LOG.error("LocatedSequenceFeature too long, ignoring - Location: " + locationOnChr.getId() + " LSF id: " + locationOnChr.getObject()); return null; } int startPos = locationOnChr.getStart().intValue() - 1; int endPos = startPos + charsToCopy; if (startPos < 0 || endPos < 0) { return ""; // TODO XXX FIXME - uncomment this // throw new RuntimeException("in TransferSequences.getSubSequence(): locationOnChr " // + locationOnChr // + "\n startPos: " + startPos + " endPos " + endPos // + "\n chromosomeSequence.substr(0,1000) " + // chromosomeSequenceString.substring(0,1000) // + "\n location.getObject() " // + locationOnChr.getObject().toString() // + " location.getSubject() " + // locationOnChr.getSubject().toString() + " " // + "\n location.getSubject().getId() " + // locationOnChr.getSubject().getId() + // "\n location.getObject().getId() "); } String subSeqString = new String(chromosomeSequenceString.substring(startPos, endPos)); if (locationOnChr.getStrand().intValue() == -1) { SymbolList symbolList = DNATools.createDNA(subSeqString); symbolList = DNATools.reverseComplement(symbolList); subSeqString = symbolList.seqString(); } return subSeqString; } private void copySeqArray(RandomAccessFile raf, String sourceSequence, int start, int strand) throws IllegalSymbolException, IllegalAlphabetException, IOException { byte[] byteArray = new byte[sourceSequence.length()]; if (strand == -1) { SymbolList symbolList = DNATools.createDNA(sourceSequence); symbolList = DNATools.reverseComplement(symbolList); byteArray = symbolList.seqString().getBytes("US-ASCII"); } else { byteArray = sourceSequence.toLowerCase().getBytes("US-ASCII"); } raf.seek(start - 1); raf.write(byteArray); } /** * For each Transcript, join and transfer the sequences from the child Exons to a new Sequence * object for the Transcript. Uses the ObjectStoreWriter that was passed to the constructor * @throws Exception if there are problems with the transfer */ public void transferToTranscripts() throws Exception { osw.beginTransaction(); ObjectStore os = osw.getObjectStore(); Query q = new Query(); q.setDistinct(false); QueryClass qcTranscript = new QueryClass(Transcript.class); q.addFrom(qcTranscript); q.addToSelect(qcTranscript); q.addToOrderBy(qcTranscript); QueryClass qcRankedRelation = new QueryClass(RankedRelation.class); q.addFrom(qcRankedRelation); q.addToSelect(qcRankedRelation); QueryField qfObj = new QueryField(qcRankedRelation, "rank"); q.addToOrderBy(qfObj); QueryClass qcExon = new QueryClass(Exon.class); q.addFrom(qcExon); q.addToSelect(qcExon); QueryClass qcExonSequence = new QueryClass(Sequence.class); q.addFrom(qcExonSequence); q.addToSelect(qcExonSequence); ConstraintSet cs = new ConstraintSet(ConstraintOp.AND); QueryObjectReference rankTransRef = new QueryObjectReference(qcRankedRelation, "object"); ContainsConstraint cc1 = new ContainsConstraint(rankTransRef, ConstraintOp.CONTAINS, qcTranscript); cs.addConstraint(cc1); QueryObjectReference rankExonRef = new QueryObjectReference(qcRankedRelation, "subject"); ContainsConstraint cc2 = new ContainsConstraint(rankExonRef, ConstraintOp.CONTAINS, qcExon); cs.addConstraint(cc2); QueryObjectReference sequenceRef = new QueryObjectReference(qcExon, "sequence"); ContainsConstraint cc3 = new ContainsConstraint(sequenceRef, ConstraintOp.CONTAINS, qcExonSequence); cs.addConstraint(cc3); q.setConstraint(cs); ((ObjectStoreInterMineImpl) os).precompute(q, PostProcessTask.PRECOMPUTE_CATEGORY); Results res = new Results(q, os, os.getSequence()); res.setBatchSize(200); Iterator resIter = res.iterator(); Transcript currentTranscript = null; StringBuffer currentTranscriptBases = new StringBuffer(); long start = System.currentTimeMillis(); int i = 0; while (resIter.hasNext()) { ResultsRow rr = (ResultsRow) resIter.next(); Transcript transcript = (Transcript) rr.get(0); Exon exon = (Exon) rr.get(2); if (currentTranscript == null || !transcript.equals(currentTranscript)) { if (currentTranscript != null) { storeNewSequence(currentTranscript, currentTranscriptBases.toString()); i++; } currentTranscriptBases = new StringBuffer(); currentTranscript = transcript; } currentTranscriptBases.append(exon.getSequence().getResidues()); if (i % 100 == 0) { long now = System.currentTimeMillis(); LOG.info("Set sequences for " + i + " Transcripts" + " (avg = " + ((60000L * i) / (now - start)) + " per minute)"); } } if (currentTranscript == null) { LOG.error("in transferToTranscripts(): no Transcripts found"); } else { storeNewSequence(currentTranscript, currentTranscriptBases.toString()); } osw.commitTransaction(); } }
Set LocatedSequenceFeature.sequence as a proxy to allow sequence objects to be garbage collected, is much more memory efficient.
flymine/model/genomic/src/java/org/flymine/postprocess/TransferSequences.java
Set LocatedSequenceFeature.sequence as a proxy to allow sequence objects to be garbage collected, is much more memory efficient.
<ide><path>lymine/model/genomic/src/java/org/flymine/postprocess/TransferSequences.java <ide> import org.intermine.objectstore.ObjectStoreException; <ide> import org.intermine.objectstore.ObjectStoreWriter; <ide> import org.intermine.objectstore.intermine.ObjectStoreInterMineImpl; <add>import org.intermine.objectstore.proxy.ProxyReference; <ide> import org.intermine.util.DynamicUtil; <ide> <ide> import org.flymine.model.genomic.Assembly; <ide> if (currentChr == null || !chr.equals(currentChr)) { <ide> if (currentChr != null) { <ide> currentChrBases.close(); <del> LOG.info("finished writing temp file for Chromosome: " + currentChr.getIdentifier()); <add> LOG.info("finished writing temp file for Chromosome: " <add> + currentChr.getIdentifier()); <ide> } <ide> <ide> File tempFile = getTempFile(chr); <ide> <ide> // fill with '.' so we can see the parts of the Chromosome sequence that haven't <ide> // been set <del> for (int i = 0; i < writeCount ; i++) { <add> for (int i = 0; i < writeCount; i++) { <ide> raf.write(bytes); <ide> } <ide> <ide> (Sequence) DynamicUtil.createObject(Collections.singleton(Sequence.class)); <ide> sequence.setResidues(sequenceString); <ide> sequence.setLength(sequenceString.length()); <del> feature.setSequence(sequence); <add> osw.store(sequence); <add> feature.proxySequence(new ProxyReference(osw.getObjectStore(), <add> sequence.getId(), Sequence.class)); <ide> feature.setLength(new Integer(sequenceString.length())); <ide> osw.store(feature); <del> osw.store(sequence); <ide> } <ide> <ide> /** <ide> (Sequence) DynamicUtil.createObject(Collections.singleton(Sequence.class)); <ide> sequence.setResidues(featureSeq); <ide> sequence.setLength(featureSeq.length()); <del> feature.setSequence(sequence); <add> osw.store(sequence); <add> feature.proxySequence(new ProxyReference(osw.getObjectStore(), <add> sequence.getId(), Sequence.class)); <ide> osw.store(feature); <del> osw.store(sequence); <ide> i++; <ide> if (i % 1000 == 0) { <ide> long now = System.currentTimeMillis(); <ide> String chromosomeSequenceString = chromosomeSequence.getResidues(); <ide> <ide> if (charsToCopy > chromosomeSequenceString.length()) { <del> LOG.error("LocatedSequenceFeature too long, ignoring - Location: " + <del> locationOnChr.getId() + " LSF id: " + locationOnChr.getObject()); <add> LOG.error("LocatedSequenceFeature too long, ignoring - Location: " <add> + locationOnChr.getId() + " LSF id: " + locationOnChr.getObject()); <ide> return null; <ide> } <ide>
JavaScript
mit
418bf83ffa8e546bd05692c3db1a98d397c586b1
0
danielsun174/sticky-load-balancer
/** * * @return {{}} * @type function * @constructor */ module.exports = (function StickyLoadBalancer() { var self = {}; var doLog = false; var log = function (w) { if (doLog) { console.dir(w); } }; //dependencies var farmhash = require('farmhash'); var http = require('http'); var request = require('request'); var querystring=require('querystring'); /** * constructor * @param {string} ip * @param {number} port * @constructor */ var ret = function (ip, port) { this.getIp = function () { return ip }; this.getPort = function () { return port }; this.identifier = '-' + Math.random() + Math.random() + Math.random() + Math.random() + Math.random() + Math.random(); /** * array which contains the current strategie * @type {String[]} * @private */ var _stickyStrategy = []; var _renderState = { cookie: false, body: false }; this.getRenderState = function () { return _renderState; }; /** * get the current sticky strategy * @return {String[]} */ this.getStickyStrategy = function () { return _stickyStrategy; }; /** * set a custom sticky-strategie * @param {string[]} stringArray everything to use to define the sticky-parameter */ this.setStickyStrategy = function (stringArray) { //1. check if strategie is ok if (stringArray.length <= 0) { log('sticky-load-balancer(): couldnt set sticky strategy (no or empty array given)'); return false; } var failed = false; stringArray.forEach(function (v) { if (typeof v !== "string") { log('sticky-load-balancer(): couldnt set sticky strategy (one array-el is not a string)'); failed = true; return false; } }); if (failed) { return false; } //2. reset performance-hints _renderState.body = false; _renderState.cookie = false; //3. check performance-hints stringArray.forEach(function (v) { var split = v.split('.'); if (split[0] == 'body') { _renderState.body = true; } if (split[0] == 'cookie') { _renderState.cookie = true; } }); _stickyStrategy = stringArray; }; /** * represent the running server * @type {null} * @private */ var _server = null; this.setServer = function (newServer) { _server = newServer; }; /** * @type {boolean} */ this.running = false; var nodes = [ /*{ //sample-node ip: '127.0.0.1', port: 3456, balance: 2, range: { from: 1234, to: 23542345 }, roundRobin: null }*/ ]; this.addOneNode = function (node) { nodes.push(node); }; this.getNodes = function () { return nodes; }; }; ret.prototype = (function () { /** * take all nodes and split the 32bit-range between them * @private */ var _reDistributeNodes = function (self) { //1. calculate balance.sum() var balanceSum = 0; self.getNodes().forEach(function (node) { balanceSum = balanceSum + node.balance; }); var rangePerBalance = Math.ceil(4294967296 / balanceSum); //2. spread to the nodes var startRange = 0; self.getNodes().forEach(function (node) { node.range.from = startRange; var addRange = node.balance * rangePerBalance; var endRange = startRange + addRange; node.range.to = endRange; startRange = endRange; }); //3. set round-robin-flag to the first node self.getNodes()[0].roundRobin = 0; }; /** * set the identifier * @param {string} ident */ var setIdentifier = function (ident) { this.identifier = ident; }; /** * add a node to the balancer * @param {string} ip * @param {number} port * @param {number} balance 1-10 only, if node X has balance=2 and node Y has balance=4, node Y would get double the load than node X */ var addNode = function (ip, port, balance) { var self = this; //1. check if balance ok if (balance < 1 || balance > 10) { log('sticky-load-balancer.addNode(' + ip + ':' + port + ',' + balance + '): balance must be between 1 and 10'); return false; } //2. check if node doesnt exist var exists = false; self.getNodes().forEach(function (node) { if (node.ip == ip && node.port == port) { exists = true; return false; } }); if (exists == true) { log('sticky-load-balancer.addNode(' + ip + ':' + port + ',' + balance + '): node already exists'); return false; } self.addOneNode({ ip: ip, port: port, balance: balance, range: { from: 0, to: 0 }, roundRobin: null }); _reDistributeNodes(self); }; /** * get the right node for a given hashObj from the StickyStrategy * @param self * @param {{}|String} hashObj * @return {*} the node * @private */ var _findDistributionNode = function (self, hashObj) { if (Object.keys(hashObj).length === 0 || hashObj === '') { //use round robin because hashObj is empty var robinNode = null; self.getNodes().forEach(function (node, i) { if (node.roundRobin != null) { robinNode = node; //set the round-robin-flag to next node.roundRobin++; if (node.roundRobin > node.balance) { node.roundRobin = null; var nextIndex = i + 1; if (nextIndex > self.getNodes().length - 1) { nextIndex = 0; } self.getNodes()[nextIndex].roundRobin = 0; } return false; } }); return robinNode; } else { //use sticky-mode var hashNr = _hash(hashObj); //find node with this range var returnNode = null; self.getNodes().forEach(function (node) { if (node.range.to >= hashNr && node.range.from <= hashNr) { returnNode = node; return false; } }); return returnNode; } }; /** * returns true if the given request can be piped * @param self * @param req * @return {boolean} * @private */ var _canPipe = function (self, req) { return !(req.method == "POST" && self.getRenderState().body == true); }; /** * get a hashObject from a non-piped request * @param self * @param req * @return {{}} * @private */ var _getHashObject = function (self, req) { var ret = {}; //parse cookies if needed if(self.getRenderState().cookie){ req.cookie=_parseCookies(req); } //parse body if needed if(self.getRenderState().body && req.bodyData){ req.body=_parseBody(req.bodyData); } self.getStickyStrategy().forEach(function (v) { var val = _objectAttributeByString(req, v); if (typeof val !== "undefined") { ret[v] = val; } }); //add unique identifier if(Object.keys(ret).length!=0){ ret[self.identifier + '______'] = '1'; } return ret; }; /** * start the shit! */ var start = function () { var self = this; if (self.getNodes().length === 0) { log('sticky-load-balancer.start(): called but no nodes are added at the moment'); } if (self.running == true) { log('sticky-load-balancer.start(): cannot start because already started'); return false; } log('load balancer started at http://' + self.getIp() + ':' + self.getPort() + '/'); var server = http.createServer(function (req, res) { /** * secret identifier called. add node */ if (req.method == "POST" && req.url == '/' + self.identifier) { var data = ''; req.on('data', function (chunk) { data += chunk; }); log('sticky-load-balancer(' + self.getIp() + ':' + self.getPort() + '): secret identifier called. Add node:'); req.on('end', function () { try { var nodeData = JSON.parse(data); log(nodeData); self.addNode(nodeData.ip, nodeData.port, nodeData.balance); } catch (e) { res.end('failed to parse body'); } }); } else { //0. exit if no node exists if (self.getNodes().length == 0) { log('sticky-load-balancer(' + self.getIp() + ':' + self.getPort() + ') incoming request but couldnt find node'); return false; } //1. check if request can be piped var hashObj = {}; var useNode=null; if (_canPipe(self, req)) { hashObj = _getHashObject(self, req); useNode = _findDistributionNode(self, hashObj); //console.dir(hashObj); //2. redirect the request var options = { host: useNode.ip, port: useNode.port, path: req.url, //This is what changes the request to a POST request method: req.method, headers: req.headers }; options.headers.originalHostname=req.headers.host; delete options.headers.host; /** * @link http://stackoverflow.com/questions/13472024/simple-node-js-proxy-by-piping-http-server-to-http-request */ var connection = http.request(options, function (serverResponse) { serverResponse.pause(); res.writeHeader(serverResponse.statusCode, serverResponse.headers); serverResponse.pipe(res); serverResponse.resume(); }); connection.on('error', function(e){ log('req error: '); log(e); _handleError(res); }); req.pipe(connection); req.resume(); } else { //1.2 w8 for all data var body=''; req.on('data', function(chunk){ body+=chunk; }); req.on('end', function(){ req.bodyData=body; hashObj = _getHashObject(self, req); useNode = _findDistributionNode(self, hashObj); //2. redirect the request var options = { host: useNode.ip, port: useNode.port, path: req.url, //This is what changes the request to a POST request method: req.method, headers: req.headers }; options.headers.originalHostname=req.headers.host; delete options.headers.host; /** * @link http://stackoverflow.com/questions/13472024/simple-node-js-proxy-by-piping-http-server-to-http-request */ var connection = http.request(options, function (serverResponse) { serverResponse.pause(); res.writeHeader(serverResponse.statusCode, serverResponse.headers); serverResponse.pipe(res); serverResponse.resume(); }); connection.on('error', function(e){ log('req error: '); log(e); _handleError(res); }); connection.end(body); }); req.on('error', function(e){ console.log('req error: '); console.dir(e); }); } } }).listen(self.getPort(), self.getIp()); self.setServer(server); self.running = true; }; return { setIdentifier: setIdentifier, addNode: addNode, start: start } })(); /** * get attribute of object by string * @param {{}} o * @param {string} s * @return {*} * @private */ var _objectAttributeByString = function (o, s) { s = s.replace(/^\./, ''); // strip a leading dot var a = s.split('.'); for (var i = 0, n = a.length; i < n; ++i) { var k = a[i]; if (k in o) { o = o[k]; } else { return; } } return o; }; /** * create an hash-number from given object * @param {*} stringORObject * @private * @returns {number} the hash as 32-bit-number ( 0 to 4,294,967,296 ) */ var _hash = function (stringORObject) { if (typeof stringORObject !== "string") { stringORObject = JSON.stringify(stringORObject); } return farmhash.hash32(stringORObject); }; var _parseCookies = function (req) { try { var list = {}, rc = req.headers.cookie; rc && rc.split(';').forEach(function (cookie) { var parts = cookie.split('='); list[parts.shift().trim()] = decodeURI(parts.join('=')); }); return list; } catch (e) { return {}; } }; var _parseBody = function (bodyData) { var ret = {}; var done = false; try { ret = JSON.parse(bodyData); done = true; } catch (e) { } try { if (done == false) { ret = querystring.parse(bodyData); } } catch (e) { } if (Object.keys(ret).length == 0) { ret = {}; } return ret; }; /** * handle requests from broken nodes * @param res * @private */ var _handleError=function(res){ res.end('StickyLoadBalancer: Error with node'); }; /** * tell another balancer that I want to be node of it * @param {{ip: string, port: number, identifier: string}} balancer * @param {{ip: string, port: number, balance: number}} node */ ret.tellBalancer = function (balancer, node) { var options = { method: 'post', body: node, json: true, url: 'http://' + balancer.ip + ':' + balancer.port + '/' + balancer.identifier }; request(options, function (err, res, body) { if (err) { log('sticky-load-balancer.tellBalancer(): cant add node, connection error: '); log(err); return false; } }) }; ret.setLogging = function (onOff) { doLog = onOff; }; return ret; })();
index.js
/** * * @return {{}} * @type function * @constructor */ module.exports = (function StickyLoadBalancer() { var self = this; var doLog = false; var log = function (w) { if (doLog) { console.dir(w); } }; //dependencies var farmhash = require('farmhash'); var http = require('http'); var request = require('request'); var querystring=require('querystring'); /** * constructor * @param {string} ip * @param {number} port * @constructor */ var ret = function (ip, port) { this.getIp = function () { return ip }; this.getPort = function () { return port }; this.identifier = '-' + Math.random() + Math.random() + Math.random() + Math.random() + Math.random() + Math.random(); /** * array which contains the current strategie * @type {String[]} * @private */ var _stickyStrategy = []; var _renderState = { cookie: false, body: false }; this.getRenderState = function () { return _renderState; }; /** * get the current sticky strategy * @return {String[]} */ this.getStickyStrategy = function () { return _stickyStrategy; }; /** * set a custom sticky-strategie * @param {string[]} stringArray everything to use to define the sticky-parameter */ this.setStickyStrategy = function (stringArray) { //1. check if strategie is ok if (stringArray.length <= 0) { log('sticky-load-balancer(): couldnt set sticky strategy (no or empty array given)'); return false; } var failed = false; stringArray.forEach(function (v) { if (typeof v !== "string") { log('sticky-load-balancer(): couldnt set sticky strategy (one array-el is not a string)'); failed = true; return false; } }); if (failed) { return false; } //2. reset performance-hints _renderState.body = false; _renderState.cookie = false; //3. check performance-hints stringArray.forEach(function (v) { var split = v.split('.'); if (split[0] == 'body') { _renderState.body = true; } if (split[0] == 'cookie') { _renderState.cookie = true; } }); _stickyStrategy = stringArray; }; /** * represent the running server * @type {null} * @private */ var _server = null; this.setServer = function (newServer) { _server = newServer; }; /** * @type {boolean} */ this.running = false; var nodes = [ /*{ //sample-node ip: '127.0.0.1', port: 3456, balance: 2, range: { from: 1234, to: 23542345 }, roundRobin: null }*/ ]; this.addOneNode = function (node) { nodes.push(node); }; this.getNodes = function () { return nodes; }; }; ret.prototype = (function () { /** * take all nodes and split the 32bit-range between them * @private */ var _reDistributeNodes = function (self) { //1. calculate balance.sum() var balanceSum = 0; self.getNodes().forEach(function (node) { balanceSum = balanceSum + node.balance; }); var rangePerBalance = Math.ceil(4294967296 / balanceSum); //2. spread to the nodes var startRange = 0; self.getNodes().forEach(function (node) { node.range.from = startRange; var addRange = node.balance * rangePerBalance; var endRange = startRange + addRange; node.range.to = endRange; startRange = endRange; }); //3. set round-robin-flag to the first node self.getNodes()[0].roundRobin = 0; }; /** * set the identifier * @param {string} ident */ var setIdentifier = function (ident) { this.identifier = ident; }; /** * add a node to the balancer * @param {string} ip * @param {number} port * @param {number} balance 1-10 only, if node X has balance=2 and node Y has balance=4, node Y would get double the load than node X */ var addNode = function (ip, port, balance) { var self = this; //1. check if balance ok if (balance < 1 || balance > 10) { log('sticky-load-balancer.addNode(' + ip + ':' + port + ',' + balance + '): balance must be between 1 and 10'); return false; } //2. check if node doesnt exist var exists = false; self.getNodes().forEach(function (node) { if (node.ip == ip && node.port == port) { exists = true; return false; } }); if (exists == true) { log('sticky-load-balancer.addNode(' + ip + ':' + port + ',' + balance + '): node already exists'); return false; } self.addOneNode({ ip: ip, port: port, balance: balance, range: { from: 0, to: 0 }, roundRobin: null }); _reDistributeNodes(self); }; /** * get the right node for a given hashObj from the StickyStrategy * @param self * @param {{}|String} hashObj * @return {*} the node * @private */ var _findDistributionNode = function (self, hashObj) { if (Object.keys(hashObj).length === 0 || hashObj === '') { //use round robin because hashObj is empty var robinNode = null; self.getNodes().forEach(function (node, i) { if (node.roundRobin != null) { robinNode = node; //set the round-robin-flag to next node.roundRobin++; if (node.roundRobin > node.balance) { node.roundRobin = null; var nextIndex = i + 1; if (nextIndex > self.getNodes().length - 1) { nextIndex = 0; } self.getNodes()[nextIndex].roundRobin = 0; } return false; } }); return robinNode; } else { //use sticky-mode var hashNr = _hash(hashObj); //find node with this range var returnNode = null; self.getNodes().forEach(function (node) { if (node.range.to >= hashNr && node.range.from <= hashNr) { returnNode = node; return false; } }); return returnNode; } }; /** * returns true if the given request can be piped * @param self * @param req * @return {boolean} * @private */ var _canPipe = function (self, req) { return !(req.method == "POST" && self.getRenderState().body == true); }; /** * get a hashObject from a non-piped request * @param self * @param req * @return {{}} * @private */ var _getHashObject = function (self, req) { var ret = {}; //parse cookies if needed if(self.getRenderState().cookie){ req.cookie=_parseCookies(req); } //parse body if needed if(self.getRenderState().body && req.bodyData){ req.body=_parseBody(req.bodyData); } self.getStickyStrategy().forEach(function (v) { var val = _objectAttributeByString(req, v); if (typeof val !== "undefined") { ret[v] = val; } }); //add unique identifier if(Object.keys(ret).length!=0){ ret[self.identifier + '______'] = '1'; } return ret; }; /** * start the shit! */ var start = function () { var self = this; if (self.getNodes().length === 0) { log('sticky-load-balancer.start(): called but no nodes are added at the moment'); } if (self.running == true) { log('sticky-load-balancer.start(): cannot start because already started'); return false; } log('load balancer started at http://' + self.getIp() + ':' + self.getPort() + '/'); var server = http.createServer(function (req, res) { /** * secret identifier called. add node */ if (req.method == "POST" && req.url == '/' + self.identifier) { var data = ''; req.on('data', function (chunk) { data += chunk; }); log('sticky-load-balancer(' + self.getIp() + ':' + self.getPort() + '): secret identifier called. Add node:'); req.on('end', function () { try { var nodeData = JSON.parse(data); log(nodeData); self.addNode(nodeData.ip, nodeData.port, nodeData.balance); } catch (e) { res.end('failed to parse body'); } }); } else { //0. exit if no node exists if (self.getNodes().length == 0) { log('sticky-load-balancer(' + self.getIp() + ':' + self.getPort() + ') incoming request but couldnt find node'); return false; } //1. check if request can be piped var hashObj = {}; var useNode=null; if (_canPipe(self, req)) { hashObj = _getHashObject(self, req); useNode = _findDistributionNode(self, hashObj); //console.dir(hashObj); //2. redirect the request var options = { host: useNode.ip, port: useNode.port, path: req.url, //This is what changes the request to a POST request method: req.method, headers: req.headers }; options.headers.originalHostname=req.headers.host; delete options.headers.host; /** * @link http://stackoverflow.com/questions/13472024/simple-node-js-proxy-by-piping-http-server-to-http-request */ var connection = http.request(options, function (serverResponse) { serverResponse.pause(); res.writeHeader(serverResponse.statusCode, serverResponse.headers); serverResponse.pipe(res); serverResponse.resume(); }); connection.on('error', function(e){ log('req error: '); log(e); _handleError(res); }); req.pipe(connection); req.resume(); } else { //1.2 w8 for all data var body=''; req.on('data', function(chunk){ body+=chunk; }); req.on('end', function(){ req.bodyData=body; hashObj = _getHashObject(self, req); useNode = _findDistributionNode(self, hashObj); //2. redirect the request var options = { host: useNode.ip, port: useNode.port, path: req.url, //This is what changes the request to a POST request method: req.method, headers: req.headers }; options.headers.originalHostname=req.headers.host; delete options.headers.host; /** * @link http://stackoverflow.com/questions/13472024/simple-node-js-proxy-by-piping-http-server-to-http-request */ var connection = http.request(options, function (serverResponse) { serverResponse.pause(); res.writeHeader(serverResponse.statusCode, serverResponse.headers); serverResponse.pipe(res); serverResponse.resume(); }); connection.on('error', function(e){ log('req error: '); log(e); _handleError(res); }); connection.end(body); }); req.on('error', function(e){ console.log('req error: '); console.dir(e); }); } } }).listen(self.getPort(), self.getIp()); self.setServer(server); self.running = true; }; return { setIdentifier: setIdentifier, addNode: addNode, start: start } })(); /** * get attribute of object by string * @param {{}} o * @param {string} s * @return {*} * @private */ var _objectAttributeByString = function (o, s) { s = s.replace(/^\./, ''); // strip a leading dot var a = s.split('.'); for (var i = 0, n = a.length; i < n; ++i) { var k = a[i]; if (k in o) { o = o[k]; } else { return; } } return o; }; /** * create an hash-number from given object * @param {*} stringORObject * @private * @returns {number} the hash as 32-bit-number ( 0 to 4,294,967,296 ) */ var _hash = function (stringORObject) { if (typeof stringORObject !== "string") { stringORObject = JSON.stringify(stringORObject); } return farmhash.hash32(stringORObject); }; var _parseCookies = function (req) { try { var list = {}, rc = req.headers.cookie; rc && rc.split(';').forEach(function (cookie) { var parts = cookie.split('='); list[parts.shift().trim()] = decodeURI(parts.join('=')); }); return list; } catch (e) { return {}; } }; var _parseBody = function (bodyData) { var ret = {}; var done = false; try { ret = JSON.parse(bodyData); done = true; } catch (e) { } try { if (done == false) { ret = querystring.parse(bodyData); } } catch (e) { } if (Object.keys(ret).length == 0) { ret = {}; } return ret; }; /** * handle requests from broken nodes * @param res * @private */ var _handleError=function(res){ res.end('StickyLoadBalancer: Error with node'); }; /** * tell another balancer that I want to be node of it * @param {{ip: string, port: number, identifier: string}} balancer * @param {{ip: string, port: number, balance: number}} node */ ret.tellBalancer = function (balancer, node) { var options = { method: 'post', body: node, json: true, url: 'http://' + balancer.ip + ':' + balancer.port + '/' + balancer.identifier }; request(options, function (err, res, body) { if (err) { log('sticky-load-balancer.tellBalancer(): cant add node, connection error: '); log(err); return false; } }) }; ret.setLogging = function (onOff) { doLog = onOff; }; return ret; })();
replace this to not conflict
index.js
replace this to not conflict
<ide><path>ndex.js <ide> * @constructor <ide> */ <ide> module.exports = (function StickyLoadBalancer() { <del> var self = this; <add> var self = {}; <ide> <ide> var doLog = false; <ide> var log = function (w) {
Java
apache-2.0
9a209fdeb2b588ec1508875be87987748bfae7bb
0
krokers/exchange-rates-mvvm
domain/src/main/java/eu/rampsoftware/er/domain/pojo/CurrencyHome.java
//package eu.rampsoftware.er.domain.pojo; // //import eu.rampsoftware.er.data.CurrencyData; // //public class CurrencyHome { // public CurrencyHome(final CurrencyData currencyData) { // // } //}
Removed unused class.
domain/src/main/java/eu/rampsoftware/er/domain/pojo/CurrencyHome.java
Removed unused class.
<ide><path>omain/src/main/java/eu/rampsoftware/er/domain/pojo/CurrencyHome.java <del>//package eu.rampsoftware.er.domain.pojo; <del>// <del>//import eu.rampsoftware.er.data.CurrencyData; <del>// <del>//public class CurrencyHome { <del>// public CurrencyHome(final CurrencyData currencyData) { <del>// <del>// } <del>//}
Java
apache-2.0
5e2414abbafb7e041af0e36f6f3b813482d3a514
0
Camila96/Libreria
package modelo.entidades; public enum TipoBusqueda { SELECIONE("Selecione una Opcin"),AUTOR("Nombre Autor"), LIBRO("Nombre Libro"), IDAUTOR("ID Autor"), IDLIBRO("ID Libro"), CLIENTE("Nombre Cliente"), IDCLIENTE("ID Cliente"); private String name; TipoBusqueda(String name){ this.name = name; } public String getName(){ return name; } @Override public String toString() { return ""+getName()+""; } }
Libreria/src/modelo/entidades/TipoBusqueda.java
package modelo.entidades; public enum TipoBusqueda { AUTOR("Nombre Autor"), LIBRO("Nombre Libro"), IDAUTOR("ID Autor"), IDLIBRO("ID Libro"); private String name; TipoBusqueda(String name){ this.name = name; } public String getName(){ return name; } @Override public String toString() { return ""+getName()+""; } }
Actualización Combo Box
Libreria/src/modelo/entidades/TipoBusqueda.java
Actualización Combo Box
<ide><path>ibreria/src/modelo/entidades/TipoBusqueda.java <ide> <ide> public enum TipoBusqueda { <ide> <del> AUTOR("Nombre Autor"), LIBRO("Nombre Libro"), IDAUTOR("ID Autor"), IDLIBRO("ID Libro"); <add> SELECIONE("Selecione una Opcin"),AUTOR("Nombre Autor"), LIBRO("Nombre Libro"), <add> IDAUTOR("ID Autor"), IDLIBRO("ID Libro"), CLIENTE("Nombre Cliente"), IDCLIENTE("ID Cliente"); <ide> <ide> private String name; <ide>
Java
apache-2.0
09f62ff23798c0d7d1640f11897fa3422d39638b
0
robinverduijn/gradle,gstevey/gradle,blindpirate/gradle,blindpirate/gradle,robinverduijn/gradle,robinverduijn/gradle,gstevey/gradle,lsmaira/gradle,robinverduijn/gradle,gstevey/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,gstevey/gradle,gradle/gradle,robinverduijn/gradle,lsmaira/gradle,blindpirate/gradle,robinverduijn/gradle,gstevey/gradle,blindpirate/gradle,lsmaira/gradle,gradle/gradle,gradle/gradle,robinverduijn/gradle,lsmaira/gradle,blindpirate/gradle,blindpirate/gradle,robinverduijn/gradle,gradle/gradle,blindpirate/gradle,gstevey/gradle,lsmaira/gradle,gradle/gradle,blindpirate/gradle,lsmaira/gradle,gradle/gradle,gstevey/gradle,lsmaira/gradle,robinverduijn/gradle,gradle/gradle,lsmaira/gradle,gstevey/gradle,gstevey/gradle,gradle/gradle,lsmaira/gradle,robinverduijn/gradle,lsmaira/gradle,robinverduijn/gradle,gradle/gradle
package org.gradle.util.exec; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import org.apache.tools.ant.util.JavaEnvUtils; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; /** * @author Tom Eyckmans */ public class DefaultExecHandleTest { private DefaultExecHandle execHandle; @Test public void testJavadocVersion() throws IOException { StreamWriterExecOutputHandle outHandle = new StreamWriterExecOutputHandle(System.out, true); StreamWriterExecOutputHandle errHandle = new StreamWriterExecOutputHandle(System.err, true); System.out.println("Javadoc executable = " + JavaEnvUtils.getJdkExecutable("javadoc")); execHandle = new DefaultExecHandle( new File("./src/main/groovy"), JavaEnvUtils.getJdkExecutable("javadoc"), Arrays.asList("-verbose", "-d", new File("tmp/javadocTmpOut").getAbsolutePath(), "org.gradle"), 0, System.getenv(), 100, outHandle, errHandle, new DefaultExecHandleNotifierFactory(), null ); final ExecHandleState endState = execHandle.startAndWaitForFinish(); if ( endState == ExecHandleState.FAILED ) { execHandle.getFailureCause().printStackTrace(); } assertEquals(ExecHandleState.SUCCEEDED, endState); } @Test public void testAbort() throws IOException { StreamWriterExecOutputHandle outHandle = new StreamWriterExecOutputHandle(System.out, true); StreamWriterExecOutputHandle errHandle = new StreamWriterExecOutputHandle(System.err, true); System.out.println("Javadoc executable = " + JavaEnvUtils.getJdkExecutable("javadoc")); execHandle = new DefaultExecHandle( new File("./src/main/groovy"), JavaEnvUtils.getJdkExecutable("javadoc"), Arrays.asList("-verbose", "-d", new File("tmp/javadocTmpOut").getAbsolutePath(), "org.gradle"), 0, System.getenv(), 100, outHandle, errHandle, new DefaultExecHandleNotifierFactory(), null ); execHandle.start(); execHandle.abort(); final ExecHandleState endState = execHandle.waitForFinish(); if ( endState == ExecHandleState.FAILED ) { execHandle.getFailureCause().printStackTrace(); } assertEquals(ExecHandleState.ABORTED, endState); } }
src/test/groovy/org/gradle/util/exec/DefaultExecHandleTest.java
package org.gradle.util.exec; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import org.apache.tools.ant.util.JavaEnvUtils; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; /** * @author Tom Eyckmans */ public class DefaultExecHandleTest { private DefaultExecHandle execHandle; @Test public void testJavadocVersion() throws IOException { StreamWriterExecOutputHandle outHandle = new StreamWriterExecOutputHandle(System.out, true); StreamWriterExecOutputHandle errHandle = new StreamWriterExecOutputHandle(System.err, true); System.out.println("Javadoc executable = " + JavaEnvUtils.getJdkExecutable("javadoc")); execHandle = new DefaultExecHandle( new File("./src/main/groovy"), JavaEnvUtils.getJdkExecutable("javadoc"), Arrays.asList("-verbose", "-d", "/tmp/javadocTmpOut", "org.gradle"), 0, System.getenv(), 100, outHandle, errHandle, new DefaultExecHandleNotifierFactory(), null ); final ExecHandleState endState = execHandle.startAndWaitForFinish(); if ( endState == ExecHandleState.FAILED ) { execHandle.getFailureCause().printStackTrace(); } assertEquals(ExecHandleState.SUCCEEDED, endState); } @Test public void testAbort() throws IOException { StreamWriterExecOutputHandle outHandle = new StreamWriterExecOutputHandle(System.out, true); StreamWriterExecOutputHandle errHandle = new StreamWriterExecOutputHandle(System.err, true); System.out.println("Javadoc executable = " + JavaEnvUtils.getJdkExecutable("javadoc")); execHandle = new DefaultExecHandle( new File("./src/main/groovy"), JavaEnvUtils.getJdkExecutable("javadoc"), Arrays.asList("-verbose", "-d", "/tmp/javadocTmpOut", "org.gradle"), 0, System.getenv(), 100, outHandle, errHandle, new DefaultExecHandleNotifierFactory(), null ); execHandle.start(); execHandle.abort(); final ExecHandleState endState = execHandle.waitForFinish(); if ( endState == ExecHandleState.FAILED ) { execHandle.getFailureCause().printStackTrace(); } assertEquals(ExecHandleState.ABORTED, endState); } }
made tmp output directory of DefaultExecHandleTest environment unspecific git-svn-id: 3c1f16eda3ef44bc7d9581ddf719321a2000da74@1270 004c2c75-fc45-0410-b1a2-da8352e2331b
src/test/groovy/org/gradle/util/exec/DefaultExecHandleTest.java
made tmp output directory of DefaultExecHandleTest environment unspecific
<ide><path>rc/test/groovy/org/gradle/util/exec/DefaultExecHandleTest.java <ide> execHandle = new DefaultExecHandle( <ide> new File("./src/main/groovy"), <ide> JavaEnvUtils.getJdkExecutable("javadoc"), <del> Arrays.asList("-verbose", "-d", "/tmp/javadocTmpOut", "org.gradle"), 0, <add> Arrays.asList("-verbose", "-d", new File("tmp/javadocTmpOut").getAbsolutePath(), "org.gradle"), 0, <ide> System.getenv(), <ide> 100, <ide> outHandle, <ide> execHandle = new DefaultExecHandle( <ide> new File("./src/main/groovy"), <ide> JavaEnvUtils.getJdkExecutable("javadoc"), <del> Arrays.asList("-verbose", "-d", "/tmp/javadocTmpOut", "org.gradle"), 0, <add> Arrays.asList("-verbose", "-d", new File("tmp/javadocTmpOut").getAbsolutePath(), "org.gradle"), 0, <ide> System.getenv(), <ide> 100, <ide> outHandle,
Java
apache-2.0
069c88fb6e2569c8ca03c8a3d567d167384df558
0
xfournet/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,signed/intellij-community,semonte/intellij-community,signed/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,da1z/intellij-community,ibinti/intellij-community,signed/intellij-community,allotria/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,signed/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,da1z/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,da1z/intellij-community,youdonghai/intellij-community,semonte/intellij-community,semonte/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,xfournet/intellij-community,signed/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,da1z/intellij-community,xfournet/intellij-community,allotria/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,signed/intellij-community,da1z/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,signed/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,allotria/intellij-community,FHannes/intellij-community,FHannes/intellij-community,xfournet/intellij-community,da1z/intellij-community,apixandru/intellij-community,FHannes/intellij-community,asedunov/intellij-community,signed/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,semonte/intellij-community,vvv1559/intellij-community,semonte/intellij-community,ibinti/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,semonte/intellij-community,FHannes/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,apixandru/intellij-community,semonte/intellij-community,ibinti/intellij-community,da1z/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,signed/intellij-community,youdonghai/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,allotria/intellij-community,da1z/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,xfournet/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,ibinti/intellij-community,apixandru/intellij-community,allotria/intellij-community,FHannes/intellij-community,signed/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,semonte/intellij-community,da1z/intellij-community,suncycheng/intellij-community,semonte/intellij-community,apixandru/intellij-community,ibinti/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,apixandru/intellij-community,signed/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,FHannes/intellij-community,allotria/intellij-community,semonte/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,da1z/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,allotria/intellij-community,asedunov/intellij-community,ibinti/intellij-community,semonte/intellij-community,signed/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.refactoring.migration; import com.intellij.history.LocalHistory; import com.intellij.history.LocalHistoryAction; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Ref; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiMigration; import com.intellij.psi.impl.migration.PsiMigrationManager; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.refactoring.BaseRefactoringProcessor; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.RefactoringHelper; import com.intellij.usageView.UsageInfo; import com.intellij.usageView.UsageViewDescriptor; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; /** * @author ven */ public class MigrationProcessor extends BaseRefactoringProcessor { private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.migration.MigrationProcessor"); private final MigrationMap myMigrationMap; private static final String REFACTORING_NAME = RefactoringBundle.message("migration.title"); private PsiMigration myPsiMigration; private final GlobalSearchScope mySearchScope; public MigrationProcessor(Project project, MigrationMap migrationMap) { this(project, migrationMap, GlobalSearchScope.projectScope(project)); } public MigrationProcessor(Project project, MigrationMap migrationMap, GlobalSearchScope scope) { super(project); myMigrationMap = migrationMap; mySearchScope = scope; myPsiMigration = startMigration(project); } @NotNull protected UsageViewDescriptor createUsageViewDescriptor(@NotNull UsageInfo[] usages) { return new MigrationUsagesViewDescriptor(myMigrationMap, false); } private PsiMigration startMigration(Project project) { final PsiMigration migration = PsiMigrationManager.getInstance(project).startMigration(); findOrCreateEntries(project, migration); return migration; } private void findOrCreateEntries(Project project, final PsiMigration migration) { for (int i = 0; i < myMigrationMap.getEntryCount(); i++) { MigrationMapEntry entry = myMigrationMap.getEntryAt(i); if (entry.getType() == MigrationMapEntry.PACKAGE) { MigrationUtil.findOrCreatePackage(project, migration, entry.getOldName()); } else { MigrationUtil.findOrCreateClass(project, migration, entry.getOldName()); } } } @Override protected void refreshElements(@NotNull PsiElement[] elements) { myPsiMigration = startMigration(myProject); } @NotNull protected UsageInfo[] findUsages() { ArrayList<UsageInfo> usagesVector = new ArrayList<>(); try { if (myMigrationMap == null) { return UsageInfo.EMPTY_ARRAY; } for (int i = 0; i < myMigrationMap.getEntryCount(); i++) { MigrationMapEntry entry = myMigrationMap.getEntryAt(i); UsageInfo[] usages; if (entry.getType() == MigrationMapEntry.PACKAGE) { usages = MigrationUtil.findPackageUsages(myProject, myPsiMigration, entry.getOldName(), mySearchScope); } else { usages = MigrationUtil.findClassUsages(myProject, myPsiMigration, entry.getOldName(), mySearchScope); } for (UsageInfo usage : usages) { usagesVector.add(new MigrationUsageInfo(usage, entry)); } } } finally { Application application = ApplicationManager.getApplication(); if (application.isUnitTestMode()) { finishFindMigration(); } else { //invalidating resolve caches without write action could lead to situations when somebody with read action resolves reference and gets ResolveResult //then here, in another read actions, all caches are invalidated but those resolve result is used without additional checks inside that read action - but it's already invalid application.invokeLater(() -> WriteAction.run(() -> finishFindMigration()), ModalityState.NON_MODAL); } } return usagesVector.toArray(UsageInfo.EMPTY_ARRAY); } private void finishFindMigration() { myPsiMigration.finish(); myPsiMigration = null; } protected boolean preprocessUsages(@NotNull Ref<UsageInfo[]> refUsages) { if (refUsages.get().length == 0) { Messages.showInfoMessage(myProject, RefactoringBundle.message("migration.no.usages.found.in.the.project"), REFACTORING_NAME); return false; } setPreviewUsages(true); return true; } protected void performRefactoring(@NotNull UsageInfo[] usages) { final PsiMigration psiMigration = PsiMigrationManager.getInstance(myProject).startMigration(); LocalHistoryAction a = LocalHistory.getInstance().startAction(getCommandName()); try { for (int i = 0; i < myMigrationMap.getEntryCount(); i++) { MigrationMapEntry entry = myMigrationMap.getEntryAt(i); if (entry.getType() == MigrationMapEntry.PACKAGE) { MigrationUtil.doPackageMigration(myProject, psiMigration, entry.getNewName(), usages); } if (entry.getType() == MigrationMapEntry.CLASS) { MigrationUtil.doClassMigration(myProject, psiMigration, entry.getNewName(), usages); } } for(RefactoringHelper helper: Extensions.getExtensions(RefactoringHelper.EP_NAME)) { Object preparedData = helper.prepareOperation(usages); //noinspection unchecked helper.performOperation(myProject, preparedData); } } finally { a.finish(); psiMigration.finish(); } } protected String getCommandName() { return REFACTORING_NAME; } static class MigrationUsageInfo extends UsageInfo { MigrationMapEntry mapEntry; MigrationUsageInfo(UsageInfo info, MigrationMapEntry mapEntry) { super(info.getElement(), info.getRangeInElement().getStartOffset(), info.getRangeInElement().getEndOffset()); this.mapEntry = mapEntry; } } }
java/java-impl/src/com/intellij/refactoring/migration/MigrationProcessor.java
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.refactoring.migration; import com.intellij.history.LocalHistory; import com.intellij.history.LocalHistoryAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Ref; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiMigration; import com.intellij.psi.impl.migration.PsiMigrationManager; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.refactoring.BaseRefactoringProcessor; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.RefactoringHelper; import com.intellij.usageView.UsageInfo; import com.intellij.usageView.UsageViewDescriptor; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; /** * @author ven */ public class MigrationProcessor extends BaseRefactoringProcessor { private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.migration.MigrationProcessor"); private final MigrationMap myMigrationMap; private static final String REFACTORING_NAME = RefactoringBundle.message("migration.title"); private PsiMigration myPsiMigration; private final GlobalSearchScope mySearchScope; public MigrationProcessor(Project project, MigrationMap migrationMap) { this(project, migrationMap, GlobalSearchScope.projectScope(project)); } public MigrationProcessor(Project project, MigrationMap migrationMap, GlobalSearchScope scope) { super(project); myMigrationMap = migrationMap; mySearchScope = scope; myPsiMigration = startMigration(project); } @NotNull protected UsageViewDescriptor createUsageViewDescriptor(@NotNull UsageInfo[] usages) { return new MigrationUsagesViewDescriptor(myMigrationMap, false); } private PsiMigration startMigration(Project project) { final PsiMigration migration = PsiMigrationManager.getInstance(project).startMigration(); findOrCreateEntries(project, migration); return migration; } private void findOrCreateEntries(Project project, final PsiMigration migration) { for (int i = 0; i < myMigrationMap.getEntryCount(); i++) { MigrationMapEntry entry = myMigrationMap.getEntryAt(i); if (entry.getType() == MigrationMapEntry.PACKAGE) { MigrationUtil.findOrCreatePackage(project, migration, entry.getOldName()); } else { MigrationUtil.findOrCreateClass(project, migration, entry.getOldName()); } } } @Override protected void refreshElements(@NotNull PsiElement[] elements) { myPsiMigration = startMigration(myProject); } @NotNull protected UsageInfo[] findUsages() { ArrayList<UsageInfo> usagesVector = new ArrayList<>(); try { if (myMigrationMap == null) { return UsageInfo.EMPTY_ARRAY; } for (int i = 0; i < myMigrationMap.getEntryCount(); i++) { MigrationMapEntry entry = myMigrationMap.getEntryAt(i); UsageInfo[] usages; if (entry.getType() == MigrationMapEntry.PACKAGE) { usages = MigrationUtil.findPackageUsages(myProject, myPsiMigration, entry.getOldName(), mySearchScope); } else { usages = MigrationUtil.findClassUsages(myProject, myPsiMigration, entry.getOldName(), mySearchScope); } for (UsageInfo usage : usages) { usagesVector.add(new MigrationUsageInfo(usage, entry)); } } } finally { myPsiMigration.finish(); myPsiMigration = null; } return usagesVector.toArray(UsageInfo.EMPTY_ARRAY); } protected boolean preprocessUsages(@NotNull Ref<UsageInfo[]> refUsages) { if (refUsages.get().length == 0) { Messages.showInfoMessage(myProject, RefactoringBundle.message("migration.no.usages.found.in.the.project"), REFACTORING_NAME); return false; } setPreviewUsages(true); return true; } protected void performRefactoring(@NotNull UsageInfo[] usages) { final PsiMigration psiMigration = PsiMigrationManager.getInstance(myProject).startMigration(); LocalHistoryAction a = LocalHistory.getInstance().startAction(getCommandName()); try { for (int i = 0; i < myMigrationMap.getEntryCount(); i++) { MigrationMapEntry entry = myMigrationMap.getEntryAt(i); if (entry.getType() == MigrationMapEntry.PACKAGE) { MigrationUtil.doPackageMigration(myProject, psiMigration, entry.getNewName(), usages); } if (entry.getType() == MigrationMapEntry.CLASS) { MigrationUtil.doClassMigration(myProject, psiMigration, entry.getNewName(), usages); } } for(RefactoringHelper helper: Extensions.getExtensions(RefactoringHelper.EP_NAME)) { Object preparedData = helper.prepareOperation(usages); //noinspection unchecked helper.performOperation(myProject, preparedData); } } finally { a.finish(); psiMigration.finish(); } } protected String getCommandName() { return REFACTORING_NAME; } static class MigrationUsageInfo extends UsageInfo { MigrationMapEntry mapEntry; MigrationUsageInfo(UsageInfo info, MigrationMapEntry mapEntry) { super(info.getElement(), info.getRangeInElement().getStartOffset(), info.getRangeInElement().getEndOffset()); this.mapEntry = mapEntry; } } }
ensure resolve caches are invalidated inside write action (IDEA-163299)
java/java-impl/src/com/intellij/refactoring/migration/MigrationProcessor.java
ensure resolve caches are invalidated inside write action (IDEA-163299)
<ide><path>ava/java-impl/src/com/intellij/refactoring/migration/MigrationProcessor.java <ide> <ide> import com.intellij.history.LocalHistory; <ide> import com.intellij.history.LocalHistoryAction; <add>import com.intellij.openapi.application.Application; <add>import com.intellij.openapi.application.ApplicationManager; <add>import com.intellij.openapi.application.ModalityState; <add>import com.intellij.openapi.application.WriteAction; <ide> import com.intellij.openapi.diagnostic.Logger; <ide> import com.intellij.openapi.extensions.Extensions; <ide> import com.intellij.openapi.project.Project; <ide> } <ide> } <ide> finally { <del> myPsiMigration.finish(); <del> myPsiMigration = null; <add> Application application = ApplicationManager.getApplication(); <add> if (application.isUnitTestMode()) { <add> finishFindMigration(); <add> } <add> else { <add> //invalidating resolve caches without write action could lead to situations when somebody with read action resolves reference and gets ResolveResult <add> //then here, in another read actions, all caches are invalidated but those resolve result is used without additional checks inside that read action - but it's already invalid <add> application.invokeLater(() -> WriteAction.run(() -> finishFindMigration()), ModalityState.NON_MODAL); <add> } <ide> } <ide> return usagesVector.toArray(UsageInfo.EMPTY_ARRAY); <add> } <add> <add> private void finishFindMigration() { <add> myPsiMigration.finish(); <add> myPsiMigration = null; <ide> } <ide> <ide> protected boolean preprocessUsages(@NotNull Ref<UsageInfo[]> refUsages) {
Java
mit
e3f4a088feb4b7c724d3a5644c0331e1f0285ada
0
wildducktheories/api
package com.wildducktheories.api.impl; import java.util.concurrent.Callable; import com.wildducktheories.api.API; import com.wildducktheories.api.APIManager; /** * An abstract implementation of the {@link APIManager} interface. * <p> * Concrete sub types should implement the newAPI() method. * <p> * @author jonseymour * @param <A> The API type. */ public abstract class AbstractAPIManagerImpl<A extends API> implements APIManager<A> { /** * An per thread override for the thread's current scheduler. */ private final ThreadLocal<A> perThread = new ThreadLocal<A>(); /** * Constructs a default instance of the API type. * @return A new instance of the API type. */ public abstract A create(); @Override public A get() { A api = perThread.get(); if (api == null) { api = create(); perThread.set(api); } return api; } /** * Run the specified {@link Runnable} with the specified {@link API} as the * current {@link API} for the current thread. * @param api The specified {@link API}I * @param run The specified {@link Runnable} */ public void with(final A api, final Runnable runnable) { final A saved = perThread.get(); try { perThread.set(api); runnable.run(); } finally { if (saved == null) { perThread.remove(); } else { perThread.set(saved); } } } /** * Run the specified {@link Callable} with the specified {@link API} as the * current {@link API} for the current thread. * @param api The specified {@link API}I * @param run The specified {@link Runnable} * @return The result of the {@link Callable} * @throws Exception The exception thrown by the specified {@link Callable}, if any. */ public <P> P with(final A api, final Callable<P> callable) throws Exception { final A saved = perThread.get(); try { perThread.set(api); return callable.call(); } finally { if (saved == null) { perThread.remove(); } else { perThread.set(saved); } } } /** * Release all thread local resources. */ public void reset() { get().reset(); perThread.remove(); } }
src/main/java/com/wildducktheories/api/impl/AbstractAPIManagerImpl.java
package com.wildducktheories.api.impl; import java.util.concurrent.Callable; import com.wildducktheories.api.API; import com.wildducktheories.api.APIManager; /** * An abstract implementation of the {@link APIManager} interface. * <p> * Concrete sub types should implement the newAPI() method. * <p> * @author jonseymour * @param <A> The API type. */ public abstract class AbstractAPIManagerImpl<A extends API> implements APIManager<A> { /** * An per thread override for the thread's current scheduler. */ private final ThreadLocal<A> perThread = new ThreadLocal<A>(); /** * Constructs a default instance of the API type. * @return A new instance of the API type. */ public abstract A create(); @Override public A get() { A api = perThread.get(); if (api == null) { api = create(); } return api; } /** * Run the specified {@link Runnable} with the specified {@link API} as the * current {@link API} for the current thread. * @param api The specified {@link API}I * @param run The specified {@link Runnable} */ public void with(final A api, final Runnable runnable) { final A saved = perThread.get(); try { perThread.set(api); runnable.run(); } finally { if (saved == null) { perThread.remove(); } else { perThread.set(saved); } } } /** * Run the specified {@link Callable} with the specified {@link API} as the * current {@link API} for the current thread. * @param api The specified {@link API}I * @param run The specified {@link Runnable} * @return The result of the {@link Callable} * @throws Exception The exception thrown by the specified {@link Callable}, if any. */ public <P> P with(final A api, final Callable<P> callable) throws Exception { final A saved = perThread.get(); try { perThread.set(api); return callable.call(); } finally { if (saved == null) { perThread.remove(); } else { perThread.set(saved); } } } /** * Release all thread local resources. */ public void reset() { get().reset(); perThread.remove(); } }
fix: set the ThreadLocal value that we create. Signed-off-by: Jon Seymour <[email protected]>
src/main/java/com/wildducktheories/api/impl/AbstractAPIManagerImpl.java
fix: set the ThreadLocal value that we create.
<ide><path>rc/main/java/com/wildducktheories/api/impl/AbstractAPIManagerImpl.java <ide> A api = perThread.get(); <ide> if (api == null) { <ide> api = create(); <add> perThread.set(api); <ide> } <ide> return api; <ide> }
JavaScript
mit
c6f3af6223078d984ab200f991980979cc232f92
0
ReidWilliams/node-hue,ReidWilliams/node-hue
// turn lights on during eveningh hours // flicker lights const hue = require("node-hue-api") const moment = require("moment") const constants = require('./constants') const api = new hue.HueApi(constants.ip, constants.username) const _ = require('underscore') const lightState = hue.lightState const lightName = require('./lib/LightName') const debug = function(m) { console.log(`${moment().format('MMM DD hh:mm:ss')} ${m}`) } // light controls var lights = null // set by main from argv const on = lightState.create().on(true).hsb(40, 100, 20).transition(3000) const off = lightState.create().on(false) const randomOnState = function() { const _hue = Math.floor(Math.random()*100) const bri = Math.floor(Math.random()* 40) return lightState.create().on(true).hsb(_hue, 100, 0).transition(60000) } const turnLightsOn = function() { setLights(lights, randomOnState()) } const turnLightsOff = function() { setLights(lights, off) } const setLights = function(lights, lightState) { lights.forEach(function(light) { api.setLightState(light.id, lightState) }) } const onTime = function() { let h = moment().hour() return (h > 18 && h < 23) } const setLightState = function() { if (onTime()) { turnLightsOn() } else { turnLightsOff() } } const main = function() { if (process.argv.length < 3) { usage() process.exit(0) } debug(`starting`) lights = lightName.lightsFromNamesOrExit(process.argv.slice(2)) setLights(lights, off) setLightState() setInterval(setLightState, 60000) } const usage = function() { debug("usage: node " + __filename + " LIGHTNAME LIGHTNAME ...") debug("Each LIGHTNAME is the name of a light defined in constants.js:") var lightNames = _.pluck(constants.lights, 'name').join(", ") debug('"' + lightNames + '"') } main()
night-on.js
// turn lights on during eveningh hours const hue = require("node-hue-api") const moment = require("moment") const constants = require('./constants') const api = new hue.HueApi(constants.ip, constants.username) const _ = require('underscore') const lightState = hue.lightState const lightName = require('./lib/LightName') const debug = function(m) { console.log(`${moment().format('MMM DD hh:mm:ss')} ${m}`) } // light controls var lights = null // set by main from argv const on = lightState.create().on(true).hsb(40, 100, 20).transition(3000) const off = lightState.create().on(false) const turnLightsOn = function() { setLights(lights, on) } const turnLightsOff = function() { setLights(lights, off) } const setLights = function(lights, lightState) { lights.forEach(function(light) { api.setLightState(light.id, lightState) }) } const onTime = function() { let h = moment().hour() debug(h) return (h > 18 && h < 23) } const setLightState = function() { if (onTime()) { turnLightsOn() } else { turnLightsOff() } } const main = function() { if (process.argv.length < 3) { usage() process.exit(0) } debug(`starting`) lights = lightName.lightsFromNamesOrExit(process.argv.slice(2)) setLights(lights, off) setLightState() setInterval(setLightState, 60000) } const usage = function() { debug("usage: node " + __filename + " LIGHTNAME LIGHTNAME ...") debug("Each LIGHTNAME is the name of a light defined in constants.js:") var lightNames = _.pluck(constants.lights, 'name').join(", ") debug('"' + lightNames + '"') } main()
timing change
night-on.js
timing change
<ide><path>ight-on.js <ide> // turn lights on during eveningh hours <add>// flicker lights <ide> <ide> const hue = require("node-hue-api") <ide> const moment = require("moment") <ide> const on = lightState.create().on(true).hsb(40, 100, 20).transition(3000) <ide> const off = lightState.create().on(false) <ide> <add>const randomOnState = function() { <add> const _hue = Math.floor(Math.random()*100) <add> const bri = Math.floor(Math.random()* 40) <add> return lightState.create().on(true).hsb(_hue, 100, 0).transition(60000) <add>} <add> <ide> const turnLightsOn = function() { <del> setLights(lights, on) <add> setLights(lights, randomOnState()) <ide> } <ide> <ide> const turnLightsOff = function() { <ide> <ide> const onTime = function() { <ide> let h = moment().hour() <del> debug(h) <ide> return (h > 18 && h < 23) <ide> } <ide>
Java
apache-2.0
aa1586a9475cd3d1666dd7ed645bb05098001dd0
0
esoco/objectrelations
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // This file is a part of the 'objectrelations' project. // Copyright 2017 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ package de.esoco.lib.expression; import de.esoco.lib.datatype.Pair; import de.esoco.lib.expression.function.AbstractInvertibleFunction; import de.esoco.lib.property.HasOrder; import de.esoco.lib.reflect.ReflectUtil; import de.esoco.lib.text.TextConvert; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Map.Entry; import java.util.StringTokenizer; import org.obrel.core.RelationType; import org.obrel.type.MetaTypes; import static org.obrel.type.MetaTypes.ELEMENT_DATATYPE; import static org.obrel.type.MetaTypes.KEY_DATATYPE; import static org.obrel.type.MetaTypes.ORDERED; import static org.obrel.type.MetaTypes.VALUE_DATATYPE; /******************************************************************** * Contains factory methods for functions that perform datatype conversions. * Most of these functions are invertible functions that can be used to convert * values in both directions. * * @author eso */ public class Conversions { //~ Static fields/initializers --------------------------------------------- private static Map<Class<?>, InvertibleFunction<?, String>> aStringConversions; //~ Constructors ----------------------------------------------------------- /*************************************** * Private, only static use. */ private Conversions() { } //~ Static methods --------------------------------------------------------- /*************************************** * Returns the string representation of a certain value as defined by the * string conversion for the value's datatype. The string conversion for a * certain type can be queried with {@link #getStringConversion(Class)}. If * no conversion has been registered an exception will be thrown. If the * value is NULL the returned string will be 'null'. * * <p>Collections and maps will also be converted by invoking this method * recursively on the elements or keys and values. They will be separated * with the default strings in {@link * TextConvert#DEFAULT_COLLECTION_SEPARATOR} and {@link * TextConvert#DEFAULT_KEY_VALUE_SEPARATOR}.</p> * * @param rValue The value to convert into a string * * @return A string representation of the given value * * @throws IllegalArgumentException If no string conversion function has * been registered for the value's class */ public static String asString(Object rValue) { String sValue; if (rValue == null) { sValue = "null"; } else if (rValue instanceof Collection<?>) { sValue = asString((Collection<?>) rValue, TextConvert.DEFAULT_COLLECTION_SEPARATOR); } else if (rValue instanceof Map<?, ?>) { sValue = asString((Map<?, ?>) rValue, TextConvert.DEFAULT_COLLECTION_SEPARATOR, TextConvert.DEFAULT_KEY_VALUE_SEPARATOR); } else { @SuppressWarnings("unchecked") InvertibleFunction<Object, String> rConversion = (InvertibleFunction<Object, String>) getStringConversion(rValue.getClass()); if (rConversion == null) { throw new IllegalArgumentException("No string conversion registered for " + rValue.getClass()); } sValue = rConversion.evaluate(rValue); } return sValue; } /*************************************** * Returns the string representation of a collection by converting all * collection elements with the method {@link #asString(Object)}. The * resulting strings will be concatenated with the given separator string. * * <p>It is the responsibility of the invoking code to ensure that the * separator string doesn't occur in the converted collection elements. To * protect against programming errors this is safeguarded by an assertion at * development time.</p> * * @param rCollection The collection to convert into a string * @param sSeparator The separator string between the collection elements * * @return A string representation of the given collection * * @throws IllegalArgumentException If no string conversion function has * been registered for one of the * collection elements */ public static String asString(Collection<?> rCollection, String sSeparator) { StringBuilder aResult = new StringBuilder(); if (rCollection.size() > 0) { for (Object rElement : rCollection) { String sElement = asString(rElement); aResult.append(TextConvert.unicodeEncode(sElement, sSeparator)); aResult.append(sSeparator); } aResult.setLength(aResult.length() - sSeparator.length()); } return aResult.toString(); } /*************************************** * Returns the string representation of a map. This is done by converting * all map keys and values with the method {@link #asString(Object)} and * concatenating the results with the given entry separator. These converted * map entries will then be concatenated with the separator string to create * the result. * * <p>It is the responsibility of the invoking code to ensure that neither * the entry separator nor the separator string occur in the converted keys * and values.To protect against programming errors this is safeguarded by * an assertion at development time.</p> * * @param rMap The map to convert into a string * @param sEntrySeparator The separator string between the map entries * @param sKeyValueSeparator The separator string between the key and value * of a map entry * * @return A string representation of the given map * * @throws IllegalArgumentException If no string conversion function has * been registered for one of the values in * the map */ public static String asString(Map<?, ?> rMap, String sEntrySeparator, String sKeyValueSeparator) { StringBuilder aResult = new StringBuilder(); if (rMap.size() > 0) { for (Entry<?, ?> rEntry : rMap.entrySet()) { String sKey = asString(rEntry.getKey()); String sValue = asString(rEntry.getValue()); assert sKey.indexOf(sEntrySeparator) < 0 && sKey.indexOf(sKeyValueSeparator) < 0; aResult.append(sKey); aResult.append(sKeyValueSeparator); aResult.append(TextConvert.unicodeEncode(sValue, sEntrySeparator)); aResult.append(sEntrySeparator); } aResult.setLength(aResult.length() - sEntrySeparator.length()); } return aResult.toString(); } /*************************************** * Returns an invertible function that converts an enum value of a certain * enum type into a string and vice versa. * * @param rEnumClass The class of the enum the returned function will * convert * * @return An enum conversion function for the given enum type */ public static <E extends Enum<E>> InvertibleFunction<E, String> enumToString( final Class<E> rEnumClass) { return new StringConversion<E>(rEnumClass) { @Override public E invert(String sEnumName) { return Enum.valueOf(rEnumClass, sEnumName); } }; } /*************************************** * Returns a standard string conversion function for a certain datatype * class. If no string conversion has been registered for the exact class * through {@link #registerStringConversion(Class, InvertibleFunction)} this * implementation will search recursively for a conversion of one of it's * superclasses. * * @param rDatatype The datatype to return the conversion function for * * @return The invertible string conversion function or NULL if none has * been registered for the given datatype or one of it's * superclasses */ @SuppressWarnings({ "unchecked" }) public static <T, E extends Enum<E>> InvertibleFunction<T, String> getStringConversion( Class<T> rDatatype) { Map<Class<?>, InvertibleFunction<?, String>> rConversions = getStringConversionMap(); InvertibleFunction<T, String> rConversion = (InvertibleFunction<T, String>) rConversions.get(rDatatype); if (rConversion == null) { if (rDatatype.isEnum()) { rConversion = (InvertibleFunction<T, String>) enumToString((Class<E>) rDatatype); rConversions.put(rDatatype, rConversion); } else { Class<? super T> rSuperclass = rDatatype; do { rSuperclass = rSuperclass.getSuperclass(); if (rSuperclass != Object.class) { rConversion = (InvertibleFunction<T, String>) rConversions.get(rSuperclass); } else { // if no conversion found for class hierarchy try a // default string conversion rConversion = new StringConversion<T>(rDatatype); rConversions.put(rDatatype, rConversion); } } while (rConversion == null); } } return rConversion; } /*************************************** * Parses a collection from a string where the collection elements are * separated by {@link TextConvert#DEFAULT_COLLECTION_SEPARATOR}. * * @see #parseCollection(String, Class, Class, String, boolean) */ public static <E, C extends Collection<E>> C parseCollection( String sElements, Class<C> rCollectionType, Class<E> rElementType, boolean bOrdered) { return parseCollection(sElements, rCollectionType, rElementType, TextConvert.DEFAULT_COLLECTION_SEPARATOR, bOrdered); } /*************************************** * Parses a collection from a string where the collection elements are * separated by {@link TextConvert#DEFAULT_COLLECTION_SEPARATOR}. * * @param sElements A string containing the elements to be parsed; * NULL values are allowed and will result in an * empty collection * @param rCollectionType The base type of the collection * @param rElementType The type of the collection elements * @param sSeparator The separator between the collection elements * @param bOrdered TRUE for an ordered collection * * @return A new collection of an appropriate type containing the parsed * elements */ @SuppressWarnings("unchecked") public static <E, C extends Collection<E>> C parseCollection( String sElements, Class<C> rCollectionType, Class<E> rElementType, String sSeparator, boolean bOrdered) { Class<? extends C> rCollectionClass = null; if (bOrdered) { Class<?> rSetClass = LinkedHashSet.class; rCollectionClass = (Class<? extends C>) rSetClass; } else { rCollectionClass = ReflectUtil.getImplementationClass(rCollectionType); } C aCollection = ReflectUtil.newInstance(rCollectionClass); if (sElements != null) { StringTokenizer aElements = new StringTokenizer(sElements, sSeparator); while (aElements.hasMoreElements()) { String sElement = TextConvert.unicodeDecode(aElements.nextToken(), sSeparator); aCollection.add(parseValue(sElement, rElementType)); } } return aCollection; } /*************************************** * Parses a map from a string with the default map entry separator {@link * TextConvert#DEFAULT_COLLECTION_SEPARATOR} and the default key and value * separator {@link TextConvert#DEFAULT_KEY_VALUE_SEPARATOR}. * * @see #parseMap(String, Class, Class, Class, String, String, boolean) */ public static <K, V, M extends Map<K, V>> Map<K, V> parseMap( String sMapEntries, Class<M> rMapType, Class<K> rKeyType, Class<V> rValueType, boolean bOrdered) { return parseMap(sMapEntries, rMapType, rKeyType, rValueType, TextConvert.DEFAULT_COLLECTION_SEPARATOR, TextConvert.DEFAULT_KEY_VALUE_SEPARATOR, bOrdered); } /*************************************** * Parses a map from a string. * * @param sMapEntries A string containing the map entries to be * parsed; NULL values are allowed and will * result in an empty map * @param rMapType The base type of the map * @param rKeyType The type of the map keys * @param rValueType The type of the map values * @param sEntrySeparator The separator string between the map entries * @param sKeyValueSeparator The separator string between the key and value * of a map entry * @param bOrdered TRUE for an ordered map * * @return A new map of an appropriate type containing the parsed key-value * pairs */ @SuppressWarnings("unchecked") public static <K, V, M extends Map<K, V>> Map<K, V> parseMap( String sMapEntries, Class<M> rMapType, Class<K> rKeyType, Class<V> rValueType, String sEntrySeparator, String sKeyValueSeparator, boolean bOrdered) { Class<? extends M> rMapClass; if (bOrdered) { // double cast necessary for JDK javac rMapClass = (Class<? extends M>) (Class<?>) LinkedHashMap.class; } else { rMapClass = ReflectUtil.getImplementationClass(rMapType); } M aMap = ReflectUtil.newInstance(rMapClass); if (sMapEntries != null) { StringTokenizer aElements = new StringTokenizer(sMapEntries, sEntrySeparator); while (aElements.hasMoreElements()) { String sEntry = aElements.nextToken(); int nKeyEnd = sEntry.indexOf(sKeyValueSeparator); String sKey = sEntry.substring(0, nKeyEnd); String sValue = sEntry.substring(nKeyEnd + sKeyValueSeparator.length()); sValue = TextConvert.unicodeDecode(sValue, sEntrySeparator); aMap.put(parseValue(sKey, rKeyType), parseValue(sValue, rValueType)); } } return aMap; } /*************************************** * Creates an object value by parsing it's string representation as defined * by the method {@link #asString(Object)}. * * @param sValue The string value to parse * @param rDatatype The datatype of the returned object * * @return The corresponding value object of the given datatype or NULL if * the original object was NULL too * * @throws NullPointerException If one of the parameters is NULL * @throws FunctionException If the string conversion function fails * @throws IllegalArgumentException If no string conversion exists for the * given datatype */ public static <T> T parseValue(String sValue, Class<T> rDatatype) { if (rDatatype == null) { throw new NullPointerException("Datatype must not be NULL"); } if (sValue == null || sValue.equals("null")) { return null; } InvertibleFunction<T, String> rConversion = getStringConversion(rDatatype); if (rConversion == null) { throw new IllegalArgumentException("No string conversion registered for " + rDatatype); } return rConversion.invert(sValue); } /*************************************** * Parses a string value for assignment to a certain relation type. Other * than {@link #parseValue(String, Class)} this method will also parse * collections and maps. For this it relies on the meta information in the * relation type's meta information like {@link MetaTypes#ELEMENT_DATATYPE} * to determine the target datatypes. If the relation type has the flag * {@link MetaTypes#ORDERED} set an ordered collection will be created. * * @param sValue The string value to parse * @param rTargetType The relation type that defines the target datatype of * the conversion * * @return The parsed value with a datatype suitable for assigning to the * relation type * * @throws IllegalArgumentException If parsing the string fails */ @SuppressWarnings("unchecked") public static <T> T parseValue(String sValue, RelationType<T> rTargetType) { Class<T> rDatatype = (Class<T>) rTargetType.getTargetType(); T aResult; boolean bOrdered = rTargetType.hasFlag(ORDERED); if (Collection.class.isAssignableFrom(rDatatype)) { aResult = (T) parseCollection(sValue, (Class<Collection<Object>>) rDatatype, (Class<Object>) rTargetType.get(ELEMENT_DATATYPE), bOrdered); } else if (Map.class.isAssignableFrom(rDatatype)) { aResult = (T) parseMap(sValue, (Class<Map<Object, Object>>) rDatatype, (Class<Object>) rTargetType.get(KEY_DATATYPE), (Class<Object>) rTargetType.get(VALUE_DATATYPE), bOrdered); } else { if (rDatatype.isEnum() && HasOrder.class.isAssignableFrom(rDatatype)) { sValue = sValue.substring(sValue.indexOf('-') + 1); } aResult = parseValue(sValue, rDatatype); } return aResult; } /*************************************** * Registers a string conversion function for a certain datatype in the * global registry. This will replace any previously registered function for * the given datatype. Functions registered through this method can be * accessed globally through the method {@link #getStringConversion(Class)}. * * <p>It is possible to register functions for a base type of certain * datatypes because the lookup in {@link #getStringConversion(Class)} work * recursively. In such a case the application must ensure that the * registered function can also restore the correct subtype upon inversion * of the function.</p> * * @param rDatatype The datatype to register the string conversion for * @param rConversion The string conversion function */ public static <T> void registerStringConversion( Class<T> rDatatype, InvertibleFunction<? super T, String> rConversion) { getStringConversionMap().put(rDatatype, rConversion); } /*************************************** * Internal method to access the map of standard string conversion functions * and to initialize it if necessary. * * @return The map of string conversion functions */ private static Map<Class<?>, InvertibleFunction<?, String>> getStringConversionMap() { if (aStringConversions == null) { aStringConversions = new HashMap<Class<?>, InvertibleFunction<?, String>>(); aStringConversions.put(String.class, Functions.<String>identity()); aStringConversions.put(Boolean.class, new StringConversion<Boolean>(Boolean.class) { @Override public Boolean invert(String sValue) { return Boolean.valueOf(sValue); } }); aStringConversions.put(Integer.class, new StringConversion<Integer>(Integer.class) { @Override public Integer invert(String sValue) { return Integer.valueOf(sValue); } }); aStringConversions.put(Long.class, new StringConversion<Long>(Long.class) { @Override public Long invert(String sValue) { return Long.valueOf(sValue); } }); aStringConversions.put(Short.class, new StringConversion<Short>(Short.class) { @Override public Short invert(String sValue) { return Short.valueOf(sValue); } }); aStringConversions.put(Float.class, new StringConversion<Float>(Float.class) { @Override public Float invert(String sValue) { return Float.valueOf(sValue); } }); aStringConversions.put(Double.class, new StringConversion<Double>(Double.class) { @Override public Double invert(String sValue) { return Double.valueOf(sValue); } }); aStringConversions.put(RelationType.class, new StringConversion<RelationType<?>>(RelationType.class) { @Override public RelationType<?> invert(String sName) { return RelationType.valueOf(sName); } }); aStringConversions.put(Pair.class, new StringConversion<Pair<?, ?>>(Pair.class) { @Override public Pair<?, ?> invert(String sPair) { return Pair.valueOf(sPair); } }); aStringConversions.put(BigDecimal.class, new StringConversion<>(BigDecimal.class)); aStringConversions.put(BigInteger.class, new StringConversion<>(BigInteger.class)); aStringConversions.put(Date.class, new DateToStringConversion()); aStringConversions.put(Class.class, new ClassToStringConversion()); } return aStringConversions; } //~ Inner Classes ---------------------------------------------------------- /******************************************************************** * An invertible function that converts a date value into a string and vice * versa. * * @author eso */ public static class DateToStringConversion extends AbstractInvertibleFunction<Date, String> { //~ Constructors ------------------------------------------------------- /*************************************** * Creates a new instance. */ public DateToStringConversion() { super("DateToString"); } //~ Methods ------------------------------------------------------------ /*************************************** * @see Function#evaluate(Object) */ @Override public String evaluate(Date rDate) { return Long.toString(rDate.getTime()); } /*************************************** * @see InvertibleFunction#invert(Object) */ @Override public Date invert(String sValue) { return new Date(Long.parseLong(sValue)); } } /******************************************************************** * A base class for conversions that convert values into strings and vice * versa. The methods have default implementations that convert values by * invoking their {@link Object#toString()} method and try to restore them * by invoking a constructor with a single argument of type {@link String}. * If that is not sufficient subclasses can override these methods to invoke * more specific methods for certain datatypes. * * @author eso */ public static class StringConversion<T> extends AbstractInvertibleFunction<T, String> { //~ Static fields/initializers ----------------------------------------- private static final Class<?>[] STRING_ARG = new Class<?>[] { String.class }; //~ Instance fields ---------------------------------------------------- private final Class<? super T> rDatatype; //~ Constructors ------------------------------------------------------- /*************************************** * @see AbstractInvertibleFunction#AbstractInvertibleFunction(String) */ public StringConversion(Class<? super T> rDatatype) { super(rDatatype.getSimpleName() + "ToString"); this.rDatatype = rDatatype; } //~ Methods ------------------------------------------------------------ /*************************************** * Implemented to return the result of {@code rValue.toString()}. Only * subclasses for which this is not appropriate need to override this * method. * * @see Function#evaluate(Object) */ @Override public String evaluate(T rValue) { return rValue.toString(); } /*************************************** * Default implementation that tries to invoke a constructor of the * datatype with a single argument of the type {@link String}. * * @see InvertibleFunction#invert(Object) */ @Override @SuppressWarnings("unchecked") public T invert(String sValue) { return (T) ReflectUtil.newInstance(rDatatype, new Object[] { sValue }, STRING_ARG); } } /******************************************************************** * Internal class that implements a string conversion for classes. This must * use the raw type or else the registration in the string conversion map * will not be possible. * * @author eso */ @SuppressWarnings("rawtypes") private static class ClassToStringConversion extends StringConversion<Class> { //~ Constructors ------------------------------------------------------- /*************************************** * @see AbstractInvertibleFunction#AbstractInvertibleFunction(String) */ ClassToStringConversion() { super(Class.class); } //~ Methods ------------------------------------------------------------ /*************************************** * Implemented to return the result of {@link Class#getName()}. * * @see Function#evaluate(Object) */ @Override public String evaluate(Class rClass) { return rClass.getName(); } /*************************************** * Invokes {@link Class#forName(String)}. * * @see InvertibleFunction#invert(Object) */ @Override public Class<?> invert(String sValue) { try { return Class.forName(sValue); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } } } }
src/main/java/de/esoco/lib/expression/Conversions.java
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // This file is a part of the 'objectrelations' project. // Copyright 2017 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ package de.esoco.lib.expression; import de.esoco.lib.datatype.Pair; import de.esoco.lib.expression.function.AbstractInvertibleFunction; import de.esoco.lib.property.HasOrder; import de.esoco.lib.reflect.ReflectUtil; import de.esoco.lib.text.TextConvert; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Map.Entry; import java.util.StringTokenizer; import org.obrel.core.RelationType; import org.obrel.type.MetaTypes; import static org.obrel.type.MetaTypes.ELEMENT_DATATYPE; import static org.obrel.type.MetaTypes.KEY_DATATYPE; import static org.obrel.type.MetaTypes.ORDERED; import static org.obrel.type.MetaTypes.VALUE_DATATYPE; /******************************************************************** * Contains factory methods for functions that perform datatype conversions. * Most of these functions are invertible functions that can be used to convert * values in both directions. * * @author eso */ public class Conversions { //~ Static fields/initializers --------------------------------------------- private static Map<Class<?>, InvertibleFunction<?, String>> aStringConversions; //~ Constructors ----------------------------------------------------------- /*************************************** * Private, only static use. */ private Conversions() { } //~ Static methods --------------------------------------------------------- /*************************************** * Returns the string representation of a certain value as defined by the * string conversion for the value's datatype. The string conversion for a * certain type can be queried with {@link #getStringConversion(Class)}. If * no conversion has been registered an exception will be thrown. If the * value is NULL the returned string will be 'null'. * * <p>Collections and maps will also be converted by invoking this method * recursively on the elements or keys and values. They will be separated * with the default strings in {@link * TextConvert#DEFAULT_COLLECTION_SEPARATOR} and {@link * TextConvert#DEFAULT_KEY_VALUE_SEPARATOR}.</p> * * @param rValue The value to convert into a string * * @return A string representation of the given value * * @throws IllegalArgumentException If no string conversion function has * been registered for the value's class */ public static String asString(Object rValue) { String sValue; if (rValue == null) { sValue = "null"; } else if (rValue instanceof Collection<?>) { sValue = asString((Collection<?>) rValue, TextConvert.DEFAULT_COLLECTION_SEPARATOR); } else if (rValue instanceof Map<?, ?>) { sValue = asString((Map<?, ?>) rValue, TextConvert.DEFAULT_COLLECTION_SEPARATOR, TextConvert.DEFAULT_KEY_VALUE_SEPARATOR); } else { @SuppressWarnings("unchecked") InvertibleFunction<Object, String> rConversion = (InvertibleFunction<Object, String>) getStringConversion(rValue.getClass()); if (rConversion == null) { throw new IllegalArgumentException("No string conversion registered for " + rValue.getClass()); } sValue = rConversion.evaluate(rValue); } return sValue; } /*************************************** * Returns the string representation of a collection by converting all * collection elements with the method {@link #asString(Object)}. The * resulting strings will be concatenated with the given separator string. * * <p>It is the responsibility of the invoking code to ensure that the * separator string doesn't occur in the converted collection elements. To * protect against programming errors this is safeguarded by an assertion at * development time.</p> * * @param rCollection The collection to convert into a string * @param sSeparator The separator string between the collection elements * * @return A string representation of the given collection * * @throws IllegalArgumentException If no string conversion function has * been registered for one of the * collection elements */ public static String asString(Collection<?> rCollection, String sSeparator) { StringBuilder aResult = new StringBuilder(); if (rCollection.size() > 0) { for (Object rElement : rCollection) { String sElement = asString(rElement); aResult.append(TextConvert.unicodeEncode(sElement, sSeparator)); aResult.append(sSeparator); } aResult.setLength(aResult.length() - sSeparator.length()); } return aResult.toString(); } /*************************************** * Returns the string representation of a map. This is done by converting * all map keys and values with the method {@link #asString(Object)} and * concatenating the results with the given entry separator. These converted * map entries will then be concatenated with the separator string to create * the result. * * <p>It is the responsibility of the invoking code to ensure that neither * the entry separator nor the separator string occur in the converted keys * and values.To protect against programming errors this is safeguarded by * an assertion at development time.</p> * * @param rMap The map to convert into a string * @param sEntrySeparator The separator string between the map entries * @param sKeyValueSeparator The separator string between the key and value * of a map entry * * @return A string representation of the given map * * @throws IllegalArgumentException If no string conversion function has * been registered for one of the values in * the map */ public static String asString(Map<?, ?> rMap, String sEntrySeparator, String sKeyValueSeparator) { StringBuilder aResult = new StringBuilder(); if (rMap.size() > 0) { for (Entry<?, ?> rEntry : rMap.entrySet()) { String sKey = asString(rEntry.getKey()); String sValue = asString(rEntry.getValue()); assert sKey.indexOf(sEntrySeparator) < 0 && sKey.indexOf(sKeyValueSeparator) < 0; aResult.append(sKey); aResult.append(sKeyValueSeparator); aResult.append(TextConvert.unicodeEncode(sValue, sEntrySeparator)); aResult.append(sEntrySeparator); } aResult.setLength(aResult.length() - sEntrySeparator.length()); } return aResult.toString(); } /*************************************** * Returns an invertible function that converts an enum value of a certain * enum type into a string and vice versa. * * @param rEnumClass The class of the enum the returned function will * convert * * @return An enum conversion function for the given enum type */ public static <E extends Enum<E>> InvertibleFunction<E, String> enumToString( final Class<E> rEnumClass) { return new StringConversion<E>(rEnumClass) { @Override public E invert(String sEnumName) { return Enum.valueOf(rEnumClass, sEnumName); } }; } /*************************************** * Returns a standard string conversion function for a certain datatype * class. If no string conversion has been registered for the exact class * through {@link #registerStringConversion(Class, InvertibleFunction)} this * implementation will search recursively for a conversion of one of it's * superclasses. * * @param rDatatype The datatype to return the conversion function for * * @return The invertible string conversion function or NULL if none has * been registered for the given datatype or one of it's * superclasses */ @SuppressWarnings({ "unchecked" }) public static <T, E extends Enum<E>> InvertibleFunction<T, String> getStringConversion( Class<T> rDatatype) { Map<Class<?>, InvertibleFunction<?, String>> rConversions = getStringConversionMap(); InvertibleFunction<T, String> rConversion = (InvertibleFunction<T, String>) rConversions.get(rDatatype); if (rConversion == null) { if (rDatatype.isEnum()) { rConversion = (InvertibleFunction<T, String>) enumToString((Class<E>) rDatatype); rConversions.put(rDatatype, rConversion); } else { Class<? super T> rSuperclass = rDatatype; do { rSuperclass = rSuperclass.getSuperclass(); if (rSuperclass != Object.class) { rConversion = (InvertibleFunction<T, String>) rConversions.get(rSuperclass); } else { // if no conversion found for class hierarchy try a // default string conversion rConversion = new StringConversion<T>(rDatatype); rConversions.put(rDatatype, rConversion); } } while (rConversion == null); } } return rConversion; } /*************************************** * Parses a collection from a string where the collection elements are * separated by {@link TextConvert#DEFAULT_COLLECTION_SEPARATOR}. * * @see #parseCollection(String, Class, Class, String, boolean) */ public static <E, C extends Collection<E>> C parseCollection( String sElements, Class<C> rCollectionType, Class<E> rElementType, boolean bOrdered) { return parseCollection(sElements, rCollectionType, rElementType, TextConvert.DEFAULT_COLLECTION_SEPARATOR, bOrdered); } /*************************************** * Parses a collection from a string where the collection elements are * separated by {@link TextConvert#DEFAULT_COLLECTION_SEPARATOR}. * * @param sElements A string containing the elements to be parsed; * NULL values are allowed and will result in an * empty collection * @param rCollectionType The base type of the collection * @param rElementType The type of the collection elements * @param sSeparator The separator between the collection elements * @param bOrdered TRUE for an ordered collection * * @return A new collection of an appropriate type containing the parsed * elements */ @SuppressWarnings("unchecked") public static <E, C extends Collection<E>> C parseCollection( String sElements, Class<C> rCollectionType, Class<E> rElementType, String sSeparator, boolean bOrdered) { Class<? extends C> rCollectionClass = null; if (bOrdered) { Class<?> rSetClass = LinkedHashSet.class; rCollectionClass = (Class<? extends C>) rSetClass; } else { rCollectionClass = ReflectUtil.getImplementationClass(rCollectionType); } C aCollection = ReflectUtil.newInstance(rCollectionClass); if (sElements != null) { StringTokenizer aElements = new StringTokenizer(sElements, sSeparator); while (aElements.hasMoreElements()) { String sElement = TextConvert.unicodeDecode(aElements.nextToken(), sSeparator); aCollection.add(parseValue(sElement, rElementType)); } } return aCollection; } /*************************************** * Parses a map from a string with the default map entry separator {@link * TextConvert#DEFAULT_COLLECTION_SEPARATOR} and the default key and value * separator {@link TextConvert#DEFAULT_KEY_VALUE_SEPARATOR}. * * @see #parseMap(String, Class, Class, Class, String, String, boolean) */ public static <K, V, M extends Map<K, V>> Map<K, V> parseMap( String sMapEntries, Class<M> rMapType, Class<K> rKeyType, Class<V> rValueType, boolean bOrdered) { return parseMap(sMapEntries, rMapType, rKeyType, rValueType, TextConvert.DEFAULT_COLLECTION_SEPARATOR, TextConvert.DEFAULT_KEY_VALUE_SEPARATOR, bOrdered); } /*************************************** * Parses a map from a string. * * @param sMapEntries A string containing the map entries to be * parsed; NULL values are allowed and will * result in an empty map * @param rMapType The base type of the map * @param rKeyType The type of the map keys * @param rValueType The type of the map values * @param sEntrySeparator The separator string between the map entries * @param sKeyValueSeparator The separator string between the key and value * of a map entry * @param bOrdered TRUE for an ordered map * * @return A new map of an appropriate type containing the parsed key-value * pairs */ @SuppressWarnings("unchecked") public static <K, V, M extends Map<K, V>> Map<K, V> parseMap( String sMapEntries, Class<M> rMapType, Class<K> rKeyType, Class<V> rValueType, String sEntrySeparator, String sKeyValueSeparator, boolean bOrdered) { Class<? extends M> rMapClass; if (bOrdered) { // double cast necessary for JDK javac rMapClass = (Class<? extends M>) (Class<?>) LinkedHashMap.class; } else { rMapClass = ReflectUtil.getImplementationClass(rMapType); } M aMap = ReflectUtil.newInstance(rMapClass); if (sMapEntries != null) { StringTokenizer aElements = new StringTokenizer(sMapEntries, sEntrySeparator); while (aElements.hasMoreElements()) { String sEntry = aElements.nextToken(); int nKeyEnd = sEntry.indexOf(sKeyValueSeparator); String sKey = sEntry.substring(0, nKeyEnd); String sValue = sEntry.substring(nKeyEnd + sKeyValueSeparator.length()); sValue = TextConvert.unicodeDecode(sValue, sEntrySeparator); aMap.put(parseValue(sKey, rKeyType), parseValue(sValue, rValueType)); } } return aMap; } /*************************************** * Creates an object value by parsing it's string representation as defined * by the method {@link #asString(Object)}. * * @param sValue The string value to parse * @param rDatatype The datatype of the returned object * * @return The corresponding value object of the given datatype or NULL if * the original object was NULL too * * @throws NullPointerException If one of the parameters is NULL * @throws FunctionException If the string conversion function fails * @throws IllegalArgumentException If no string conversion exists for the * given datatype */ public static <T> T parseValue(String sValue, Class<T> rDatatype) { if (rDatatype == null) { throw new NullPointerException("Datatype must not be NULL"); } if (sValue == null || sValue.equals("null")) { return null; } InvertibleFunction<T, String> rConversion = getStringConversion(rDatatype); if (rConversion == null) { throw new IllegalArgumentException("No string conversion registered for " + rDatatype); } return rConversion.invert(sValue); } /*************************************** * Parses a string value for assignment to a certain relation type. Other * than {@link #parseValue(String, Class)} this method will also parse * collections and maps. For this it relies on the meta information in the * relation type's meta information like {@link MetaTypes#ELEMENT_DATATYPE} * to determine the target datatypes. If the relation type has the flag * {@link MetaTypes#ORDERED} set an ordered collection will be created. * * @param sValue The string value to parse * @param rTargetType The relation type that defines the target datatype of * the conversion * * @return The parsed value with a datatype suitable for assigning to the * relation type * * @throws IllegalArgumentException If parsing the string fails */ @SuppressWarnings("unchecked") public static <T> T parseValue(String sValue, RelationType<T> rTargetType) { Class<T> rDatatype = (Class<T>) rTargetType.getTargetType(); T aResult; boolean bOrdered = rTargetType.hasFlag(ORDERED); if (Collection.class.isAssignableFrom(rDatatype)) { aResult = (T) parseCollection(sValue, (Class<Collection<Object>>) rDatatype, (Class<Object>) rTargetType.get(ELEMENT_DATATYPE), bOrdered); } else if (Map.class.isAssignableFrom(rDatatype)) { aResult = (T) parseMap(sValue, (Class<Map<Object, Object>>) rDatatype, (Class<Object>) rTargetType.get(KEY_DATATYPE), (Class<Object>) rTargetType.get(VALUE_DATATYPE), bOrdered); } else { if (rDatatype.isEnum() && HasOrder.class.isAssignableFrom(rDatatype)) { sValue = sValue.substring(sValue.indexOf('-') + 1); } aResult = parseValue(sValue, rDatatype); } return aResult; } /*************************************** * Registers a string conversion function for a certain datatype in the * global registry. This will replace any previously registered function for * the given datatype. Functions registered through this method can be * accessed globally through the method {@link #getStringConversion(Class)}. * * <p>It is possible to register functions for a base type of certain * datatypes because the lookup in {@link #getStringConversion(Class)} work * recursively. In such a case the application must ensure that the * registered function can also restore the correct subtype upon inversion * of the function.</p> * * @param rDatatype The datatype to register the string conversion for * @param rConversion The string conversion function */ public static <T> void registerStringConversion( Class<T> rDatatype, InvertibleFunction<? super T, String> rConversion) { getStringConversionMap().put(rDatatype, rConversion); } /*************************************** * Internal method to access the map of standard string conversion functions * and to initialize it if necessary. * * @return The map of string conversion functions */ @SuppressWarnings("rawtypes") private static Map<Class<?>, InvertibleFunction<?, String>> getStringConversionMap() { if (aStringConversions == null) { aStringConversions = new HashMap<Class<?>, InvertibleFunction<?, String>>(); aStringConversions.put(String.class, Functions.<String>identity()); aStringConversions.put(Boolean.class, new StringConversion<Boolean>(Boolean.class) { @Override public Boolean invert(String sValue) { return Boolean.valueOf(sValue); } }); aStringConversions.put(Integer.class, new StringConversion<Integer>(Integer.class) { @Override public Integer invert(String sValue) { return Integer.valueOf(sValue); } }); aStringConversions.put(Long.class, new StringConversion<Long>(Long.class) { @Override public Long invert(String sValue) { return Long.valueOf(sValue); } }); aStringConversions.put(Short.class, new StringConversion<Short>(Short.class) { @Override public Short invert(String sValue) { return Short.valueOf(sValue); } }); aStringConversions.put(Float.class, new StringConversion<Float>(Float.class) { @Override public Float invert(String sValue) { return Float.valueOf(sValue); } }); aStringConversions.put(Double.class, new StringConversion<Double>(Double.class) { @Override public Double invert(String sValue) { return Double.valueOf(sValue); } }); aStringConversions.put(RelationType.class, new StringConversion<RelationType>(RelationType.class) { @Override public RelationType<?> invert(String sName) { return RelationType.valueOf(sName); } }); aStringConversions.put(Pair.class, new StringConversion<Pair>(Pair.class) { @Override public Pair<?, ?> invert(String sPair) { return Pair.valueOf(sPair); } }); aStringConversions.put(BigDecimal.class, new StringConversion<>(BigDecimal.class)); aStringConversions.put(BigInteger.class, new StringConversion<>(BigInteger.class)); aStringConversions.put(Date.class, new DateToStringConversion()); aStringConversions.put(Class.class, new ClassToStringConversion()); } return aStringConversions; } //~ Inner Classes ---------------------------------------------------------- /******************************************************************** * An invertible function that converts a date value into a string and vice * versa. * * @author eso */ public static class DateToStringConversion extends AbstractInvertibleFunction<Date, String> { //~ Constructors ------------------------------------------------------- /*************************************** * Creates a new instance. */ public DateToStringConversion() { super("DateToString"); } //~ Methods ------------------------------------------------------------ /*************************************** * @see Function#evaluate(Object) */ @Override public String evaluate(Date rDate) { return Long.toString(rDate.getTime()); } /*************************************** * @see InvertibleFunction#invert(Object) */ @Override public Date invert(String sValue) { return new Date(Long.parseLong(sValue)); } } /******************************************************************** * A base class for conversions that convert values into strings and vice * versa. The methods have default implementations that convert values by * invoking their {@link Object#toString()} method and try to restore them * by invoking a constructor with a single argument of type {@link String}. * If that is not sufficient subclasses can override these methods to invoke * more specific methods for certain datatypes. * * @author eso */ public static class StringConversion<T> extends AbstractInvertibleFunction<T, String> { //~ Static fields/initializers ----------------------------------------- private static final Class<?>[] STRING_ARG = new Class<?>[] { String.class }; //~ Instance fields ---------------------------------------------------- private final Class<T> rDatatype; //~ Constructors ------------------------------------------------------- /*************************************** * @see AbstractInvertibleFunction#AbstractInvertibleFunction(String) */ public StringConversion(Class<T> rDatatype) { super(rDatatype.getSimpleName() + "ToString"); this.rDatatype = rDatatype; } //~ Methods ------------------------------------------------------------ /*************************************** * Implemented to return the result of {@code rValue.toString()}. Only * subclasses for which this is not appropriate need to override this * method. * * @see Function#evaluate(Object) */ @Override public String evaluate(T rValue) { return rValue.toString(); } /*************************************** * Default implementation that tries to invoke a constructor of the * datatype with a single argument of the type {@link String}. * * @see InvertibleFunction#invert(Object) */ @Override public T invert(String sValue) { return ReflectUtil.newInstance(rDatatype, new Object[] { sValue }, STRING_ARG); } } /******************************************************************** * Internal class that implements a string conversion for classes. This must * use the raw type or else the registration in the string conversion map * will not be possible. * * @author eso */ @SuppressWarnings("rawtypes") private static class ClassToStringConversion extends StringConversion<Class> { //~ Constructors ------------------------------------------------------- /*************************************** * @see AbstractInvertibleFunction#AbstractInvertibleFunction(String) */ ClassToStringConversion() { super(Class.class); } //~ Methods ------------------------------------------------------------ /*************************************** * Implemented to return the result of {@link Class#getName()}. * * @see Function#evaluate(Object) */ @Override public String evaluate(Class rClass) { return rClass.getName(); } /*************************************** * Invokes {@link Class#forName(String)}. * * @see InvertibleFunction#invert(Object) */ @Override public Class<?> invert(String sValue) { try { return Class.forName(sValue); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } } } }
OPT: generic declaration of StringConversion
src/main/java/de/esoco/lib/expression/Conversions.java
OPT: generic declaration of StringConversion
<ide><path>rc/main/java/de/esoco/lib/expression/Conversions.java <ide> * <ide> * @return The map of string conversion functions <ide> */ <del> @SuppressWarnings("rawtypes") <ide> private static Map<Class<?>, InvertibleFunction<?, String>> getStringConversionMap() <ide> { <ide> if (aStringConversions == null) <ide> } <ide> }); <ide> aStringConversions.put(RelationType.class, <del> new StringConversion<RelationType>(RelationType.class) <add> new StringConversion<RelationType<?>>(RelationType.class) <ide> { <ide> @Override <ide> public RelationType<?> invert(String sName) <ide> } <ide> }); <ide> aStringConversions.put(Pair.class, <del> new StringConversion<Pair>(Pair.class) <add> new StringConversion<Pair<?, ?>>(Pair.class) <ide> { <ide> @Override <ide> public Pair<?, ?> invert(String sPair) <ide> <ide> //~ Instance fields ---------------------------------------------------- <ide> <del> private final Class<T> rDatatype; <add> private final Class<? super T> rDatatype; <ide> <ide> //~ Constructors ------------------------------------------------------- <ide> <ide> /*************************************** <ide> * @see AbstractInvertibleFunction#AbstractInvertibleFunction(String) <ide> */ <del> public StringConversion(Class<T> rDatatype) <add> public StringConversion(Class<? super T> rDatatype) <ide> { <ide> super(rDatatype.getSimpleName() + "ToString"); <ide> this.rDatatype = rDatatype; <ide> * @see InvertibleFunction#invert(Object) <ide> */ <ide> @Override <add> @SuppressWarnings("unchecked") <ide> public T invert(String sValue) <ide> { <del> return ReflectUtil.newInstance(rDatatype, <del> new Object[] { sValue }, <del> STRING_ARG); <add> return (T) ReflectUtil.newInstance(rDatatype, <add> new Object[] { sValue }, <add> STRING_ARG); <ide> } <ide> } <ide>
JavaScript
mit
751093458084f48a76e6f04b439e416f22ad86b9
0
pboyer/verb,pboyer/verb
var fs = require('fs') , path = require('path'); parse( path.join( __dirname, "../src/verb/geom/ISurface.hx") ); function parse(srcfn){ var input = fs.readFileSync( srcfn, "utf8" ); var tokenStream = new TokenStream( input ); var parser = new Parser( tokenStream ); return parser.parse(); } // // An incomplete parser for Haxe that to aid in // constructing documentation // function Parser( tokenStream ){ var debug = false; var currentToken, lastComment, types = []; function tokenMatchesAny( possibleTypes ){ for(var i = 0; i < possibleTypes.length; i++) { if ( possibleTypes[i] === currentToken.type){ return true; } } return false; } function consume( expectedType ){ currentToken = tokenStream.consume(); if (debug) console.log("currentToken", currentToken); if ( expectedType && !tokenMatchesAny( Array.prototype.slice.call(arguments) )){ console.log(tokenStream.neighborhood()); throw new Error( "Syntax Error - expectedType \"" + Array.prototype.join.call( arguments, ", ") + "\", but got \"" + currentToken.type + "\"" + "\n\n" + tokenStream.neighborhood() + "\n" + " ^ " ); } return currentToken; } function peak(){ return tokenStream.peak(); } function parseExtends(){ consume("extends"); // get the type name var r = consume(); return r.contents; } function parseIdList(){ var idlist = [] , peaked; do { consume(); if ( currentToken.type === "id" ){ idlist.push( currentToken.contents ); } } while ( (peaked = peak()) && (peaked.type === "id" || peaked.type === ",") ) return idlist; } function parseImplements(){ consume("implements"); return parseIdList(); } function parseClass( visibility ){ // get visibility from current token or default visibility = visibility || "public"; consume("class"); // get the type name for the class var typeName = consume().contents; // build the class type var def = new Class( typeName, visibility ); // set the description if (lastComment){ def.description = lastComment // don't reuse the lastComment lastComment = undefined; } var peaked = peak(); // parent class if ( peaked.type === "extends" ){ def.parentClass = parseExtends(); // look further ahead peaked = peak(); } // parse interfaces if ( peaked.type === "implements" ){ def.interfaces = parseImplements(); } parseClassBody( def ); console.log(def); return def; } function consumeBlock(){ consume("{"); var parenCount = 1; while ( parenCount != 0 ){ consume(); if (currentToken.type === "{") { parenCount++; } else if (currentToken.type === "}"){ parenCount--; } } } function consumeIf(char){ var peaked = peak(); if (peaked.type === char) consume(); } function consumeUntil(char){ var peaked; while ( (peaked = peak()) && peaked.type != char ){ consume(); } } function consumeUntilInclusive(char){ consumeUntil(char); consume(char); } function parseProperty( isStatic ){ consume("var"); var name = consume().contents; var type; var peaked = peak(); if (peaked.type === ":"){ consume(":"); type = consume("id").contents; peaked = peak(); } consumeUntilInclusive(";"); return new Property( name, type, isStatic ); } function parseMethodArgument(){ // id : Type = expression var name = consume("id").contents; var peaked = peak(); var type; if (peaked.type === ":"){ type = parseTypeAnnotation(); peaked = peak(); } var defaultVal; if (peaked.type === "="){ consume("="); defaultVal = consume("number", "string", "boolean", "null").contents; } return new MethodArgument(name, type, defaultVal); } function parseMethodArguments(){ // ( methodArgument, methodArgument ) consume("("); var peaked, args = []; while ( (peaked = peak()) && peaked.type != ")"){ if (peaked.type === "id"){ args.push( parseMethodArgument() ); } else if (peaked.type === ","){ consume(","); // consume the "," } } consume(")"); return args; } function getLastComment(){ var lc = lastComment; lastComment = undefined; return lc ? lc.contents : lc; } function parseTypeAnnotation(){ consume(":"); return consume("id").contents; } function parseMethod( isStatic ){ // function MethodName( methodArgument, methodArgument ) : ExpectedType { ... } consume("function"); var name = consume("id", "new").contents; var args = parseMethodArguments(); peaked = peak(); var type; if (peaked.type === ":"){ type = parseTypeAnnotation(); } consumeBlock(); return new Method( name, args, type, getLastComment() ); } function parseClassMember( def, visibility ){ // parse "public" or "private" var visibility = visibility ? visibility : consume("visibility").contents; // hack to ignore private members if ( visibility === "private"){ def = new Class(); } var peaked = peak(); var isStatic = false; if ( peaked.type === "static" ){ isStatic = true; consume("static"); peaked = peak(); } if ( peaked.type === "var" ){ return def.properties.push( parseProperty( isStatic )); } else if (peaked.type === "function"){ return def.methods.push( parseMethod( isStatic )); } throw new Error("Unknown class member encountered" + JSON.stringify( peaked )); } function parseClassBody( def ){ consume("{"); var peaked; while ( (peaked = peak()) && peaked.type != "}"){ if (peaked.type === "comment"){ parseComment(); continue; } else if (peaked.type === "visibility"){ parseClassMember( def ); continue; } else if (peaked.type === "function"){ parseClassMember( def, "private" ); continue; } else if (peaked.type === "var"){ parseClassMember( def, "private" ); continue; } else if (peaked.type === "static"){ parseClassMember( def, "private" ); continue; } consume(); } consume("}"); } function parseMethodDefinition(){ // function MethodName( methodArgument, methodArgument ) : ExpectedType; consume("function"); var name = consume("id", "new").contents; var args = parseMethodArguments(); peaked = peak(); var type; if (peaked.type === ":"){ type = parseTypeAnnotation(); } consumeUntilInclusive(";"); return new Method( name, args, type, getLastComment() ); } function parseInterfaceMember( def, visibility ){ // parse "public" or "private" var visibility = visibility ? visibility : consume("visibility").contents; // hack to ignore private members if ( visibility === "private"){ def = new Interface(); } var peaked = peak(); if ( peaked.type === "var" ){ return def.properties.push( parseProperty()); } else if (peaked.type === "function"){ return def.methods.push( parseMethodDefinition()); } throw new Error("Unknown interface member type encountered" + JSON.stringify( peaked )); } function parseInterfaceBody( def ){ consume("{"); var peaked; while ( (peaked = peak()) && peaked.type != "}"){ if (peaked.type === "comment"){ parseComment(); continue; } else if (peaked.type === "visibility"){ parseInterfaceMember( def ); continue; } else if (peaked.type === "function"){ parseInterfaceMember( def, "public" ); continue; } consume(); } consume("}"); } function parseInterface( visibility ){ // get visibility from current token or default visibility = visibility || "public"; consume("interface"); // get the type name for the class var typeName = consume().contents; // build the class type var def = new Interface( typeName, visibility ); // set the description def.description = getLastComment(); if ( peak().type === "implements" ){ def.interfaces = parseImplements(); } parseInterfaceBody( def ); console.log( def ); return def; } function parseTypeDefinition(){ var visibility = consume("visibility").contents; var peaked = peak(); if (peaked.contents === "class"){ return parseClass(); } else if (peaked.contents === "interface"){ return parseInterface(); } throw new Error("Not implemented" + JSON.stringify( peaked )); } function parseComment() { var squashed = consume("comment"); while ( peak().type === "comment" ){ currentToken = consume(); squashed.contents += "\n"; squashed.contents += currentToken.contents; } return lastComment = squashed; } this.parse = () => { var peaked; while ( (peaked = peak()) ){ if (peaked.type === "class"){ types.push( parseClass() ); } else if (peaked.type === "interface"){ types.push( parseInterface() ); } else if ( peaked.type === "visibility" ){ types.push( parseTypeDefinition() ); } else if (peaked.type === "comment"){ parseComment(); } else { consume(); } } return types; } } function TokenStream( input ){ // token state var i = 0; var peaking = false; var line = 1; var col = 0; // helpers var isNumeric = (c) => c === "." || c=== "+" || c === "-" || (c <= '9' && c >= '0'); var isInnerNumeric = (c) => isNumeric(c) || c === "e" || c === "E"; var isWhitespace = (c) => c === '\n' || c === '\t' || c === ' '; var isComment = (c) => c === '/'; var isSeparator = (c) => c === ";" || c === "(" || c === ")" || c === "{" || c === "}" || c === "," || c === ":" || c === "="; var isLineEnd = (c) => c === '\n'; var isAlpha = (c) => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); var make = (type, contents) => ({ type : type, contents : contents, line: line, col: col }); var categorizeId = (s) => { if (s === "class"){ return make(s,s); } else if (s === "interface") { return make(s,s); } else if (s === "true"){ return make("boolean", s); } else if (s === "true"){ return make("boolean", s); } else if (s === "private"){ return make("visibility", s); } else if (s === "public"){ return make("visibility", s); } else if (s === "extends"){ return make(s,s); } else if (s === "implements"){ return make(s,s); } else if (s === "typedef"){ return make(s,s); } else if (s === "function"){ return make(s,s); } else if (s === "static"){ return make(s,s); } else if (s === "new"){ return make(s,s); } else if (s === "null"){ return make(s,s); } else if (s === "var"){ return make(s,s); } return make("id", s); }; var inc = () => { if (!peaking){ col++; if (input.charAt(i) === '\n'){ line++; col = 0; } } i++; return i; }; // functions this.empty = () => i >= input.length; this.peak = () => { peaking = true; var m = i; var t = this.consume(); i = m; peaking = false; return t; }; this.neighborhood = () => { return input.slice(i-10, i+10); } this.consume = () => { var c = input.charAt(i); var s; while ( c ){ s = ""; c = input.charAt(i); // Separators if ( isSeparator( c ) ){ inc(); return make(c); } // Numbers else if ( isNumeric( c ) ){ while ( c && isNumeric(c) ){ s += c; c = input.charAt(inc()); } return make("number", s); } // Name else if ( isAlpha(c) ){ while ( c && !isWhitespace(c) && !isSeparator(c)){ s += c; c = input.charAt(inc()); } return categorizeId(s); // Comment } else if (isComment(c) && isComment(input.charAt(i+1))) { // trim comments while (isComment(input.charAt(i))){ inc() } c = input.charAt(i); // consume comments while ( c && !isLineEnd(c) ){ s += c; c = input.charAt(inc()); } return make("comment", s); } inc(); } return null; } } function Method(name, args, returnType, description){ this.name = name; this.description = description || ""; this.args = args || []; this.returnType = returnType; } function MethodArgument(name, type, defaultValue){ this.name = name; this.type = type; this.defaultValue = defaultValue; } function Property(name, type){ this.name = name; this.type = type; } function Typedef(name){ this.name = name; } function Enum(name, fields){ this.name = name; this.fields = fields; } function Interface(name){ this.name = name; this.description = ""; this.methods = []; } function Class(name, visibility){ this.visibility = visibility; this.name = name; this.description = ""; this.methods = []; this.parentClass = undefined; this.interfaces = []; this.properties = []; }
docs/parse.js
var fs = require('fs') , path = require('path'); parse( path.join( __dirname, "../src/verb/geom/NurbsCurve.hx") ); function parse(srcfn){ var input = fs.readFileSync( srcfn, "utf8" ); var tokenStream = new TokenStream( input ); var parser = new Parser( tokenStream ); return parser.parse(); } function Parser( tokenStream ){ var debug = false; var currentToken, lastComment, types = []; function tokenMatchesAny( possibleTypes ){ for(var i = 0; i < possibleTypes.length; i++) { if ( possibleTypes[i] === currentToken.type){ return true; } } return false; } function consume( expectedType ){ currentToken = tokenStream.consume(); if (debug) console.log("currentToken", currentToken); if ( expectedType && !tokenMatchesAny( Array.prototype.slice.call(arguments) )){ console.log(tokenStream.neighborhood()); throw new Error("Syntax Error - expectedType \"" + expectedType + "\", but got \"" + currentToken.type + "\""); } return currentToken; } function peak(){ return tokenStream.peak(); } function parseExtends(){ consume("extends"); // get the type name var r = consume(); return r.contents; } function parseIdList(){ var idlist = [] , peaked; do { consume(); if ( currentToken.type === "id" ){ idlist.push( currentToken.contents ); } } while ( (peaked = peak()) && (peaked.type === "id" || peaked.type === ",") ) return idlist; } function parseImplements(){ consume("implements"); return parseIdList(); } function parseClass( visibility ){ // get visibility from current token or default visibility = visibility || "public"; consume("class"); // get the type name for the class var typeName = consume().contents; // build the class type var classDef = new Class( typeName, visibility ); // set the description if (lastComment){ classDef.description = lastComment // don't reuse the lastComment lastComment = undefined; } var peaked = peak(); // parent class if ( peaked.type === "extends" ){ classDef.parentClass = parseExtends(); // look further ahead peaked = peak(); } // parse interfaces if ( peaked.type === "implements" ){ classDef.interfaces = parseImplements(); } parseClassBody( classDef ); // console.log(classDef); return classDef; } function consumeBlock(){ consume("{"); var parenCount = 1; while ( parenCount != 0 ){ consume(); if (currentToken.type === "{") { parenCount++; } else if (currentToken.type === "}"){ parenCount--; } } } function consumeIf(char){ var peaked = peak(); if (peaked.type === char) consume(); } function consumeUntil(char){ var peaked; while ( (peaked = peak()) && peaked.type != char ){ consume(); } } function consumeUntilInclusive(char){ consumeUntil(char); consume(char); } function parseProperty( isStatic ){ consume("var"); var name = consume().contents; var type; var peaked = peak(); if (peaked.type === ":"){ consume(":"); type = consume("id").contents; peaked = peak(); } consumeUntilInclusive(";"); return new Property( name, type, isStatic ); } function parseMethodArgument(){ // id : Type = expression var name = consume("id").contents; var peaked = peak(); var type; if (peaked.type === ":"){ type = parseTypeAnnotation(); peaked = peak(); } var defaultVal; if (peaked.type === "="){ consume("="); defaultVal = consume("number", "string", "null").contents; } return new MethodArgument(name, type, defaultVal); } function parseMethodArguments(){ // ( methodArgument, methodArgument ) consume("("); var peaked, args = []; while ( (peaked = peak()) && peaked.type != ")"){ if (peaked.type === "id"){ args.push( parseMethodArgument() ); } else if (peaked.type === ","){ consume(","); // consume the "," } } consume(")"); return args; } function getLastComment(){ var lc = lastComment; lastComment = undefined; return lc; } function parseTypeAnnotation(){ consume(":"); return consume("id").contents; } function parseMethod( isStatic ){ // function MethodName( methodArgument, methodArgument ) : ExpectedType { ... } consume("function"); var name = consume("id", "new").contents; var args = parseMethodArguments(); peaked = peak(); var type; if (peaked.type === ":"){ type = parseTypeAnnotation(); } consumeBlock(); return new Method( name, args, type, getLastComment() ); } function parseClassMember( classDef, visibility ){ // parse "public" or "private" var visibility = visibility ? visibility : consume("visibility").contents; // hack to ignore private members if ( visibility === "private"){ classDef = new Class(); } var peaked = peak(); var isStatic = false; if ( peaked.type === "static" ){ isStatic = true; consume("static"); peaked = peak(); } if ( peaked.type === "var" ){ return classDef.properties.push( parseProperty( isStatic )); } else if (peaked.type === "function"){ return classDef.properties.push( parseMethod( isStatic )); } throw new Error("Unknown member type encountered" + JSON.stringify( peaked )); } function parseClassBody( classDef ){ consume("{"); var peaked; while ( (peaked = peak()) && peaked.type != "}"){ if (peaked.type === "comment"){ parseComment(); continue; } else if (peaked.type === "visibility"){ parseClassMember( classDef ); continue; } else if (peaked.type === "function"){ parseClassMember( classDef, "private" ); continue; } else if (peaked.type === "var"){ parseClassMember( classDef, "private" ); continue; } else if (peaked.type === "static"){ parseClassMember( classDef, "private" ); continue; } consume(); } consume("}"); } function parseTypeDefinition(){ var visibility = consume("visibility").contents; var peaked = peak(); if (peaked.contents === "class"){ return parseClass(); } throw new Error("Not implemented" + JSON.stringify( peaked )); } function parseComment() { var squashed = consume("comment"); while ( peak().type === "comment" ){ currentToken = consume(); squashed.contents += "\n"; squashed.contents += currentToken.contents; } return lastComment = squashed; } this.parse = () => { var peaked; while ( (peaked = peak()) ){ if (peaked.type === "class"){ types.push( parseClass() ); } else if ( peaked.type === "visibility" ){ types.push( parseTypeDefinition() ); } else if (peaked.type === "comment"){ parseComment(); } else { consume(); } } return types; } } function TokenStream( input ){ // token state var i = 0; var peaking = false; var line = 1; var col = 0; // helpers var isNumeric = (c) => c === "." || c=== "+" || c === "-" || (c <= '9' && c >= '0'); var isInnerNumeric = (c) => isNumeric(c) || c === "e" || c === "E"; var isWhitespace = (c) => c === '\n' || c === '\t' || c === ' '; var isComment = (c) => c === '/'; var isSeparator = (c) => c === ";" || c === "(" || c === ")" || c === "{" || c === "}" || c === "," || c === ":" || c === "="; var isLineEnd = (c) => c === '\n'; var isAlpha = (c) => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); var make = (type, contents) => ({ type : type, contents : contents || type, line: line, col: col }); var categorizeId = (s) => { if (s === "class"){ return make(s); } else if (s === "private"){ return make("visibility", s); } else if (s === "public"){ return make("visibility", s); } else if (s === "extends"){ return make(s); } else if (s === "implements"){ return make(s); } else if (s === "typedef"){ return make(s); } else if (s === "function"){ return make(s); } else if (s === "static"){ return make(s); } else if (s === "new"){ return make(s); } else if (s === "null"){ return make(s); } else if (s === "var"){ return make(s); } return make("id", s); } // functions this.empty = () => i >= input.length; this.peak = () => { peaking = true; var m = i; var t = this.consume(); i = m; peaking = false; return t; }; this.neighborhood = () => { return input.slice(i-10, i+10); } var inc = () => { if (!peaking){ col++; if (input.charAt(i) === '\n'){ line++; col = 0; } } i++; return i; }; this.consume = () => { var c = input.charAt(i); var s; while ( c ){ s = ""; c = input.charAt(i); // Separators if ( isSeparator( c ) ){ inc(); return make(c); } // Numbers else if ( isNumeric( c ) ){ while ( c && isNumeric(c) ){ s += c; c = input.charAt(inc()); } return make("number", s); } // Name else if ( isAlpha(c) ){ while ( c && !isWhitespace(c) && !isSeparator(c)){ s += c; c = input.charAt(inc()); } return categorizeId(s); // Comment } else if (isComment(c) && isComment(input.charAt(i+1))) { // trim comments inc(); inc(); c = input.charAt(i); // trim starting whitespace while ( c && isWhitespace(c) ){ c = input.charAt(inc()); } // consume comments while ( c && !isLineEnd(c) ){ s += c; c = input.charAt(inc()); } return make("comment", s); } inc(); } return null; } } function Method(name, args, returnType, description){ this.name = name; this.description = ""; this.args = args || []; this.returnType = returnType; } function MethodArgument(name, type, defaultValue){ this.name = name; this.type = type; this.defaultValue = defaultValue; } function Property(name, type){ this.name = name; this.type = type; } function Typedef(name){ this.name = name; } function Enum(name, fields){ this.name = name; this.fields = fields; } function Interface(name){ this.name = name; this.description = ""; this.methods = []; } function Class(name, visibility){ this.visibility = visibility; this.name = name; this.description = ""; this.methods = []; this.parentClass = undefined; this.interfaces = []; this.properties = []; }
Parse interfaces
docs/parse.js
Parse interfaces
<ide><path>ocs/parse.js <ide> var fs = require('fs') <ide> , path = require('path'); <ide> <del>parse( path.join( __dirname, "../src/verb/geom/NurbsCurve.hx") ); <add>parse( path.join( __dirname, "../src/verb/geom/ISurface.hx") ); <ide> <ide> function parse(srcfn){ <ide> <ide> var input = fs.readFileSync( srcfn, "utf8" ); <del> <add> <ide> var tokenStream = new TokenStream( input ); <ide> var parser = new Parser( tokenStream ); <ide> <ide> return parser.parse(); <ide> } <add> <add>// <add>// An incomplete parser for Haxe that to aid in <add>// constructing documentation <add>// <ide> <ide> function Parser( tokenStream ){ <ide> <ide> var currentToken, lastComment, types = []; <ide> <ide> function tokenMatchesAny( possibleTypes ){ <del> <ide> for(var i = 0; i < possibleTypes.length; i++) { <ide> if ( possibleTypes[i] === currentToken.type){ <ide> return true; <ide> <ide> if ( expectedType && !tokenMatchesAny( Array.prototype.slice.call(arguments) )){ <ide> console.log(tokenStream.neighborhood()); <del> throw new Error("Syntax Error - expectedType \"" + expectedType + "\", but got \"" + currentToken.type + "\""); <add> throw new Error( <add> "Syntax Error - expectedType \"" + Array.prototype.join.call( arguments, ", ") + "\", but got \"" + currentToken.type + "\"" + "\n\n" + <add> tokenStream.neighborhood() + "\n" + <add> " ^ " <add> ); <ide> } <ide> <ide> return currentToken; <ide> } <del> <del> <ide> <ide> function peak(){ <ide> return tokenStream.peak(); <ide> var typeName = consume().contents; <ide> <ide> // build the class type <del> var classDef = new Class( typeName, visibility ); <add> var def = new Class( typeName, visibility ); <ide> <ide> // set the description <ide> if (lastComment){ <del> classDef.description = lastComment <add> def.description = lastComment <ide> <ide> // don't reuse the lastComment <ide> lastComment = undefined; <ide> // parent class <ide> if ( peaked.type === "extends" ){ <ide> <del> classDef.parentClass = parseExtends(); <add> def.parentClass = parseExtends(); <ide> <ide> // look further ahead <ide> peaked = peak(); <ide> <ide> // parse interfaces <ide> if ( peaked.type === "implements" ){ <del> classDef.interfaces = parseImplements(); <del> } <del> <del> parseClassBody( classDef ); <del> <del> // console.log(classDef); <del> <del> return classDef; <add> def.interfaces = parseImplements(); <add> } <add> <add> parseClassBody( def ); <add> <add> console.log(def); <add> <add> return def; <ide> } <ide> <ide> function consumeBlock(){ <ide> var defaultVal; <ide> if (peaked.type === "="){ <ide> consume("="); <del> defaultVal = consume("number", "string", "null").contents; <add> defaultVal = consume("number", "string", "boolean", "null").contents; <ide> } <ide> <ide> return new MethodArgument(name, type, defaultVal); <ide> <ide> var lc = lastComment; <ide> lastComment = undefined; <del> return lc; <add> return lc ? lc.contents : lc; <ide> <ide> } <ide> <ide> return new Method( name, args, type, getLastComment() ); <ide> } <ide> <del> function parseClassMember( classDef, visibility ){ <add> function parseClassMember( def, visibility ){ <ide> <ide> // parse "public" or "private" <ide> var visibility = visibility ? visibility : consume("visibility").contents; <ide> <ide> // hack to ignore private members <ide> if ( visibility === "private"){ <del> classDef = new Class(); <add> def = new Class(); <ide> } <ide> <ide> var peaked = peak(); <ide> } <ide> <ide> if ( peaked.type === "var" ){ <del> return classDef.properties.push( parseProperty( isStatic )); <add> return def.properties.push( parseProperty( isStatic )); <ide> } else if (peaked.type === "function"){ <del> return classDef.properties.push( parseMethod( isStatic )); <del> } <del> <del> throw new Error("Unknown member type encountered" + JSON.stringify( peaked )); <del> } <del> <del> function parseClassBody( classDef ){ <add> return def.methods.push( parseMethod( isStatic )); <add> } <add> <add> throw new Error("Unknown class member encountered" + JSON.stringify( peaked )); <add> } <add> <add> function parseClassBody( def ){ <ide> <ide> consume("{"); <ide> <ide> parseComment(); <ide> continue; <ide> } else if (peaked.type === "visibility"){ <del> parseClassMember( classDef ); <add> parseClassMember( def ); <ide> continue; <ide> } else if (peaked.type === "function"){ <del> parseClassMember( classDef, "private" ); <add> parseClassMember( def, "private" ); <ide> continue; <ide> } else if (peaked.type === "var"){ <del> parseClassMember( classDef, "private" ); <add> parseClassMember( def, "private" ); <ide> continue; <ide> } else if (peaked.type === "static"){ <del> parseClassMember( classDef, "private" ); <add> parseClassMember( def, "private" ); <ide> continue; <ide> } <ide> <ide> } <ide> <ide> consume("}"); <add> } <add> <add> function parseMethodDefinition(){ <add> <add> // function MethodName( methodArgument, methodArgument ) : ExpectedType; <add> consume("function"); <add> <add> var name = consume("id", "new").contents; <add> <add> var args = parseMethodArguments(); <add> <add> peaked = peak(); <add> <add> var type; <add> if (peaked.type === ":"){ <add> type = parseTypeAnnotation(); <add> } <add> <add> consumeUntilInclusive(";"); <add> <add> return new Method( name, args, type, getLastComment() ); <add> } <add> <add> function parseInterfaceMember( def, visibility ){ <add> <add> // parse "public" or "private" <add> var visibility = visibility ? visibility : consume("visibility").contents; <add> <add> // hack to ignore private members <add> if ( visibility === "private"){ <add> def = new Interface(); <add> } <add> <add> var peaked = peak(); <add> <add> if ( peaked.type === "var" ){ <add> return def.properties.push( parseProperty()); <add> } else if (peaked.type === "function"){ <add> return def.methods.push( parseMethodDefinition()); <add> } <add> <add> throw new Error("Unknown interface member type encountered" + JSON.stringify( peaked )); <add> } <add> <add> function parseInterfaceBody( def ){ <add> <add> consume("{"); <add> <add> var peaked; <add> <add> while ( (peaked = peak()) && peaked.type != "}"){ <add> if (peaked.type === "comment"){ <add> parseComment(); <add> continue; <add> } else if (peaked.type === "visibility"){ <add> parseInterfaceMember( def ); <add> continue; <add> } else if (peaked.type === "function"){ <add> parseInterfaceMember( def, "public" ); <add> continue; <add> } <add> <add> consume(); <add> } <add> <add> consume("}"); <add> } <add> <add> function parseInterface( visibility ){ <add> <add> // get visibility from current token or default <add> visibility = visibility || "public"; <add> <add> consume("interface"); <add> <add> // get the type name for the class <add> var typeName = consume().contents; <add> <add> // build the class type <add> var def = new Interface( typeName, visibility ); <add> <add> // set the description <add> def.description = getLastComment(); <add> <add> if ( peak().type === "implements" ){ <add> def.interfaces = parseImplements(); <add> } <add> <add> parseInterfaceBody( def ); <add> <add> console.log( def ); <add> <add> return def; <ide> } <ide> <ide> function parseTypeDefinition(){ <ide> var peaked = peak(); <ide> <ide> if (peaked.contents === "class"){ <del> return parseClass(); <add> return parseClass(); <add> } else if (peaked.contents === "interface"){ <add> return parseInterface(); <ide> } <ide> <ide> throw new Error("Not implemented" + JSON.stringify( peaked )); <ide> <ide> while ( peak().type === "comment" ){ <ide> currentToken = consume(); <del> <add> <ide> squashed.contents += "\n"; <ide> squashed.contents += currentToken.contents; <ide> } <ide> while ( (peaked = peak()) ){ <ide> if (peaked.type === "class"){ <ide> types.push( parseClass() ); <add> } else if (peaked.type === "interface"){ <add> types.push( parseInterface() ); <ide> } else if ( peaked.type === "visibility" ){ <ide> types.push( parseTypeDefinition() ); <ide> } else if (peaked.type === "comment"){ <ide> var isSeparator = (c) => c === ";" || c === "(" || c === ")" || c === "{" || c === "}" || c === "," || c === ":" || c === "="; <ide> var isLineEnd = (c) => c === '\n'; <ide> var isAlpha = (c) => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); <del> var make = (type, contents) => ({ type : type, contents : contents || type, line: line, col: col }); <add> var make = (type, contents) => ({ type : type, contents : contents, line: line, col: col }); <ide> var categorizeId = (s) => { <ide> <ide> if (s === "class"){ <del> return make(s); <add> return make(s,s); <add> } else if (s === "interface") { <add> return make(s,s); <add> } else if (s === "true"){ <add> return make("boolean", s); <add> } else if (s === "true"){ <add> return make("boolean", s); <ide> } else if (s === "private"){ <ide> return make("visibility", s); <ide> } else if (s === "public"){ <ide> return make("visibility", s); <ide> } else if (s === "extends"){ <del> return make(s); <add> return make(s,s); <ide> } else if (s === "implements"){ <del> return make(s); <add> return make(s,s); <ide> } else if (s === "typedef"){ <del> return make(s); <add> return make(s,s); <ide> } else if (s === "function"){ <del> return make(s); <add> return make(s,s); <ide> } else if (s === "static"){ <del> return make(s); <add> return make(s,s); <ide> } else if (s === "new"){ <del> return make(s); <add> return make(s,s); <ide> } else if (s === "null"){ <del> return make(s); <add> return make(s,s); <ide> } else if (s === "var"){ <del> return make(s); <add> return make(s,s); <ide> } <ide> <ide> return make("id", s); <del> <del> } <add> }; <add> <add> var inc = () => { <add> if (!peaking){ <add> col++; <add> <add> if (input.charAt(i) === '\n'){ <add> line++; <add> col = 0; <add> } <add> } <add> i++; <add> return i; <add> }; <ide> <ide> // functions <ide> this.empty = () => i >= input.length; <ide> this.neighborhood = () => { <ide> return input.slice(i-10, i+10); <ide> } <del> <del> var inc = () => { <del> if (!peaking){ <del> col++; <del> <del> if (input.charAt(i) === '\n'){ <del> line++; <del> col = 0; <del> } <del> } <del> i++; <del> return i; <del> }; <del> <ide> this.consume = () => { <ide> <ide> var c = input.charAt(i); <ide> } else if (isComment(c) && isComment(input.charAt(i+1))) { <ide> <ide> // trim comments <del> inc(); inc(); <add> while (isComment(input.charAt(i))){ inc() } <add> <ide> c = input.charAt(i); <del> <del> // trim starting whitespace <del> while ( c && isWhitespace(c) ){ <del> c = input.charAt(inc()); <del> } <ide> <ide> // consume comments <ide> while ( c && !isLineEnd(c) ){ <ide> s += c; <ide> c = input.charAt(inc()); <ide> } <del> <add> <ide> return make("comment", s); <ide> <ide> } <ide> <ide> function Method(name, args, returnType, description){ <ide> this.name = name; <del> this.description = ""; <add> this.description = description || ""; <ide> this.args = args || []; <ide> this.returnType = returnType; <ide> } <ide> this.properties = []; <ide> } <ide> <del>
Java
apache-2.0
7147f2185c6beb5e64cd07373dbc105835a8a2dd
0
lz4/lz4-java,lz4/lz4-java,jpountz/lz4-java,jpountz/lz4-java,jpountz/lz4-java,lz4/lz4-java
package net.jpountz.lz4; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import net.jpountz.util.Native; import net.jpountz.util.Utils; import static net.jpountz.lz4.LZ4Constants.DEFAULT_COMPRESSION_LEVEL; import static net.jpountz.lz4.LZ4Constants.MAX_COMPRESSION_LEVEL; /** * Entry point for the LZ4 API. * <p> * This class has 3 instances<ul> * <li>a {@link #nativeInstance() native} instance which is a JNI binding to * <a href="https://github.com/lz4/lz4">the original LZ4 C implementation</a>. * <li>a {@link #safeInstance() safe Java} instance which is a pure Java port * of the original C library,</li> * <li>an {@link #unsafeInstance() unsafe Java} instance which is a Java port * using the unofficial {@link sun.misc.Unsafe} API. * </ul> * <p> * Only the {@link #safeInstance() safe instance} is guaranteed to work on your * JVM, as a consequence it is advised to use the {@link #fastestInstance()} or * {@link #fastestJavaInstance()} to pull a {@link LZ4Factory} instance. * <p> * All methods from this class are very costly, so you should get an instance * once, and then reuse it whenever possible. This is typically done by storing * a {@link LZ4Factory} instance in a static field. */ public final class LZ4Factory { private static LZ4Factory instance(String impl) { try { return new LZ4Factory(impl); } catch (Exception e) { throw new AssertionError(e); } } private static LZ4Factory NATIVE_INSTANCE, JAVA_UNSAFE_INSTANCE, JAVA_SAFE_INSTANCE; /** * Returns a {@link LZ4Factory} instance that returns compressors and * decompressors that are native bindings to the original C library. * <p> * Please note that this instance has some traps you should be aware of:<ol> * <li>Upon loading this instance, files will be written to the temporary * directory of the system. Although these files are supposed to be deleted * when the JVM exits, they might remain on systems that don't support * removal of files being used such as Windows. * <li>The instance can only be loaded once per JVM. This can be a problem * if your application uses multiple class loaders (such as most servlet * containers): this instance will only be available to the children of the * class loader which has loaded it. As a consequence, it is advised to * either not use this instance in webapps or to put this library in the lib * directory of your servlet container so that it is loaded by the system * class loader. * <li>From lz4-java version 1.6.0, a {@link LZ4FastDecompressor} instance * returned by {@link #fastDecompressor()} of this instance is SLOWER * than a {@link LZ4SafeDecompressor} instance returned by * {@link #safeDecompressor()}, due to a change in the original LZ4 * C implementation. The corresponding C API function is deprecated. * Hence use of {@link #fastDecompressor()} is deprecated * for this instance. * </ol> * * @return a {@link LZ4Factory} instance that returns compressors and * decompressors that are native bindings to the original C library */ public static synchronized LZ4Factory nativeInstance() { if (NATIVE_INSTANCE == null) { NATIVE_INSTANCE = instance("JNI"); } return NATIVE_INSTANCE; } /** * Returns a {@link LZ4Factory} instance that returns compressors and * decompressors that are written with Java's official API. * * @return a {@link LZ4Factory} instance that returns compressors and * decompressors that are written with Java's official API. */ public static synchronized LZ4Factory safeInstance() { if (JAVA_SAFE_INSTANCE == null) { JAVA_SAFE_INSTANCE = instance("JavaSafe"); } return JAVA_SAFE_INSTANCE; } /** * Returns a {@link LZ4Factory} instance that returns compressors and * decompressors that may use {@link sun.misc.Unsafe} to speed up compression * and decompression. * * @return a {@link LZ4Factory} instance that returns compressors and * decompressors that may use {@link sun.misc.Unsafe} to speed up compression * and decompression. */ public static synchronized LZ4Factory unsafeInstance() { if (JAVA_UNSAFE_INSTANCE == null) { JAVA_UNSAFE_INSTANCE = instance("JavaUnsafe"); } return JAVA_UNSAFE_INSTANCE; } /** * Returns the fastest available {@link LZ4Factory} instance which does not * rely on JNI bindings. It first tries to load the * {@link #unsafeInstance() unsafe instance}, and then the * {@link #safeInstance() safe Java instance} if the JVM doesn't have a * working {@link sun.misc.Unsafe}. * * @return the fastest available {@link LZ4Factory} instance which does not * rely on JNI bindings. */ public static LZ4Factory fastestJavaInstance() { if (Utils.isUnalignedAccessAllowed()) { try { return unsafeInstance(); } catch (Throwable t) { return safeInstance(); } } else { return safeInstance(); } } /** * Returns the fastest available {@link LZ4Factory} instance. If the class * loader is the system class loader and if the * {@link #nativeInstance() native instance} loads successfully, then the * {@link #nativeInstance() native instance} is returned, otherwise the * {@link #fastestJavaInstance() fastest Java instance} is returned. * <p> * Please read {@link #nativeInstance() javadocs of nativeInstance()} before * using this method. * * @return the fastest available {@link LZ4Factory} instance */ public static LZ4Factory fastestInstance() { if (Native.isLoaded() || Native.class.getClassLoader() == ClassLoader.getSystemClassLoader()) { try { return nativeInstance(); } catch (Throwable t) { return fastestJavaInstance(); } } else { return fastestJavaInstance(); } } @SuppressWarnings("unchecked") private static <T> T classInstance(String cls) throws NoSuchFieldException, SecurityException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException { ClassLoader loader = LZ4Factory.class.getClassLoader(); loader = loader == null ? ClassLoader.getSystemClassLoader() : loader; final Class<?> c = loader.loadClass(cls); Field f = c.getField("INSTANCE"); return (T) f.get(null); } private final String impl; private final LZ4Compressor fastCompressor; private final LZ4Compressor highCompressor; private final LZ4FastDecompressor fastDecompressor; private final LZ4SafeDecompressor safeDecompressor; private final LZ4Compressor[] highCompressors = new LZ4Compressor[MAX_COMPRESSION_LEVEL+1]; private LZ4Factory(String impl) throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InstantiationException, InvocationTargetException { this.impl = impl; fastCompressor = classInstance("net.jpountz.lz4.LZ4" + impl + "Compressor"); highCompressor = classInstance("net.jpountz.lz4.LZ4HC" + impl + "Compressor"); fastDecompressor = classInstance("net.jpountz.lz4.LZ4" + impl + "FastDecompressor"); safeDecompressor = classInstance("net.jpountz.lz4.LZ4" + impl + "SafeDecompressor"); Constructor<? extends LZ4Compressor> highConstructor = highCompressor.getClass().getDeclaredConstructor(int.class); highCompressors[DEFAULT_COMPRESSION_LEVEL] = highCompressor; for(int level = 1; level <= MAX_COMPRESSION_LEVEL; level++) { if(level == DEFAULT_COMPRESSION_LEVEL) continue; highCompressors[level] = highConstructor.newInstance(level); } // quickly test that everything works as expected final byte[] original = new byte[] {'a','b','c','d',' ',' ',' ',' ',' ',' ','a','b','c','d','e','f','g','h','i','j'}; for (LZ4Compressor compressor : Arrays.asList(fastCompressor, highCompressor)) { final int maxCompressedLength = compressor.maxCompressedLength(original.length); final byte[] compressed = new byte[maxCompressedLength]; final int compressedLength = compressor.compress(original, 0, original.length, compressed, 0, maxCompressedLength); final byte[] restored = new byte[original.length]; fastDecompressor.decompress(compressed, 0, restored, 0, original.length); if (!Arrays.equals(original, restored)) { throw new AssertionError(); } Arrays.fill(restored, (byte) 0); final int decompressedLength = safeDecompressor.decompress(compressed, 0, compressedLength, restored, 0); if (decompressedLength != original.length || !Arrays.equals(original, restored)) { throw new AssertionError(); } } } /** * Returns a blazing fast {@link LZ4Compressor}. * * @return a blazing fast {@link LZ4Compressor} */ public LZ4Compressor fastCompressor() { return fastCompressor; } /** * Returns a {@link LZ4Compressor} which requires more memory than * {@link #fastCompressor()} and is slower but compresses more efficiently. * * @return a {@link LZ4Compressor} which requires more memory than * {@link #fastCompressor()} and is slower but compresses more efficiently. */ public LZ4Compressor highCompressor() { return highCompressor; } /** * Returns a {@link LZ4Compressor} which requires more memory than * {@link #fastCompressor()} and is slower but compresses more efficiently. * The compression level can be customized. * <p>For current implementations, the following is true about compression level:<ol> * <li>It should be in range [1, 17]</li> * <li>A compression level higher than 17 would be treated as 17.</li> * <li>A compression level lower than 1 would be treated as 9.</li> * </ol> * Note that compression levels from different implementations * (native, unsafe Java, and safe Java) cannot be compared with one another. * Specifically, the native implementation of a high compression level * is not necessarily faster than the safe/unsafe Java implementation * of the same compression level. * * @param compressionLevel the compression level between [1, 17]; the higher the level, the higher the compression ratio * @return a {@link LZ4Compressor} which requires more memory than * {@link #fastCompressor()} and is slower but compresses more efficiently. */ public LZ4Compressor highCompressor(int compressionLevel) { if(compressionLevel > MAX_COMPRESSION_LEVEL) { compressionLevel = MAX_COMPRESSION_LEVEL; } else if (compressionLevel < 1) { compressionLevel = DEFAULT_COMPRESSION_LEVEL; } return highCompressors[compressionLevel]; } /** * Returns a {@link LZ4FastDecompressor} instance. * Use of this method is deprecated for the {@link #nativeInstance() native instance}. * * @return a {@link LZ4FastDecompressor} instance * * @see #nativeInstance() */ public LZ4FastDecompressor fastDecompressor() { return fastDecompressor; } /** * Returns a {@link LZ4SafeDecompressor} instance. * * @return a {@link LZ4SafeDecompressor} instance */ public LZ4SafeDecompressor safeDecompressor() { return safeDecompressor; } /** * Returns a {@link LZ4UnknownSizeDecompressor} instance. * @deprecated use {@link #safeDecompressor()} * * @return a {@link LZ4UnknownSizeDecompressor} instance */ public LZ4UnknownSizeDecompressor unknownSizeDecompressor() { return safeDecompressor(); } /** * Returns a {@link LZ4Decompressor} instance. * @deprecated use {@link #fastDecompressor()} * * @return a {@link LZ4Decompressor} instance */ public LZ4Decompressor decompressor() { return fastDecompressor(); } /** * Prints the fastest instance. * * @param args no argument required */ public static void main(String[] args) { System.out.println("Fastest instance is " + fastestInstance()); System.out.println("Fastest Java instance is " + fastestJavaInstance()); } @Override public String toString() { return getClass().getSimpleName() + ":" + impl; } }
src/java/net/jpountz/lz4/LZ4Factory.java
package net.jpountz.lz4; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import net.jpountz.util.Native; import net.jpountz.util.Utils; import static net.jpountz.lz4.LZ4Constants.DEFAULT_COMPRESSION_LEVEL; import static net.jpountz.lz4.LZ4Constants.MAX_COMPRESSION_LEVEL; /** * Entry point for the LZ4 API. * <p> * This class has 3 instances<ul> * <li>a {@link #nativeInstance() native} instance which is a JNI binding to * <a href="https://github.com/lz4/lz4">the original LZ4 C implementation</a>. * <li>a {@link #safeInstance() safe Java} instance which is a pure Java port * of the original C library,</li> * <li>an {@link #unsafeInstance() unsafe Java} instance which is a Java port * using the unofficial {@link sun.misc.Unsafe} API. * </ul> * <p> * Only the {@link #safeInstance() safe instance} is guaranteed to work on your * JVM, as a consequence it is advised to use the {@link #fastestInstance()} or * {@link #fastestJavaInstance()} to pull a {@link LZ4Factory} instance. * <p> * All methods from this class are very costly, so you should get an instance * once, and then reuse it whenever possible. This is typically done by storing * a {@link LZ4Factory} instance in a static field. */ public final class LZ4Factory { private static LZ4Factory instance(String impl) { try { return new LZ4Factory(impl); } catch (Exception e) { throw new AssertionError(e); } } private static LZ4Factory NATIVE_INSTANCE, JAVA_UNSAFE_INSTANCE, JAVA_SAFE_INSTANCE; /** * Returns a {@link LZ4Factory} instance that returns compressors and * decompressors that are native bindings to the original C library. * <p> * Please note that this instance has some traps you should be aware of:<ol> * <li>Upon loading this instance, files will be written to the temporary * directory of the system. Although these files are supposed to be deleted * when the JVM exits, they might remain on systems that don't support * removal of files being used such as Windows. * <li>The instance can only be loaded once per JVM. This can be a problem * if your application uses multiple class loaders (such as most servlet * containers): this instance will only be available to the children of the * class loader which has loaded it. As a consequence, it is advised to * either not use this instance in webapps or to put this library in the lib * directory of your servlet container so that it is loaded by the system * class loader. * <li>From lz4-java version 1.6.0, a {@link LZ4FastDecompressor} instance * returned by {@link #fastDecompressor()} of this instance is SLOWER * than a {@link LZ4SafeDecompressor} instance returned by * {@link #safeDecompressor()}, due to a change in the original LZ4 * C implementation. The corresponding C API function is deprecated. * Hence use of {@link #fastDecompressor()} is deprecated * for this instance. * </ol> * * @return a {@link LZ4Factory} instance that returns compressors and * decompressors that are native bindings to the original C library */ public static synchronized LZ4Factory nativeInstance() { if (NATIVE_INSTANCE == null) { NATIVE_INSTANCE = instance("JNI"); } return NATIVE_INSTANCE; } /** * Returns a {@link LZ4Factory} instance that returns compressors and * decompressors that are written with Java's official API. * * @return a {@link LZ4Factory} instance that returns compressors and * decompressors that are written with Java's official API. */ public static synchronized LZ4Factory safeInstance() { if (JAVA_SAFE_INSTANCE == null) { JAVA_SAFE_INSTANCE = instance("JavaSafe"); } return JAVA_SAFE_INSTANCE; } /** * Returns a {@link LZ4Factory} instance that returns compressors and * decompressors that may use {@link sun.misc.Unsafe} to speed up compression * and decompression. * * @return a {@link LZ4Factory} instance that returns compressors and * decompressors that may use {@link sun.misc.Unsafe} to speed up compression * and decompression. */ public static synchronized LZ4Factory unsafeInstance() { if (JAVA_UNSAFE_INSTANCE == null) { JAVA_UNSAFE_INSTANCE = instance("JavaUnsafe"); } return JAVA_UNSAFE_INSTANCE; } /** * Returns the fastest available {@link LZ4Factory} instance which does not * rely on JNI bindings. It first tries to load the * {@link #unsafeInstance() unsafe instance}, and then the * {@link #safeInstance() safe Java instance} if the JVM doesn't have a * working {@link sun.misc.Unsafe}. * * @return the fastest available {@link LZ4Factory} instance which does not * rely on JNI bindings. */ public static LZ4Factory fastestJavaInstance() { if (Utils.isUnalignedAccessAllowed()) { try { return unsafeInstance(); } catch (Throwable t) { return safeInstance(); } } else { return safeInstance(); } } /** * Returns the fastest available {@link LZ4Factory} instance. If the class * loader is the system class loader and if the * {@link #nativeInstance() native instance} loads successfully, then the * {@link #nativeInstance() native instance} is returned, otherwise the * {@link #fastestJavaInstance() fastest Java instance} is returned. * <p> * Please read {@link #nativeInstance() javadocs of nativeInstance()} before * using this method. * * @return the fastest available {@link LZ4Factory} instance */ public static LZ4Factory fastestInstance() { if (Native.isLoaded() || Native.class.getClassLoader() == ClassLoader.getSystemClassLoader()) { try { return nativeInstance(); } catch (Throwable t) { return fastestJavaInstance(); } } else { return fastestJavaInstance(); } } @SuppressWarnings("unchecked") private static <T> T classInstance(String cls) throws NoSuchFieldException, SecurityException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException { ClassLoader loader = LZ4Factory.class.getClassLoader(); loader = loader == null ? ClassLoader.getSystemClassLoader() : loader; final Class<?> c = loader.loadClass(cls); Field f = c.getField("INSTANCE"); return (T) f.get(null); } private final String impl; private final LZ4Compressor fastCompressor; private final LZ4Compressor highCompressor; private final LZ4FastDecompressor fastDecompressor; private final LZ4SafeDecompressor safeDecompressor; private final LZ4Compressor[] highCompressors = new LZ4Compressor[MAX_COMPRESSION_LEVEL+1]; private LZ4Factory(String impl) throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InstantiationException, InvocationTargetException { this.impl = impl; fastCompressor = classInstance("net.jpountz.lz4.LZ4" + impl + "Compressor"); highCompressor = classInstance("net.jpountz.lz4.LZ4HC" + impl + "Compressor"); fastDecompressor = classInstance("net.jpountz.lz4.LZ4" + impl + "FastDecompressor"); safeDecompressor = classInstance("net.jpountz.lz4.LZ4" + impl + "SafeDecompressor"); Constructor<? extends LZ4Compressor> highConstructor = highCompressor.getClass().getDeclaredConstructor(int.class); highCompressors[DEFAULT_COMPRESSION_LEVEL] = highCompressor; for(int level = 1; level <= MAX_COMPRESSION_LEVEL; level++) { if(level == DEFAULT_COMPRESSION_LEVEL) continue; highCompressors[level] = highConstructor.newInstance(level); } // quickly test that everything works as expected final byte[] original = new byte[] {'a','b','c','d',' ',' ',' ',' ',' ',' ','a','b','c','d','e','f','g','h','i','j'}; for (LZ4Compressor compressor : Arrays.asList(fastCompressor, highCompressor)) { final int maxCompressedLength = compressor.maxCompressedLength(original.length); final byte[] compressed = new byte[maxCompressedLength]; final int compressedLength = compressor.compress(original, 0, original.length, compressed, 0, maxCompressedLength); final byte[] restored = new byte[original.length]; fastDecompressor.decompress(compressed, 0, restored, 0, original.length); if (!Arrays.equals(original, restored)) { throw new AssertionError(); } Arrays.fill(restored, (byte) 0); final int decompressedLength = safeDecompressor.decompress(compressed, 0, compressedLength, restored, 0); if (decompressedLength != original.length || !Arrays.equals(original, restored)) { throw new AssertionError(); } } } /** * Returns a blazing fast {@link LZ4Compressor}. * * @return a blazing fast {@link LZ4Compressor} */ public LZ4Compressor fastCompressor() { return fastCompressor; } /** * Returns a {@link LZ4Compressor} which requires more memory than * {@link #fastCompressor()} and is slower but compresses more efficiently. * * @return a {@link LZ4Compressor} which requires more memory than * {@link #fastCompressor()} and is slower but compresses more efficiently. */ public LZ4Compressor highCompressor() { return highCompressor; } /** * Returns a {@link LZ4Compressor} which requires more memory than * {@link #fastCompressor()} and is slower but compresses more efficiently. * The compression level can be customized. * <p>For current implementations, the following is true about compression level:<ol> * <li>It should be in range [1, 17]</li> * <li>A compression level higher than 17 would be treated as 17.</li> * <li>A compression level lower than 1 would be treated as 9.</li> * </ol> * * @param compressionLevel the compression level between [1, 17]; the higher the level, the higher the compression ratio * @return a {@link LZ4Compressor} which requires more memory than * {@link #fastCompressor()} and is slower but compresses more efficiently. */ public LZ4Compressor highCompressor(int compressionLevel) { if(compressionLevel > MAX_COMPRESSION_LEVEL) { compressionLevel = MAX_COMPRESSION_LEVEL; } else if (compressionLevel < 1) { compressionLevel = DEFAULT_COMPRESSION_LEVEL; } return highCompressors[compressionLevel]; } /** * Returns a {@link LZ4FastDecompressor} instance. * Use of this method is deprecated for the {@link #nativeInstance() native instance}. * * @return a {@link LZ4FastDecompressor} instance * * @see #nativeInstance() */ public LZ4FastDecompressor fastDecompressor() { return fastDecompressor; } /** * Returns a {@link LZ4SafeDecompressor} instance. * * @return a {@link LZ4SafeDecompressor} instance */ public LZ4SafeDecompressor safeDecompressor() { return safeDecompressor; } /** * Returns a {@link LZ4UnknownSizeDecompressor} instance. * @deprecated use {@link #safeDecompressor()} * * @return a {@link LZ4UnknownSizeDecompressor} instance */ public LZ4UnknownSizeDecompressor unknownSizeDecompressor() { return safeDecompressor(); } /** * Returns a {@link LZ4Decompressor} instance. * @deprecated use {@link #fastDecompressor()} * * @return a {@link LZ4Decompressor} instance */ public LZ4Decompressor decompressor() { return fastDecompressor(); } /** * Prints the fastest instance. * * @param args no argument required */ public static void main(String[] args) { System.out.println("Fastest instance is " + fastestInstance()); System.out.println("Fastest Java instance is " + fastestJavaInstance()); } @Override public String toString() { return getClass().getSimpleName() + ":" + impl; } }
Add a comment that a native high compressor is not necessarily faster than the Java high compressor of the same compression level
src/java/net/jpountz/lz4/LZ4Factory.java
Add a comment that a native high compressor is not necessarily faster than the Java high compressor of the same compression level
<ide><path>rc/java/net/jpountz/lz4/LZ4Factory.java <ide> * <li>A compression level higher than 17 would be treated as 17.</li> <ide> * <li>A compression level lower than 1 would be treated as 9.</li> <ide> * </ol> <add> * Note that compression levels from different implementations <add> * (native, unsafe Java, and safe Java) cannot be compared with one another. <add> * Specifically, the native implementation of a high compression level <add> * is not necessarily faster than the safe/unsafe Java implementation <add> * of the same compression level. <ide> * <ide> * @param compressionLevel the compression level between [1, 17]; the higher the level, the higher the compression ratio <ide> * @return a {@link LZ4Compressor} which requires more memory than
Java
apache-2.0
33fd0f11c1d32b4df8693e8220bfcc75a3f9c157
0
ebf/spring-granular-permissions
/** * Copyright 2009-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.ebf.security.guard; import java.util.Collection; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.authentication.InsufficientAuthenticationException; import org.springframework.security.core.Authentication; public class PermissionAccessDecisionManager implements AccessDecisionManager { private static final Logger logger = LoggerFactory.getLogger(PermissionAccessDecisionManager.class); @Override public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { Stream<ConfigAttribute> accessableAttributes = configAttributes.stream().filter(configAttr -> { if (authentication.getAuthorities() == null) { return false; } return authentication.getAuthorities().stream().filter(authority -> { return authority.getAuthority().equals(configAttr.getAttribute()); }).count() == 1; }); if (accessableAttributes.count() == 0) { throw new AccessDeniedException("Insufficient permissions."); } } @Override public boolean supports(ConfigAttribute attribute) { return PermissionSecurityAttribute.class.isAssignableFrom(attribute.getClass()); } @Override public boolean supports(Class<?> clazz) { return true; } }
src/main/java/de/ebf/security/guard/PermissionAccessDecisionManager.java
/** * Copyright 2009-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.ebf.security.guard; import java.util.Collection; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.authentication.InsufficientAuthenticationException; import org.springframework.security.core.Authentication; public class PermissionAccessDecisionManager implements AccessDecisionManager { private static final Logger logger = LoggerFactory.getLogger(PermissionAccessDecisionManager.class); @Override public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { Stream<ConfigAttribute> accessableAttributes = configAttributes.stream().filter(configAttr -> { if (authentication.getAuthorities() == null) { return false; } return authentication.getAuthorities().stream().filter(authority -> { return authority.getAuthority().equals(configAttr.getAttribute()); }).count() == 1; }); if (accessableAttributes.count() == 0) { throw new AccessDeniedException("Insuficient permissions."); } } @Override public boolean supports(ConfigAttribute attribute) { return PermissionSecurityAttribute.class.isAssignableFrom(attribute.getClass()); } @Override public boolean supports(Class<?> clazz) { return true; } }
fix typo
src/main/java/de/ebf/security/guard/PermissionAccessDecisionManager.java
fix typo
<ide><path>rc/main/java/de/ebf/security/guard/PermissionAccessDecisionManager.java <ide> }); <ide> <ide> if (accessableAttributes.count() == 0) { <del> throw new AccessDeniedException("Insuficient permissions."); <add> throw new AccessDeniedException("Insufficient permissions."); <ide> } <ide> <ide> }
Java
mit
0bbf85d373be9faea5f80691ca720b7df40f2f02
0
dacrome/addon-administration,osiam/addon-administration,tkrille/osiam-addon-administration,tkrille/osiam-addon-administration,osiam/addon-administration,tkrille/osiam-addon-administration,thomasdarimont/addon-administration,dacrome/addon-administration,thomasdarimont/addon-administration,thomasdarimont/addon-administration,osiam/addon-administration,dacrome/addon-administration
package org.osiam.addons.administration.controller.user; import javax.inject.Inject; import org.apache.log4j.Logger; import org.osiam.addons.administration.controller.AdminController; import org.osiam.addons.administration.controller.GenericController; import org.osiam.addons.administration.model.command.UpdateUserCommand; import org.osiam.addons.administration.service.UserService; import org.osiam.addons.administration.util.RedirectBuilder; import org.osiam.resources.exception.SCIMDataValidationException; import org.osiam.resources.scim.User; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.validation.Validator; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; /** * Controller for the user edit view. */ @Controller @RequestMapping(EditUserController.CONTROLLER_PATH) public class EditUserController extends GenericController { private static final Logger LOG = Logger.getLogger(EditUserController.class); public static final String CONTROLLER_PATH = AdminController.CONTROLLER_PATH + "/user/edit"; public static final String REQUEST_PARAMETER_ID = "id"; public static final String REQUEST_PARAMETER_ERROR = "error"; private static final String SESSION_KEY_COMMAND = "command"; public static final String MODEL = "model"; @Inject private UserService userService; @Inject private Validator validator; @RequestMapping(method = RequestMethod.GET) public ModelAndView handleUserEdit(@RequestParam(value = REQUEST_PARAMETER_ID) final String id) { ModelAndView modelAndView = new ModelAndView("user/editUser"); clearSession(); User user = userService.getUser(id); modelAndView.addObject(MODEL, new UpdateUserCommand(user)); return modelAndView; } private void clearSession() { removeFromSession(SESSION_KEY_COMMAND); removeBindingResultFromSession(MODEL); } @RequestMapping(method = RequestMethod.GET, params = REQUEST_PARAMETER_ERROR + "=validation") public ModelAndView handleUserEditFailure( @RequestParam(value = REQUEST_PARAMETER_ID) final String id) { ModelAndView modelAndView = new ModelAndView("user/editUser"); modelAndView.addObject(MODEL, restoreFromSession(SESSION_KEY_COMMAND)); enrichBindingResultFromSession(MODEL, modelAndView); return modelAndView; } @RequestMapping(method = RequestMethod.POST) public String handleUserUpdate( @ModelAttribute(MODEL) UpdateUserCommand command, BindingResult bindingResult) { validateCommand(command, bindingResult); final RedirectBuilder redirect = new RedirectBuilder() .setPath(CONTROLLER_PATH) .addParameter(REQUEST_PARAMETER_ID, command.getId()); try { if(!bindingResult.hasErrors()){ User user = userService.getUser(command.getId()); command.setUser(user); userService.replaceUser(command.getId(), command.getAsUser()); redirect.addParameter("saveSuccess", true); redirect.setPath(UserViewController.CONTROLLER_PATH); return redirect.build(); } } catch(SCIMDataValidationException e) { LOG.warn("Could not update user.", e); } storeInSession(SESSION_KEY_COMMAND, command); storeBindingResultIntoSession(bindingResult, MODEL); redirect.addParameter(REQUEST_PARAMETER_ERROR, "validation"); return redirect.build(); } private void validateCommand(UpdateUserCommand command, BindingResult bindingResult) { //we must validate for our own, because we need to purge the command //before we can validate it command.purge(); validator.validate(command, bindingResult); } }
src/main/java/org/osiam/addons/administration/controller/user/EditUserController.java
package org.osiam.addons.administration.controller.user; import javax.inject.Inject; import javax.validation.Valid; import org.apache.log4j.Logger; import org.osiam.addons.administration.controller.AdminController; import org.osiam.addons.administration.controller.GenericController; import org.osiam.addons.administration.model.command.UpdateUserCommand; import org.osiam.addons.administration.service.UserService; import org.osiam.addons.administration.util.RedirectBuilder; import org.osiam.resources.exception.SCIMDataValidationException; import org.osiam.resources.scim.User; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.validation.Validator; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; /** * Controller for the user edit view. */ @Controller @RequestMapping(EditUserController.CONTROLLER_PATH) public class EditUserController extends GenericController { private static final Logger LOG = Logger.getLogger(EditUserController.class); public static final String CONTROLLER_PATH = AdminController.CONTROLLER_PATH + "/user/edit"; public static final String REQUEST_PARAMETER_ID = "id"; public static final String REQUEST_PARAMETER_ERROR = "error"; private static final String SESSION_KEY_COMMAND = "command"; public static final String MODEL = "model"; @Inject private UserService userService; @Inject private Validator validator; @RequestMapping(method = RequestMethod.GET) public ModelAndView handleUserEdit(@RequestParam(value = REQUEST_PARAMETER_ID) final String id) { ModelAndView modelAndView = new ModelAndView("user/editUser"); clearSession(); User user = userService.getUser(id); modelAndView.addObject(MODEL, new UpdateUserCommand(user)); return modelAndView; } private void clearSession() { removeFromSession(SESSION_KEY_COMMAND); removeBindingResultFromSession(MODEL); } @RequestMapping(method = RequestMethod.GET, params = REQUEST_PARAMETER_ERROR + "=validation") public ModelAndView handleUserEditFailure( @RequestParam(value = REQUEST_PARAMETER_ID) final String id) { ModelAndView modelAndView = new ModelAndView("user/editUser"); modelAndView.addObject(MODEL, restoreFromSession(SESSION_KEY_COMMAND)); enrichBindingResultFromSession(MODEL, modelAndView); return modelAndView; } @RequestMapping(method = RequestMethod.POST) public String handleUserUpdate( @Valid @ModelAttribute(MODEL) UpdateUserCommand command, BindingResult bindingResult) { final RedirectBuilder redirect = new RedirectBuilder() .setPath(CONTROLLER_PATH) .addParameter(REQUEST_PARAMETER_ID, command.getId()); try { if(!bindingResult.hasErrors()){ User user = userService.getUser(command.getId()); command.setUser(user); userService.replaceUser(command.getId(), command.getAsUser()); redirect.addParameter("saveSuccess", true); redirect.setPath(UserViewController.CONTROLLER_PATH); return redirect.build(); } } catch(SCIMDataValidationException e) { LOG.warn("Could not update user.", e); } storeInSession(SESSION_KEY_COMMAND, command); storeBindingResultIntoSession(bindingResult, MODEL); redirect.addParameter(REQUEST_PARAMETER_ERROR, "validation"); return redirect.build(); } private void validateCommand(UpdateUserCommand command, BindingResult bindingResult) { //we must validate for our own, because we need to purge the command //before we can validate it command.purge(); validator.validate(command, bindingResult); } }
trigger the validation manually
src/main/java/org/osiam/addons/administration/controller/user/EditUserController.java
trigger the validation manually
<ide><path>rc/main/java/org/osiam/addons/administration/controller/user/EditUserController.java <ide> package org.osiam.addons.administration.controller.user; <ide> <ide> import javax.inject.Inject; <del>import javax.validation.Valid; <ide> <ide> import org.apache.log4j.Logger; <ide> import org.osiam.addons.administration.controller.AdminController; <ide> <ide> @RequestMapping(method = RequestMethod.POST) <ide> public String handleUserUpdate( <del> @Valid @ModelAttribute(MODEL) UpdateUserCommand command, <add> @ModelAttribute(MODEL) UpdateUserCommand command, <ide> BindingResult bindingResult) { <add> <add> validateCommand(command, bindingResult); <ide> <ide> final RedirectBuilder redirect = new RedirectBuilder() <ide> .setPath(CONTROLLER_PATH)
Java
apache-2.0
a830ab9a59c556a7a35433511ad3b07711536543
0
curious-attempt-bunny/rabbit-http-proxy-fake-desktop-headers,toonetown/rabbit-maven
package rabbit.io; import java.nio.ByteBuffer; /** A handle to a ByteBuffer that uses a buffer handler * * @author <a href="mailto:[email protected]">Robert Olofsson</a> */ public class CacheBufferHandle implements BufferHandle { private final BufferHandler bh; private ByteBuffer buffer; private boolean mayBeFlushed = true; /** Create a new CacheBufferHandle that uses the given BufferHandler * for the caching of the ByteBuffer:s * @param bh the BufferHandler that is the actual cache */ public CacheBufferHandle (BufferHandler bh) { this.bh = bh; } public synchronized boolean isEmpty () { return buffer == null || !buffer.hasRemaining (); } public synchronized ByteBuffer getBuffer () { if (buffer == null) buffer = bh.getBuffer (); return buffer; } public synchronized ByteBuffer getLargeBuffer () { buffer = bh.growBuffer (buffer); return buffer; } public boolean isLarge (ByteBuffer buffer) { return bh.isLarge (buffer); } public synchronized void possiblyFlush () { if (!mayBeFlushed) throw new IllegalStateException ("buffer may not be flushed!: " + System.identityHashCode (buffer)); if (buffer == null) return; if (!buffer.hasRemaining ()) { bh.putBuffer (buffer); buffer = null; } } public synchronized void setMayBeFlushed (boolean mayBeFlushed) { this.mayBeFlushed = mayBeFlushed; } @Override public String toString () { return getClass ().getName () + "[buffer: " + buffer + ", bh: " + bh + "}"; } }
src/rabbit/io/CacheBufferHandle.java
package rabbit.io; import java.nio.ByteBuffer; /** A handle to a ByteBuffer that uses a buffer handler * * @author <a href="mailto:[email protected]">Robert Olofsson</a> */ public class CacheBufferHandle implements BufferHandle { private final BufferHandler bh; private ByteBuffer buffer; private boolean mayBeFlushed = true; /** Create a new CacheBufferHandle that uses the given BufferHandler * for the caching of the ByteBuffer:s * @param bh the BufferHandler that is the actual cache */ public CacheBufferHandle (BufferHandler bh) { this.bh = bh; } public boolean isEmpty () { return buffer == null || !buffer.hasRemaining (); } public ByteBuffer getBuffer () { if (buffer == null) buffer = bh.getBuffer (); return buffer; } public ByteBuffer getLargeBuffer () { buffer = bh.growBuffer (buffer); return buffer; } public boolean isLarge (ByteBuffer buffer) { return bh.isLarge (buffer); } public void possiblyFlush () { if (!mayBeFlushed) throw new IllegalStateException ("buffer may not be flushed!: " + System.identityHashCode (buffer)); if (buffer == null) return; if (!buffer.hasRemaining ()) { bh.putBuffer (buffer); buffer = null; } } public void setMayBeFlushed (boolean mayBeFlushed) { this.mayBeFlushed = mayBeFlushed; } @Override public String toString () { return getClass ().getName () + "[buffer: " + buffer + ", bh: " + bh + "}"; } }
Synchronize access to the buffer.
src/rabbit/io/CacheBufferHandle.java
Synchronize access to the buffer.
<ide><path>rc/rabbit/io/CacheBufferHandle.java <ide> this.bh = bh; <ide> } <ide> <del> public boolean isEmpty () { <add> public synchronized boolean isEmpty () { <ide> return buffer == null || !buffer.hasRemaining (); <ide> } <ide> <del> public ByteBuffer getBuffer () { <add> public synchronized ByteBuffer getBuffer () { <ide> if (buffer == null) <ide> buffer = bh.getBuffer (); <ide> return buffer; <ide> } <ide> <del> public ByteBuffer getLargeBuffer () { <add> public synchronized ByteBuffer getLargeBuffer () { <ide> buffer = bh.growBuffer (buffer); <ide> return buffer; <ide> } <ide> return bh.isLarge (buffer); <ide> } <ide> <del> public void possiblyFlush () { <add> public synchronized void possiblyFlush () { <ide> if (!mayBeFlushed) <ide> throw new IllegalStateException ("buffer may not be flushed!: " + <ide> System.identityHashCode (buffer)); <ide> } <ide> } <ide> <del> public void setMayBeFlushed (boolean mayBeFlushed) { <add> public synchronized void setMayBeFlushed (boolean mayBeFlushed) { <ide> this.mayBeFlushed = mayBeFlushed; <ide> } <ide>
JavaScript
mit
7ff67ae36a7b12f4c5601a7e0a7227d1ec098f32
0
julianxhokaxhiu/mockups-creator,julianxhokaxhiu/mockups-creator
/* The MIT License (MIT) Copyright (c) 2014 Julian Xhokaxhiu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ module.exports = function(grunt) { // Load Tasks require('load-grunt-tasks')(grunt); // Configure the tasks grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), app: grunt.file.readJSON('app.json'), cssMin: 'css/<%= pkg.name %>.min.<%= getCurrentDate() %>.css', cssPrintMin: 'css/<%= pkg.name %>.min.<%= getCurrentDate() %>.print.css', jsMin: 'js/<%= pkg.name %>.min.<%= getCurrentDate() %>.js', getCurrentDate: function() { var date = new Date(); return date.getDate() + '-' + ( date.getMonth() + 1 ) + '-' + date.getFullYear(); }, clean: { options: { force: true }, output: [ '<%= app.config.output.path %>/*', 'tpl/scss/_<%= pkg.name %>-icons.scss' ], cssFiles: [ 'tpl/css/99_<%= pkg.name %>.css', 'tpl/css-print/99_<%= pkg.name %>.css' ], mapFiles: [ 'tpl/css/*.map', 'tpl/css/*.map', ], webfonts: [ 'webfonts/' ], webicons: [ 'webicons/' ] }, tasty_swig: { build: { options: { context: { app: { name: '<%= pkg.name %>', liveReloadHost: '<%= app.config.livereload.host %>:<%= app.config.livereload.port %>', cssFiles: { 'screen': grunt.file.expand({ filter: 'isFile', cwd: 'tpl/' }, 'css/**/*.css'), 'print': grunt.file.expand({ filter: 'isFile', cwd: 'tpl/' }, 'css-print/**/*.css') }, jsFiles: [ '<%= jsMin %>' ], data: '<%= app.data %>' } } }, src: [ 'tpl/*.swig' ], dest: '<%= app.config.output.path %>/' }, deploy: { options: { context: { app: { name: '<%= pkg.name %>', liveReloadHost: false, cssFiles: { 'screen': [ '<%= cssMin %>' ], 'print': [ '<%= cssPrintMin %>' ] }, jsFiles: [ '<%= jsMin %>' ], data: '<%= app.data %>' } } }, src: [ 'tpl/*.swig' ], dest: '<%= app.config.output.path %>/' } }, sass: { options: { style: 'compressed' }, build: { files: { 'tpl/css/99_<%= pkg.name %>.css' : [ 'tpl/scss/screen.scss' ], 'tpl/css-print/99_<%= pkg.name %>.css' : [ 'tpl/scss/print.scss' ] } } }, fontgen: { build: { options: { path_prefix: '../fonts/' }, files: { 'webfonts/' : [ 'fonts/*.otf', 'fonts/*.ttf' ] } } }, webfont: { icons: { src: 'icons/*.svg', dest: 'webicons/', destCss: 'tpl/scss/', options: { template: 'tpl/icons.css', relativeFontPath: '../fonts/', font: '<%= pkg.name %>-icons', stylesheet: 'scss', htmlDemo: false, templateOptions: { baseClass: '<%= pkg.name %>-icon', classPrefix: '<%= pkg.name %>-icon-', mixinPrefix: '<%= pkg.name %>-icon-' } } } }, concat: { webfonts: { files: { 'tpl/css/98_webfonts.css' : [ 'webfonts/*.css' ], 'tpl/css-print/98_webfonts.css' : [ 'webfonts/*.css' ] } }, css: { filter: 'isFile', src: 'tpl/css/**/*.css', dest: '<%= app.config.output.path %>/<%= cssMin %>' }, cssPrint: { filter: 'isFile', src: 'tpl/css-print/**/*.css', dest: '<%= app.config.output.path %>/<%= cssPrintMin %>' }, js: { files: { '<%= app.config.output.path %>/<%= jsMin %>' : '<%= app.assets.js %>' } } }, autoprefixer: { options: { browsers: [ "Android 2.3", "Android >= 4", "Chrome >= 20", "Firefox >= 24", "Explorer >= 8", "iOS >= 6", "Opera >= 12", "Safari >= 6" ] }, build: { options: { map: true }, src: '<%= app.config.output.path %>/css/*.css' }, deploy: { options: { map: false }, src: '<%= app.config.output.path %>/css/*.css' } }, cssmin: { build: { files: { '<%= app.config.output.path %>/<%= cssMin %>' : [ '<%= app.config.output.path %>/<%= cssMin %>' ], '<%= app.config.output.path %>/<%= cssPrintMin %>' : [ '<%= app.config.output.path %>/<%= cssPrintMin %>' ] } } }, closurecompiler: { build: { files: { '<%= app.config.output.path %>/<%= jsMin %>': '<%= app.assets.js %>' }, options: { // Any options supported by Closure Compiler, for example: "compilation_level": "SIMPLE_OPTIMIZATIONS", // Plus a simultaneous processes limit "max_processes": 5, } } }, copy: { build: { files: [ // The project CSS and JS files { expand: true, cwd: 'tpl/', src: [ 'css/**/*.css', 'css-print/**/*.css', 'css/**/*.map', 'css-print/**/*.map', 'js/**/*.js' ], dest: '<%= app.config.output.path %>/' } ] }, deploy: { files: [ // External Packages Fonts { expand: true, flatten: true, src: '<%= app.assets.fonts %>', dest: '<%= app.config.output.path %>/fonts/' }, // The project Webfonts { expand: true, flatten: true, cwd: 'webfonts/', src: ['**/*.{ttf,woff,eot,svg,otf}'], dest: '<%= app.config.output.path %>/fonts/' }, // The project Webicons { expand: true, flatten: true, cwd: 'webicons/', src: ['**/*.{ttf,woff,eot,svg,otf}'], dest: '<%= app.config.output.path %>/fonts/' }, // Webicons sass generated file { expand: true, cwd: 'webicons/', src: [ '*.scss' ], dest: 'tpl/scss/' }, // The project resource files { expand: true, cwd: 'rsc/', src: ['**'], dest: '<%= app.config.output.path %>/' } ] }, typo3: { files: [ // Icons { expand: true, flatten: true, cwd: 'icons/', src: [ '*.svg' ], dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/Icons/' }, // Fonts { expand: true, flatten: true, cwd: 'fonts/', src: [ '*' ], dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/Fonts/' }, // Images { expand: true, cwd: 'rsc/img', src: [ '**/*' ], dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/Images/' }, // HTML { expand: true, flatten: true, cwd: '<%= app.config.output.path %>/', src: ['*.html'], dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/Templates/Html/' }, // SCSS { expand: true, flatten: true, cwd: 'tpl/scss/', src: ['*.scss'], dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/Scss/' }, // Javascript { expand: true, flatten: true, cwd: 'tpl/js/', src: ['*.js'], dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/JavaScript/' }, // Bower + App configuration { expand: true, flatten: true, src: [ 'app.json', 'bower.json' ], dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/' }, /// Typo3 related stuff { expand: true, flatten: true, dot: true, cwd: '_typo3/', src: [ '*' ], dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/' } ] } }, watch: { options: { livereload: '<%= app.config.livereload.port %>' }, html: { files: [ 'tpl/**/*.swig', 'app.json' ], tasks: [ 'rebuild:html' ] }, css: { files: [ 'tpl/**/*.scss', ], tasks: [ 'rebuild:css' ] }, js: { files: [ 'tpl/**/*.js' ], tasks: [ 'rebuild:js' ] } }, rsync: { options: { recursive: true, deleteAll: true }, deploy: { options: { src: '<%= app.config.output.path %>/', dest: '<%= app.config.deploy.path %>', host: '<%= app.config.deploy.host %>' } } }, connect: { build: { options: { port: '<%= app.config.server.port %>', hostname: '*', base: '<%= app.config.output.path %>/' } } } }); grunt.registerTask('default', 'Gruntfile for Mockups', function() { grunt.warn('No task name specified.\n\nAvailable tasks: build, deploy, server, typo3"\n\n'); }); grunt.registerTask('server', 'Serve an already built mockup', [ 'connect:build:keepalive' ]); grunt.registerTask('build', 'Build a mockup and watch for file modifications', [ 'rebuild', 'watch' ]); grunt.registerTask('rebuild', 'Build a mockup without watching for file modifications', function ( watchTask ) { var tasks = []; if ( watchTask === undefined ) watchTask = 'all'; if ( watchTask == 'all' ) { tasks = tasks.concat([ 'clean', 'fontgen', 'webfont', 'concat:webfonts', 'sass', 'concat:js', 'tasty_swig:build', 'copy:deploy', 'copy:build', 'autoprefixer:build', 'clean:mapFiles', 'clean:webfonts', 'clean:webicons' ]); if ( grunt.config.get('app').config.server.port > -1 ) tasks = tasks.concat([ 'connect:build' ]); } else if ( watchTask == 'html' ) { tasks = tasks.concat([ 'tasty_swig:build', 'copy:deploy', 'copy:build' ]); } else if ( watchTask == 'css' ) { tasks = tasks.concat([ 'clean:cssFiles', 'sass', 'copy:deploy', 'copy:build', 'autoprefixer:build' ]); } else if ( watchTask == 'js' ) { tasks = tasks.concat([ 'concat:js', 'copy:deploy', 'copy:build' ]); } grunt.task.run(tasks); }); grunt.registerTask('build_deploy', 'Build a mockup ready for deployment sync', [ 'clean', 'fontgen', 'webfont', 'concat:webfonts', 'sass', 'concat:css', 'concat:cssPrint', 'cssmin', 'closurecompiler', 'tasty_swig:deploy', 'copy:deploy', 'autoprefixer:deploy', 'clean:mapFiles', 'clean:webfonts', 'clean:webicons' ]); grunt.registerTask('deploy', 'Deploy a mockup to the Mockups Server', [ 'build_deploy', 'rsync:deploy' ]); grunt.registerTask('typo3', 'Create a TYPO3 extension based on the current output of the mockup', [ 'build_deploy', 'copy:typo3' ]) };
_apptpl/Gruntfile.js
/* The MIT License (MIT) Copyright (c) 2014 Julian Xhokaxhiu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ module.exports = function(grunt) { // Load Tasks require('load-grunt-tasks')(grunt); // Configure the tasks grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), app: grunt.file.readJSON('app.json'), cssMin: 'css/<%= pkg.name %>.min.<%= getCurrentDate() %>.css', cssPrintMin: 'css/<%= pkg.name %>.min.<%= getCurrentDate() %>.print.css', jsMin: 'js/<%= pkg.name %>.min.<%= getCurrentDate() %>.js', getCurrentDate: function() { var date = new Date(); return date.getDate() + '-' + ( date.getMonth() + 1 ) + '-' + date.getFullYear(); }, clean: { options: { force: true }, output: [ '<%= app.config.output.path %>/*', 'tpl/scss/_<%= pkg.name %>-icons.scss' ], cssFiles: [ 'tpl/css/99_<%= pkg.name %>.css', 'tpl/css-print/99_<%= pkg.name %>.css' ], mapFiles: [ 'tpl/css/*.map', 'tpl/css/*.map', ], webfonts: [ 'webfonts/' ], webicons: [ 'webicons/' ] }, tasty_swig: { build: { options: { context: { app: { name: '<%= pkg.name %>', liveReloadHost: '<%= app.config.livereload.host %>:<%= app.config.livereload.port %>', cssFiles: { 'screen': grunt.file.expand({ filter: 'isFile', cwd: 'tpl/' }, 'css/**/*.css'), 'print': grunt.file.expand({ filter: 'isFile', cwd: 'tpl/' }, 'css-print/**/*.css') }, jsFiles: [ '<%= jsMin %>' ], data: '<%= app.data %>' } } }, src: [ 'tpl/*.swig' ], dest: '<%= app.config.output.path %>/' }, deploy: { options: { context: { app: { name: '<%= pkg.name %>', liveReloadHost: false, cssFiles: { 'screen': [ '<%= cssMin %>' ], 'print': [ '<%= cssPrintMin %>' ] }, jsFiles: [ '<%= jsMin %>' ], data: '<%= app.data %>' } } }, src: [ 'tpl/*.swig' ], dest: '<%= app.config.output.path %>/' } }, sass: { options: { style: 'compressed' }, build: { files: { 'tpl/css/99_<%= pkg.name %>.css' : [ 'tpl/scss/screen.scss' ], 'tpl/css-print/99_<%= pkg.name %>.css' : [ 'tpl/scss/print.scss' ] } } }, fontgen: { build: { options: { path_prefix: '../fonts/' }, files: { 'webfonts/' : [ 'fonts/*.otf', 'fonts/*.ttf' ] } } }, webfont: { icons: { src: 'icons/*.svg', dest: 'webicons/', destCss: 'tpl/scss/', options: { template: 'tpl/icons.css', relativeFontPath: '../fonts/', font: '<%= pkg.name %>-icons', stylesheet: 'scss', htmlDemo: false, templateOptions: { baseClass: '<%= pkg.name %>-icon', classPrefix: '<%= pkg.name %>-icon-', mixinPrefix: '<%= pkg.name %>-icon-' } } } }, concat: { webfonts: { files: { 'tpl/css/98_webfonts.css' : [ 'webfonts/*.css' ], 'tpl/css-print/98_webfonts.css' : [ 'webfonts/*.css' ] } }, css: { filter: 'isFile', src: 'tpl/css/**/*.css', dest: '<%= app.config.output.path %>/<%= cssMin %>' }, cssPrint: { filter: 'isFile', src: 'tpl/css-print/**/*.css', dest: '<%= app.config.output.path %>/<%= cssPrintMin %>' }, js: { files: { '<%= app.config.output.path %>/<%= jsMin %>' : '<%= app.assets.js %>' } } }, autoprefixer: { options: { browsers: ['last 3 versions', 'bb 10', 'android 3'] }, build: { options: { map: true }, src: '<%= app.config.output.path %>/css/*.css' }, deploy: { options: { map: false }, src: '<%= app.config.output.path %>/css/*.css' } }, cssmin: { build: { files: { '<%= app.config.output.path %>/<%= cssMin %>' : [ '<%= app.config.output.path %>/<%= cssMin %>' ], '<%= app.config.output.path %>/<%= cssPrintMin %>' : [ '<%= app.config.output.path %>/<%= cssPrintMin %>' ] } } }, closurecompiler: { build: { files: { '<%= app.config.output.path %>/<%= jsMin %>': '<%= app.assets.js %>' }, options: { // Any options supported by Closure Compiler, for example: "compilation_level": "SIMPLE_OPTIMIZATIONS", // Plus a simultaneous processes limit "max_processes": 5, } } }, copy: { build: { files: [ // The project CSS and JS files { expand: true, cwd: 'tpl/', src: [ 'css/**/*.css', 'css-print/**/*.css', 'css/**/*.map', 'css-print/**/*.map', 'js/**/*.js' ], dest: '<%= app.config.output.path %>/' } ] }, deploy: { files: [ // External Packages Fonts { expand: true, flatten: true, src: '<%= app.assets.fonts %>', dest: '<%= app.config.output.path %>/fonts/' }, // The project Webfonts { expand: true, flatten: true, cwd: 'webfonts/', src: ['**/*.{ttf,woff,eot,svg,otf}'], dest: '<%= app.config.output.path %>/fonts/' }, // The project Webicons { expand: true, flatten: true, cwd: 'webicons/', src: ['**/*.{ttf,woff,eot,svg,otf}'], dest: '<%= app.config.output.path %>/fonts/' }, // Webicons sass generated file { expand: true, cwd: 'webicons/', src: [ '*.scss' ], dest: 'tpl/scss/' }, // The project resource files { expand: true, cwd: 'rsc/', src: ['**'], dest: '<%= app.config.output.path %>/' } ] }, typo3: { files: [ // Icons { expand: true, flatten: true, cwd: 'icons/', src: [ '*.svg' ], dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/Icons/' }, // Fonts { expand: true, flatten: true, cwd: 'fonts/', src: [ '*' ], dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/Fonts/' }, // Images { expand: true, cwd: 'rsc/img', src: [ '**/*' ], dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/Images/' }, // HTML { expand: true, flatten: true, cwd: '<%= app.config.output.path %>/', src: ['*.html'], dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/Templates/Html/' }, // SCSS { expand: true, flatten: true, cwd: 'tpl/scss/', src: ['*.scss'], dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/Scss/' }, // Javascript { expand: true, flatten: true, cwd: 'tpl/js/', src: ['*.js'], dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/JavaScript/' }, // Bower + App configuration { expand: true, flatten: true, src: [ 'app.json', 'bower.json' ], dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/' }, /// Typo3 related stuff { expand: true, flatten: true, dot: true, cwd: '_typo3/', src: [ '*' ], dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/' } ] } }, watch: { options: { livereload: '<%= app.config.livereload.port %>' }, html: { files: [ 'tpl/**/*.swig', 'app.json' ], tasks: [ 'rebuild:html' ] }, css: { files: [ 'tpl/**/*.scss', ], tasks: [ 'rebuild:css' ] }, js: { files: [ 'tpl/**/*.js' ], tasks: [ 'rebuild:js' ] } }, rsync: { options: { recursive: true, deleteAll: true }, deploy: { options: { src: '<%= app.config.output.path %>/', dest: '<%= app.config.deploy.path %>', host: '<%= app.config.deploy.host %>' } } }, connect: { build: { options: { port: '<%= app.config.server.port %>', hostname: '*', base: '<%= app.config.output.path %>/' } } } }); grunt.registerTask('default', 'Gruntfile for Mockups', function() { grunt.warn('No task name specified.\n\nAvailable tasks: build, deploy, server, typo3"\n\n'); }); grunt.registerTask('server', 'Serve an already built mockup', [ 'connect:build:keepalive' ]); grunt.registerTask('build', 'Build a mockup and watch for file modifications', [ 'rebuild', 'watch' ]); grunt.registerTask('rebuild', 'Build a mockup without watching for file modifications', function ( watchTask ) { var tasks = []; if ( watchTask === undefined ) watchTask = 'all'; if ( watchTask == 'all' ) { tasks = tasks.concat([ 'clean', 'fontgen', 'webfont', 'concat:webfonts', 'sass', 'concat:js', 'tasty_swig:build', 'copy:deploy', 'copy:build', 'autoprefixer:build', 'clean:mapFiles', 'clean:webfonts', 'clean:webicons' ]); if ( grunt.config.get('app').config.server.port > -1 ) tasks = tasks.concat([ 'connect:build' ]); } else if ( watchTask == 'html' ) { tasks = tasks.concat([ 'tasty_swig:build', 'copy:deploy', 'copy:build' ]); } else if ( watchTask == 'css' ) { tasks = tasks.concat([ 'clean:cssFiles', 'sass', 'copy:deploy', 'copy:build', 'autoprefixer:build' ]); } else if ( watchTask == 'js' ) { tasks = tasks.concat([ 'concat:js', 'copy:deploy', 'copy:build' ]); } grunt.task.run(tasks); }); grunt.registerTask('build_deploy', 'Build a mockup ready for deployment sync', [ 'clean', 'fontgen', 'webfont', 'concat:webfonts', 'sass', 'concat:css', 'concat:cssPrint', 'cssmin', 'closurecompiler', 'tasty_swig:deploy', 'copy:deploy', 'autoprefixer:deploy', 'clean:mapFiles', 'clean:webfonts', 'clean:webicons' ]); grunt.registerTask('deploy', 'Deploy a mockup to the Mockups Server', [ 'build_deploy', 'rsync:deploy' ]); grunt.registerTask('typo3', 'Create a TYPO3 extension based on the current output of the mockup', [ 'build_deploy', 'copy:typo3' ]) };
Use official Bootstrap autoprefixing rules See https://github.com/twbs/bootstrap/blob/master/grunt/configBridge.json#L20
_apptpl/Gruntfile.js
Use official Bootstrap autoprefixing rules
<ide><path>apptpl/Gruntfile.js <ide> }, <ide> autoprefixer: { <ide> options: { <del> browsers: ['last 3 versions', 'bb 10', 'android 3'] <add> browsers: [ <add> "Android 2.3", <add> "Android >= 4", <add> "Chrome >= 20", <add> "Firefox >= 24", <add> "Explorer >= 8", <add> "iOS >= 6", <add> "Opera >= 12", <add> "Safari >= 6" <add> ] <ide> }, <ide> build: { <ide> options: {
Java
mit
80d04fceb1076f09c7653e328d92acb8a021d3a6
0
eqlbin/Simple-IP-Utils
// Copyright (c) 2016 Nikita Shpak aka eqlbin // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package ru.eqlbin.utils.net.ipv4; /** * * A set of static methods for working with subnets. * * @author Nikita Shpak aka eqlbin * */ public class IPv4SubnetUtils { public static final int MAX_PREFIX_LENGTH = 32; public static final int MIN_PREFIX_LENGTH = 1; /** * Converts an integer representation of the subnet mask in * the length of the routing prefix in bits (CIDR notation). * * @param subnet mask an integer representation of the subnet mask * @return the length of the routing prefix in bits */ public static int subnetMaskToPrefixLength(int subnetMask){ int prefixLength = Integer.bitCount(subnetMask); if(prefixLengthToSubnetMask(prefixLength) != subnetMask) throw new InvalidSubnetMaskException("'"+IPv4Utils.asString(subnetMask)+"'"); return Integer.bitCount(subnetMask); } /** * Converts the length of the routing prefix in bits (CIDR notation) in * an integer representation of the subnet mask. * * @param routingPrefixLength the length of the routing prefix in bits * @return an integer representation of the subnet mask */ public static int prefixLengthToSubnetMask(int routingPrefixLength){ if(routingPrefixLength < MIN_PREFIX_LENGTH || routingPrefixLength > MAX_PREFIX_LENGTH) throw new IllegalArgumentException( "Incorrect routing prefix length: " + routingPrefixLength + ". It must be between " + MIN_PREFIX_LENGTH +" and " + MAX_PREFIX_LENGTH + " (both inclusive)"); int val = 0; int shift = MAX_PREFIX_LENGTH; while(shift-- > MAX_PREFIX_LENGTH - routingPrefixLength){ val = val | 1 << shift; } return val; } /** * Calculates the count of IP addresses per subnet for the given subnet mask. * * @param subnet mask an integer representation of the subnet mask * @return the count of IP addresses per subnet */ public static long addressPerSubnetCount(int subnetMask){ return (long)(Math.pow(2, 32 - subnetMaskToPrefixLength(subnetMask)) - 2); } /** * Calculates the count of subnets for the given subnet mask. * * @param subnet mask an integer representation of the subnet mask * @return the count of subnets */ public static long subnetCount(int subnetMask){ return (long)(Math.pow(2, subnetMaskToPrefixLength(subnetMask) % 8)); } /** * Calculates the network (routing prefix) for the given IP * address and subnet mask. * * @param ip an integer representation of the IP address * @param subnet mask an integer representation of the subnet mask * @return integer an representation of the network */ public static int network(int ip, int subnetMask){ return ip & subnetMask; } /** * Calculates the broadcast address for given IP address or network and the subnet mask * * @param ip an integer representation of the IP address * @param subnet mask an integer representation of the subnet mask * @return an integer representation of the broadcast address */ public static int brodcast(int ip, int subnetMask){ return ip | ~subnetMask; } /** * Checks whether the given IP address in the range of IP addresses * for subnet calculated by given network and subnet mask. * Network and broadcast addresses are excluded. * * @param ip an integer representation of the IP address * @param network an integer representation of the network (routing prefix) * @param subnet mask an integer representation of the subnet mask * @return true if IP in range and false in otherwise */ public static boolean isInRange(int ip, int network, int subnetMask){ return ip >= network && ip <= brodcast(network, subnetMask); } }
src/ru/eqlbin/utils/net/ipv4/IPv4SubnetUtils.java
// Copyright (c) 2016 Nikita Shpak aka eqlbin // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package ru.eqlbin.utils.net.ipv4; /** * * A set of static methods for working with subnets. * * @author Nikita Shpak aka eqlbin * */ public class IPv4SubnetUtils { public static final int MAX_PREFIX_LENGTH = 32; public static final int MIN_PREFIX_LENGTH = 1; /** * Converts an integer representation of the subnet mask in * the length of the routing prefix in bits (CIDR notation). * * @param subnet mask an integer representation of the subnet mask * @return the length of the routing prefix in bits */ public static int subnetMaskToPrefixLength(int subnetMask){ int prefixLength = Integer.bitCount(subnetMask); if(prefixLengthToSubnetMask(prefixLength) != subnetMask) throw new InvalidSubnetMaskException("'"+IPv4Utils.asString(subnetMask)+"'"); return Integer.bitCount(subnetMask); } /** * Converts the length of the routing prefix in bits (CIDR notation) in * an integer representation of the subnet mask. * * @param routingPrefixLength the length of the routing prefix in bits * @return an integer representation of the subnet mask */ public static int prefixLengthToSubnetMask(int routingPrefixLength){ if(routingPrefixLength < MIN_PREFIX_LENGTH || routingPrefixLength > MAX_PREFIX_LENGTH) throw new IllegalArgumentException( "Incorrect routing prefix length: " + routingPrefixLength + ". It must be between " + MIN_PREFIX_LENGTH +" and " + MAX_PREFIX_LENGTH + " (inclusive)"); int val = 0; int shift = MAX_PREFIX_LENGTH; while(shift-- > MAX_PREFIX_LENGTH - routingPrefixLength){ val = val | 1 << shift; } return val; } /** * Calculates the count of IP addresses per subnet for the given subnet mask. * * @param subnet mask an integer representation of the subnet mask * @return the count of IP addresses per subnet */ public static long addressPerSubnetCount(int subnetMask){ return (long)(Math.pow(2, 32 - subnetMaskToPrefixLength(subnetMask)) - 2); } /** * Calculates the count of subnets for the given subnet mask. * * @param subnet mask an integer representation of the subnet mask * @return the count of subnets */ public static long subnetCount(int subnetMask){ return (long)(Math.pow(2, subnetMaskToPrefixLength(subnetMask) % 8)); } /** * Calculates the network (routing prefix) for the given IP * address and subnet mask. * * @param ip an integer representation of the IP address * @param subnet mask an integer representation of the subnet mask * @return integer an representation of the network */ public static int network(int ip, int subnetMask){ return ip & subnetMask; } /** * Calculates the broadcast address for given IP address or network and the subnet mask * * @param ip an integer representation of the IP address * @param subnet mask an integer representation of the subnet mask * @return an integer representation of the broadcast address */ public static int brodcast(int ip, int subnetMask){ return ip | ~subnetMask; } /** * Checks whether the given IP address in the range of IP addresses * for subnet calculated by given network and subnet mask. * Network and broadcast addresses are excluded. * * @param ip an integer representation of the IP address * @param network an integer representation of the network (routing prefix) * @param subnet mask an integer representation of the subnet mask * @return true if IP in range and false in otherwise */ public static boolean isInRange(int ip, int network, int subnetMask){ return ip >= network && ip <= brodcast(network, subnetMask); } }
Exception message edited
src/ru/eqlbin/utils/net/ipv4/IPv4SubnetUtils.java
Exception message edited
<ide><path>rc/ru/eqlbin/utils/net/ipv4/IPv4SubnetUtils.java <ide> throw new IllegalArgumentException( <ide> "Incorrect routing prefix length: " + routingPrefixLength + <ide> ". It must be between " + MIN_PREFIX_LENGTH +" and " + <del> MAX_PREFIX_LENGTH + " (inclusive)"); <add> MAX_PREFIX_LENGTH + " (both inclusive)"); <ide> <ide> int val = 0; <ide> int shift = MAX_PREFIX_LENGTH;
Java
apache-2.0
e8d9718f20c3606c3e6669e4d335e367553f7171
0
sruehl/camel-example-rcode,sruehl/camel-example-rcode
package org.apacheextras.camel.examples.rcode.builder; import org.apache.camel.Exchange; import org.apache.camel.LoggingLevel; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.dataformat.csv.CsvDataFormat; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import org.apache.camel.model.dataformat.JsonLibrary; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.CharEncoding; import org.apacheextras.camel.examples.rcode.bean.MonthlySalesFigureCalculator; import org.apacheextras.camel.examples.rcode.types.ForecastDocument; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author cemmersb, Sebastian Rühl */ public class RCodeRouteBuilder extends RouteBuilder { /** * Logger provides some degree of debugging information. */ private final static Logger LOGGER = LoggerFactory.getLogger(RCodeRouteBuilder.class); /** * Map contains all the R code which has been loaded via external files. */ private final static Map<String, String> R_CODE_SOURCES = new HashMap<String, String>(); static { R_CODE_SOURCES.put("FN_PLOT_HOLT_WINTERS_FORECAST", sourceRCodeSources("fn_PlotHoltWintersForecast.R")); R_CODE_SOURCES.put("CMD_LIBRARIES", sourceRCodeSources("cmd_Libraries.R")); R_CODE_SOURCES.put("CMD_TIME_SERIES", sourceRCodeSources("cmd_TimeSeries.R")); R_CODE_SOURCES.put("CMD_DEVICE", sourceRCodeSources("cmd_Device.R")); R_CODE_SOURCES.put("CMD_PLOT", sourceRCodeSources("cmd_Plot.R")); R_CODE_SOURCES.put("CMD_BINARY", sourceRCodeSources("cmd_Binary.R")); } /** * Source file containing the data to be forecasted. */ private File source; /** * Target directory the result will be written to. */ private File target; /** * Camel endpoint where the CSV result will be written to. */ private static final String DIRECT_CSV_SINK_URI = "direct://csv_sink"; /** * Camel endpoint that starts the R-Code processing. */ private static final String DIRECT_RCODE_SOURCE_URI = "direct://rcode_source"; /** * Camel endpoint that starts writing the output as binary file. */ private static final String DIRECT_GRAPH_FILE_SOURCE_URI = "seda://graph_file_source"; /** * Camel endpoint that writes the result as JSON formated file. */ private static final String DIRECT_GRAPH_JSON_SOURCE_URI = "seda://graph_json_source"; /** * Creates the routes by taking a source and a target file. * * @param source directory to read the CSV * @param target directory to write the JPEG */ public RCodeRouteBuilder(File source, File target) { this.source = source; this.target = target; } /** * Reads the R code sources based on the given source path within the class * path. Returns the result as String that can be further used within the * route. * * @param rCodeSource - String value of of the resource within the class * loader * @return read sources as String value */ private static String sourceRCodeSources(String rCodeSource) { // StringWriter to convert the InputStream to String final StringWriter writer = new StringWriter(); LOGGER.debug("Try to source the following R Code snipped: {}", rCodeSource); // Sourcing the external file and read the UTF-8 encoded String try { InputStream inputStream = RCodeRouteBuilder.class.getResourceAsStream(rCodeSource); IOUtils.copy(inputStream, writer, CharEncoding.UTF_8); } catch (IOException ex) { LOGGER.error("Could not copy InputStream on to StringWriter: {}", ex); } // Return the R code sources return writer.toString(); } /** * {@inheritDoc} * <p> * Configures all routes required for the RCode demo. * </p> */ @Override public void configure() throws Exception { configureCsvRoute(); configureRCodeRoute(); configureGraphFileRoute(); configureGraphJsonRoute(); wireRoutes(); } /** * Takes an input as bytes and writes it as JSON formatted file. */ private void configureGraphJsonRoute() { from(DIRECT_GRAPH_JSON_SOURCE_URI) .convertBodyTo(ForecastDocument.class) // TODO: Add title to forecast document // TODO: Add path to forecast document // TODO: Add date to forecast document .marshal().json(JsonLibrary.Gson) // TODO: Modify log level to debug .to("log://json?level=INFO") // TODO: Write file to target (same name as jpeg, just ending with *.json) .end(); } /** * Takes an input as bytes and writes it as an JPEG file. */ private void configureGraphFileRoute() { from(DIRECT_GRAPH_FILE_SOURCE_URI) .setHeader(Exchange.FILE_NAME, simple("graph${exchangeId}.jpeg")) .to("file://" + target.getAbsolutePath()) .log("Generated graph file: '${header.CamelFileNameProduced}'") .end(); } /** * Takes an incoming string argument containing monthly quantities and * generates an output graph. */ private void configureRCodeRoute() { from(DIRECT_RCODE_SOURCE_URI) // Create the R Command via simple language and String concatenation .setBody(simple(R_CODE_SOURCES.get("CMD_LIBRARIES") + "\n" + R_CODE_SOURCES.get("FN_PLOT_HOLT_WINTERS_FORECAST") + "\n" + "sales <- c(${body});\n" + R_CODE_SOURCES.get("CMD_TIME_SERIES") + "\n" + R_CODE_SOURCES.get("CMD_DEVICE") + "\n" + R_CODE_SOURCES.get("CMD_PLOT") + "\n" + R_CODE_SOURCES.get("CMD_BINARY") + "\n")) // Logs the R command in debug mode // Send the R command to Rserve .to("rcode://localhost:6311/parse_and_eval?bufferSize=4194304") // Convert the generated JPEG as bytes to byte code .setBody(simple("${body.asBytes}")) .end(); } /** * Configures a CSV route that reads the quantity values from the route and * sends the result to the RCode route. */ private void configureCsvRoute() { // Configure CSV data format with ';' as separator and skipping of the header final CsvDataFormat csv = new CsvDataFormat(); csv.setDelimiter(";"); csv.setSkipFirstLine(true); from("file://" + source.getPath() + "?noop=TRUE") .unmarshal(csv) // Call the processor to calculate the daily figures into monthly results .bean(MonthlySalesFigureCalculator.class) .to(DIRECT_CSV_SINK_URI) .end(); } /** * Wires the routes together. */ private void wireRoutes() { from(DIRECT_CSV_SINK_URI) .to(DIRECT_RCODE_SOURCE_URI) .multicast() .to(DIRECT_GRAPH_FILE_SOURCE_URI, DIRECT_GRAPH_JSON_SOURCE_URI) .end(); } }
src/main/java/org/apacheextras/camel/examples/rcode/builder/RCodeRouteBuilder.java
package org.apacheextras.camel.examples.rcode.builder; import org.apache.camel.Exchange; import org.apache.camel.LoggingLevel; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.dataformat.csv.CsvDataFormat; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import org.apache.camel.model.dataformat.JsonLibrary; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.CharEncoding; import org.apacheextras.camel.examples.rcode.bean.MonthlySalesFigureCalculator; import org.apacheextras.camel.examples.rcode.types.ForecastDocument; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author cemmersb, Sebastian Rühl */ public class RCodeRouteBuilder extends RouteBuilder { /** * Logger provides some degree of debugging information. */ private final static Logger LOGGER = LoggerFactory.getLogger(RCodeRouteBuilder.class); /** * Map contains all the R code which has been loaded via external files. */ private final static Map<String, String> R_CODE_SOURCES = new HashMap<String, String>(); static { R_CODE_SOURCES.put("FN_PLOT_HOLT_WINTERS_FORECAST", sourceRCodeSources("fn_PlotHoltWintersForecast.R")); R_CODE_SOURCES.put("CMD_LIBRARIES", sourceRCodeSources("cmd_Libraries.R")); R_CODE_SOURCES.put("CMD_TIME_SERIES", sourceRCodeSources("cmd_TimeSeries.R")); R_CODE_SOURCES.put("CMD_DEVICE", sourceRCodeSources("cmd_Device.R")); R_CODE_SOURCES.put("CMD_PLOT", sourceRCodeSources("cmd_Plot.R")); R_CODE_SOURCES.put("CMD_BINARY", sourceRCodeSources("cmd_Binary.R")); } /** * Source file containing the data to be forecasted. */ private File source; /** * Target directory the result will be written to. */ private File target; /** * Camel endpoint where the CSV result will be written to. */ private static final String DIRECT_CSV_SINK_URI = "direct://csv_sink"; /** * Camel endpoint that starts the R-Code processing. */ private static final String DIRECT_RCODE_SOURCE_URI = "direct://rcode_source"; /** * Camel endpoint that starts writing the output as binary file. */ private static final String DIRECT_GRAPH_FILE_SOURCE_URI = "seda://graph_file_source"; /** * Camel endpoint that writes the result as JSON formated file. */ private static final String DIRECT_GRAPH_JSON_SOURCE_URI = "seda://graph_json_source"; /** * Creates the routes by taking a source and a target file. * * @param source directory to read the CSV * @param target directory to write the JPEG */ public RCodeRouteBuilder(File source, File target) { this.source = source; this.target = target; } /** * Reads the R code sources based on the given source path within the class * path. Returns the result as String that can be further used within the * route. * * @param rCodeSource - String value of of the resource within the class * loader * @return read sources as String value */ private static String sourceRCodeSources(String rCodeSource) { // StringWriter to convert the InputStream to String final StringWriter writer = new StringWriter(); LOGGER.debug("Try to source the following R Code snipped: {}", rCodeSource); // Sourcing the external file and read the UTF-8 encoded String try { InputStream inputStream = RCodeRouteBuilder.class.getResourceAsStream(rCodeSource); IOUtils.copy(inputStream, writer, CharEncoding.UTF_8); } catch (IOException ex) { LOGGER.error("Could not copy InputStream on to StringWriter: {}", ex); } // Return the R code sources return writer.toString(); } /** * {@inheritDoc} * <p> * Configures all routes required for the RCode demo. * </p> */ @Override public void configure() throws Exception { configureCsvRoute(); configureRCodeRoute(); configureGraphFileRoute(); configureGraphJsonRoute(); wireRoutes(); } /** * Takes an input as bytes and writes it as JSON formatted file. */ private void configureGraphJsonRoute() { from(DIRECT_GRAPH_JSON_SOURCE_URI) .convertBodyTo(ForecastDocument.class) // TODO: Add title to forecast document // TODO: Add path to forecast document // TODO: Add date to forecast document .marshal().json(JsonLibrary.Gson) // TODO: Modify log level to debug .to("log://json?level=INFO") // TODO: Write file to target (same name as jpeg, just ending with *.json) .end(); } /** * Takes an input as bytes and writes it as an JPEG file. */ private void configureGraphFileRoute() { from(DIRECT_GRAPH_FILE_SOURCE_URI) .setHeader(Exchange.FILE_NAME, simple("graph${exchangeId}.jpeg")) .to("file://" + target.getAbsolutePath()) .log("Generated graph file: '${header.CamelFileNameProduced}'") .end(); } /** * Takes an incoming string argument containing monthly quantities and * generates an output graph. */ private void configureRCodeRoute() { from(DIRECT_RCODE_SOURCE_URI) .log(LoggingLevel.DEBUG, "Executing R command.") // Create the R Command via simple language and String concatenation .setBody(simple(R_CODE_SOURCES.get("CMD_LIBRARIES") + "\n" + R_CODE_SOURCES.get("FN_PLOT_HOLT_WINTERS_FORECAST") + "\n" + "sales <- c(${body});\n" + R_CODE_SOURCES.get("CMD_TIME_SERIES") + "\n" + R_CODE_SOURCES.get("CMD_DEVICE") + "\n" + R_CODE_SOURCES.get("CMD_PLOT") + "\n" + R_CODE_SOURCES.get("CMD_BINARY") + "\n")) // Logs the R command in debug mode .to("log://command?level=TRACE") // Send the R command to Rserve .to("rcode://localhost:6311/parse_and_eval?bufferSize=4194304") .to("log://r_output?level=TRACE") // Convert the generated JPEG as bytes to byte code .setBody(simple("${body.asBytes}")) .end(); } /** * Configures a CSV route that reads the quantity values from the route and * sends the result to the RCode route. */ private void configureCsvRoute() { // Configure CSV data format with ';' as separator and skipping of the header final CsvDataFormat csv = new CsvDataFormat(); csv.setDelimiter(";"); csv.setSkipFirstLine(true); from("file://" + source.getPath() + "?noop=TRUE") .log(LoggingLevel.DEBUG, "Unmarshalling CSV file.") .unmarshal(csv) .to("log://CSV?level=TRACE") // Call the processor to calculate the daily figures into monthly results .bean(MonthlySalesFigureCalculator.class) .to("log://CSV?level=TRACE") .log(LoggingLevel.DEBUG, "Finished the unmarshaling") .to(DIRECT_CSV_SINK_URI) .end(); } /** * Wires the routes together. */ private void wireRoutes() { from(DIRECT_CSV_SINK_URI) .to(DIRECT_RCODE_SOURCE_URI) .multicast() .to(DIRECT_GRAPH_FILE_SOURCE_URI, DIRECT_GRAPH_JSON_SOURCE_URI) .end(); } }
remove log endpoints
src/main/java/org/apacheextras/camel/examples/rcode/builder/RCodeRouteBuilder.java
remove log endpoints
<ide><path>rc/main/java/org/apacheextras/camel/examples/rcode/builder/RCodeRouteBuilder.java <ide> private void configureRCodeRoute() { <ide> <ide> from(DIRECT_RCODE_SOURCE_URI) <del> .log(LoggingLevel.DEBUG, "Executing R command.") <ide> // Create the R Command via simple language and String concatenation <ide> .setBody(simple(R_CODE_SOURCES.get("CMD_LIBRARIES") + "\n" <ide> + R_CODE_SOURCES.get("FN_PLOT_HOLT_WINTERS_FORECAST") + "\n" <ide> + R_CODE_SOURCES.get("CMD_PLOT") + "\n" <ide> + R_CODE_SOURCES.get("CMD_BINARY") + "\n")) <ide> // Logs the R command in debug mode <del> .to("log://command?level=TRACE") <ide> // Send the R command to Rserve <ide> .to("rcode://localhost:6311/parse_and_eval?bufferSize=4194304") <del> .to("log://r_output?level=TRACE") <ide> // Convert the generated JPEG as bytes to byte code <ide> .setBody(simple("${body.asBytes}")) <ide> .end(); <ide> csv.setDelimiter(";"); <ide> csv.setSkipFirstLine(true); <ide> from("file://" + source.getPath() + "?noop=TRUE") <del> .log(LoggingLevel.DEBUG, "Unmarshalling CSV file.") <ide> .unmarshal(csv) <del> .to("log://CSV?level=TRACE") <ide> // Call the processor to calculate the daily figures into monthly results <ide> .bean(MonthlySalesFigureCalculator.class) <del> .to("log://CSV?level=TRACE") <del> .log(LoggingLevel.DEBUG, "Finished the unmarshaling") <ide> .to(DIRECT_CSV_SINK_URI) <ide> .end(); <ide> }
JavaScript
mit
41069c1e58f81d4306af238ebf1d30dd07c57f5d
0
ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt
'use strict'; // --------------------------------------------------------------------------- const Exchange = require ('./base/Exchange'); const { ExchangeError, ArgumentsRequired, ExchangeNotAvailable, InsufficientFunds, OrderNotFound, InvalidOrder, AccountSuspended, InvalidNonce, DDoSProtection, NotSupported, BadRequest, AuthenticationError } = require ('./base/errors'); // --------------------------------------------------------------------------- module.exports = class kucoin2 extends Exchange { describe () { return this.deepExtend (super.describe (), { 'id': 'kucoin2', 'name': 'KuCoin', 'countries': [ 'SC' ], 'rateLimit': 334, 'version': 'v2', 'certified': true, 'comment': 'Platform 2.0', 'has': { 'fetchMarkets': true, 'fetchCurrencies': true, 'fetchTicker': true, 'fetchTickers': true, 'fetchOrderBook': true, 'fetchOrder': true, 'fetchClosedOrders': true, 'fetchOpenOrders': true, 'fetchDepositAddress': true, 'createDepositAddress': true, 'withdraw': true, 'fetchDeposits': true, 'fetchWithdrawals': true, 'fetchBalance': true, 'fetchTrades': true, 'fetchMyTrades': true, 'createOrder': true, 'cancelOrder': true, 'fetchAccounts': true, 'fetchFundingFee': true, 'fetchOHLCV': true, }, 'urls': { 'logo': 'https://user-images.githubusercontent.com/1294454/51909432-b0a72780-23dd-11e9-99ba-73d23c8d4eed.jpg', 'referral': 'https://www.kucoin.com/ucenter/signup?rcode=E5wkqe', 'api': { 'public': 'https://openapi-v2.kucoin.com', 'private': 'https://openapi-v2.kucoin.com', }, 'test': { 'public': 'https://openapi-sandbox.kucoin.com', 'private': 'https://openapi-sandbox.kucoin.com', }, 'www': 'https://www.kucoin.com', 'doc': [ 'https://docs.kucoin.com', ], }, 'requiredCredentials': { 'apiKey': true, 'secret': true, 'password': true, }, 'api': { 'public': { 'get': [ 'timestamp', 'symbols', 'market/allTickers', 'market/orderbook/level{level}', 'market/histories', 'market/candles', 'market/stats', 'currencies', 'currencies/{currency}', ], 'post': [ 'bullet-public', ], }, 'private': { 'get': [ 'accounts', 'accounts/{accountId}', 'accounts/{accountId}/ledgers', 'accounts/{accountId}/holds', 'deposit-addresses', 'deposits', 'withdrawals', 'withdrawals/quotas', 'orders', 'orders/{orderId}', 'fills', ], 'post': [ 'accounts', 'accounts/inner-transfer', 'deposit-addresses', 'withdrawals', 'orders', 'bullet-private', ], 'delete': [ 'withdrawals/{withdrawalId}', 'orders/{orderId}', ], }, }, 'timeframes': { '1m': '1min', '3m': '3min', '5m': '5min', '15m': '15min', '30m': '30min', '1h': '1hour', '2h': '2hour', '4h': '4hour', '6h': '6hour', '8h': '8hour', '12h': '12hour', '1d': '1day', '1w': '1week', }, 'exceptions': { '400': BadRequest, '401': AuthenticationError, '403': NotSupported, '404': NotSupported, '405': NotSupported, '429': DDoSProtection, '500': ExchangeError, '503': ExchangeNotAvailable, '200004': InsufficientFunds, '300000': InvalidOrder, '400001': AuthenticationError, '400002': InvalidNonce, '400003': AuthenticationError, '400004': AuthenticationError, '400005': AuthenticationError, '400006': AuthenticationError, '400007': AuthenticationError, '400008': NotSupported, '400100': ArgumentsRequired, '411100': AccountSuspended, '500000': ExchangeError, 'order_not_exist': OrderNotFound, // {"code":"order_not_exist","msg":"order_not_exist"} ¯\_(ツ)_/¯ 'order_not_exist_or_not_allow_to_cancel': InvalidOrder, }, 'fees': { 'trading': { 'tierBased': false, 'percentage': true, 'taker': 0.001, 'maker': 0.001, }, 'funding': { 'tierBased': false, 'percentage': false, 'withdraw': {}, 'deposit': {}, }, }, 'options': { 'version': 'v1', 'symbolSeparator': '-', }, }); } nonce () { return this.milliseconds (); } async loadTimeDifference () { const response = await this.publicGetTimestamp (); const after = this.milliseconds (); const kucoinTime = this.safeInteger (response, 'data'); this.options['timeDifference'] = parseInt (after - kucoinTime); return this.options['timeDifference']; } async fetchMarkets (params = {}) { const response = await this.publicGetSymbols (params); // // { quoteCurrency: 'BTC', // symbol: 'KCS-BTC', // quoteMaxSize: '9999999', // quoteIncrement: '0.000001', // baseMinSize: '0.01', // quoteMinSize: '0.00001', // enableTrading: true, // priceIncrement: '0.00000001', // name: 'KCS-BTC', // baseIncrement: '0.01', // baseMaxSize: '9999999', // baseCurrency: 'KCS' } // const data = response['data']; const result = {}; for (let i = 0; i < data.length; i++) { const market = data[i]; const id = market['name']; const baseId = market['baseCurrency']; const quoteId = market['quoteCurrency']; const base = this.commonCurrencyCode (baseId); const quote = this.commonCurrencyCode (quoteId); const symbol = base + '/' + quote; const active = market['enableTrading']; const baseMaxSize = this.safeFloat (market, 'baseMaxSize'); const baseMinSize = this.safeFloat (market, 'baseMinSize'); const quoteMaxSize = this.safeFloat (market, 'quoteMaxSize'); const quoteMinSize = this.safeFloat (market, 'quoteMinSize'); const quoteIncrement = this.safeFloat (market, 'quoteIncrement'); const precision = { 'amount': this.precisionFromString (this.safeString (market, 'baseIncrement')), 'price': this.precisionFromString (this.safeString (market, 'priceIncrement')), }; const limits = { 'amount': { 'min': baseMinSize, 'max': baseMaxSize, }, 'price': { 'min': Math.max (baseMinSize / quoteMaxSize, quoteIncrement), 'max': baseMaxSize / quoteMinSize, }, 'cost': { 'min': quoteMinSize, 'max': quoteMaxSize, }, }; result[symbol] = { 'id': id, 'symbol': symbol, 'baseId': baseId, 'quoteId': quoteId, 'base': base, 'quote': quote, 'active': active, 'precision': precision, 'limits': limits, 'info': market, }; } return result; } async fetchCurrencies (params = {}) { const response = await this.publicGetCurrencies (params); // // { precision: 10, // name: 'KCS', // fullName: 'KCS shares', // currency: 'KCS' } // const responseData = response['data']; let result = {}; for (let i = 0; i < responseData.length; i++) { const entry = responseData[i]; const id = this.safeString (entry, 'name'); const name = entry['fullName']; const code = this.commonCurrencyCode (id); const precision = this.safeInteger (entry, 'precision'); result[code] = { 'id': id, 'name': name, 'code': code, 'precision': precision, 'info': entry, }; } return result; } async fetchAccounts (params = {}) { const response = await this.privateGetAccounts (params); // // { code: "200000", // data: [ { balance: "0.00009788", // available: "0.00009788", // holds: "0", // currency: "BTC", // id: "5c6a4fd399a1d81c4f9cc4d0", // type: "trade" }, // ..., // { balance: "0.00000001", // available: "0.00000001", // holds: "0", // currency: "ETH", // id: "5c6a49ec99a1d819392e8e9f", // type: "trade" } ] } // const data = this.safeValue (response, 'data'); let result = []; for (let i = 0; i < data.length; i++) { const account = data[i]; const accountId = this.safeString (account, 'id'); const currencyId = this.safeString (account, 'currency'); const code = this.commonCurrencyCode (currencyId); const type = this.safeString (account, 'type'); // main or trade result.push ({ 'id': accountId, 'type': type, 'currency': code, 'info': account, }); } return result; } async fetchFundingFee (code, params = {}) { const currencyId = this.currencyId (code); const request = { 'currency': currencyId, }; const response = await this.privateGetWithdrawalsQuotas (this.extend (request, params)); const data = response['data']; let withdrawFees = {}; withdrawFees[code] = this.safeFloat (data, 'withdrawMinFee'); return { 'info': response, 'withdraw': withdrawFees, 'deposit': {}, }; } parseTicker (ticker, market = undefined) { // // { // 'buy': '0.00001168', // 'changePrice': '-0.00000018', // 'changeRate': '-0.0151', // 'datetime': 1550661146316, // 'high': '0.0000123', // 'last': '0.00001169', // 'low': '0.00001159', // 'sell': '0.00001182', // 'symbol': 'LOOM-BTC', // 'vol': '44399.5669' // } // let percentage = this.safeFloat (ticker, 'changeRate'); if (percentage !== undefined) { percentage = percentage * 100; } const last = this.safeFloat (ticker, 'last'); let symbol = undefined; const marketId = this.safeString (ticker, 'symbol'); if (marketId !== undefined) { if (marketId in this.markets_by_id) { market = this.markets_by_id[marketId]; symbol = market['symbol']; } else { const [ baseId, quoteId ] = marketId.split ('-'); const base = this.commonCurrencyCode (baseId); const quote = this.commonCurrencyCode (quoteId); symbol = base + '/' + quote; } } if (symbol === undefined) { if (market !== undefined) { symbol = market['symbol']; } } return { 'symbol': symbol, 'timestamp': undefined, 'datetime': undefined, 'high': this.safeFloat (ticker, 'high'), 'low': this.safeFloat (ticker, 'low'), 'bid': this.safeFloat (ticker, 'buy'), 'bidVolume': undefined, 'ask': this.safeFloat (ticker, 'sell'), 'askVolume': undefined, 'vwap': undefined, 'open': this.safeFloat (ticker, 'open'), 'close': last, 'last': last, 'previousClose': undefined, 'change': this.safeFloat (ticker, 'changePrice'), 'percentage': percentage, 'average': undefined, 'baseVolume': this.safeFloat (ticker, 'vol'), 'quoteVolume': this.safeFloat (ticker, 'volValue'), 'info': ticker, }; } async fetchTickers (symbols = undefined, params = {}) { await this.loadMarkets (); const response = await this.publicGetMarketAllTickers (params); // // { // "code": "200000", // "data": { // "date": 1550661940645, // "ticker": [ // 'buy': '0.00001168', // 'changePrice': '-0.00000018', // 'changeRate': '-0.0151', // 'datetime': 1550661146316, // 'high': '0.0000123', // 'last': '0.00001169', // 'low': '0.00001159', // 'sell': '0.00001182', // 'symbol': 'LOOM-BTC', // 'vol': '44399.5669' // }, // ] // } // const data = this.safeValue (response, 'data', {}); const tickers = this.safeValue (data, 'ticker', []); const result = {}; for (let i = 0; i < tickers.length; i++) { const ticker = this.parseTicker (tickers[i]); const symbol = this.safeString (ticker, 'symbol'); if (symbol !== undefined) { result[symbol] = ticker; } } return result; } async fetchTicker (symbol, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'symbol': market['id'], }; const response = await this.publicGetMarketStats (this.extend (request, params)); // // { // "code": "200000", // "data": { // 'buy': '0.00001168', // 'changePrice': '-0.00000018', // 'changeRate': '-0.0151', // 'datetime': 1550661146316, // 'high': '0.0000123', // 'last': '0.00001169', // 'low': '0.00001159', // 'sell': '0.00001182', // 'symbol': 'LOOM-BTC', // 'vol': '44399.5669' // }, // } // return this.parseTicker (response['data'], market); } parseOHLCV (ohlcv, market = undefined, timeframe = '1m', since = undefined, limit = undefined) { // // [ // "1545904980", // Start time of the candle cycle // "0.058", // opening price // "0.049", // closing price // "0.058", // highest price // "0.049", // lowest price // "0.018", // base volume // "0.000945", // quote volume // ] // return [ parseInt (ohlcv[0]) * 1000, parseFloat (ohlcv[1]), parseFloat (ohlcv[3]), parseFloat (ohlcv[4]), parseFloat (ohlcv[2]), parseFloat (ohlcv[5]), ]; } async fetchOHLCV (symbol, timeframe = '15m', since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const marketId = market['id']; let request = { 'symbol': marketId, 'endAt': this.seconds (), // required param 'type': this.timeframes[timeframe], }; if (since !== undefined) { request['startAt'] = Math.floor (since / 1000); } const response = await this.publicGetMarketCandles (this.extend (request, params)); const responseData = response['data']; return this.parseOHLCVs (responseData, market, timeframe, since, limit); } async createDepositAddress (code, params = {}) { await this.loadMarkets (); const currencyId = this.currencyId (code); const request = { 'currency': currencyId }; const response = await this.privatePostDepositAddresses (this.extend (request, params)); // BCH {"code":"200000","data":{"address":"bitcoincash:qza3m4nj9rx7l9r0cdadfqxts6f92shvhvr5ls4q7z","memo":""}} // BTC {"code":"200000","data":{"address":"36SjucKqQpQSvsak9A7h6qzFjrVXpRNZhE","memo":""}} const data = this.safeValue (response, 'data', {}); let address = this.safeString (data, 'address'); // BCH/BSV is returned with a "bitcoincash:" prefix, which we cut off here and only keep the address address = address.replace ('bitcoincash:', ''); const tag = this.safeString (data, 'memo'); this.checkAddress (address); return { 'info': response, 'currency': code, 'address': address, 'tag': tag, }; } async fetchDepositAddress (code, params = {}) { await this.loadMarkets (); const currencyId = this.currencyId (code); const request = { 'currency': currencyId }; const response = await this.privateGetDepositAddresses (this.extend (request, params)); // BCH {"code":"200000","data":{"address":"bitcoincash:qza3m4nj9rx7l9r0cdadfqxts6f92shvhvr5ls4q7z","memo":""}} // BTC {"code":"200000","data":{"address":"36SjucKqQpQSvsak9A7h6qzFjrVXpRNZhE","memo":""}} const data = this.safeValue (response, 'data', {}); let address = this.safeString (data, 'address'); // BCH/BSV is returned with a "bitcoincash:" prefix, which we cut off here and only keep the address if (address !== undefined) { address = address.replace ('bitcoincash:', ''); } const tag = this.safeString (data, 'memo'); this.checkAddress (address); return { 'info': response, 'currency': code, 'address': address, 'tag': tag, }; } async fetchOrderBook (symbol, limit = undefined, params = {}) { await this.loadMarkets (); const marketId = this.marketId (symbol); const request = this.extend ({ 'symbol': marketId, 'level': 2 }, params); const response = await this.publicGetMarketOrderbookLevelLevel (request); // // { sequence: '1547731421688', // asks: [ [ '5c419328ef83c75456bd615c', '0.9', '0.09' ], ... ], // bids: [ [ '5c419328ef83c75456bd615c', '0.9', '0.09' ], ... ], } // const data = response['data']; const timestamp = this.safeInteger (data, 'sequence'); // level can be a string such as 2_20 or 2_100 const levelString = this.safeString (request, 'level'); const levelParts = levelString.split ('_'); const level = parseInt (levelParts[0]); return this.parseOrderBook (data, timestamp, 'bids', 'asks', level - 2, level - 1); } async createOrder (symbol, type, side, amount, price = undefined, params = {}) { await this.loadMarkets (); const marketId = this.marketId (symbol); // required param, cannot be used twice const clientOid = this.uuid (); const request = { 'clientOid': clientOid, 'price': this.priceToPrecision (symbol, price), 'side': side, 'size': this.amountToPrecision (symbol, amount), 'symbol': marketId, 'type': type, }; const response = await this.privatePostOrders (this.extend (request, params)); const responseData = response['data']; return { 'id': responseData['orderId'], 'symbol': symbol, 'type': type, 'side': side, 'status': 'open', 'clientOid': clientOid, 'info': responseData, }; } async cancelOrder (id, symbol = undefined, params = {}) { const request = { 'orderId': id }; const response = this.privateDeleteOrdersOrderId (this.extend (request, params)); return response; } async fetchOrdersByStatus (status, symbol = undefined, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); let request = { 'status': status, }; let market = undefined; if (symbol !== undefined) { market = this.market (symbol); request['symbol'] = market['id']; } if (since !== undefined) { request['startAt'] = since; } if (limit !== undefined) { request['pageSize'] = limit; } const response = await this.privateGetOrders (this.extend (request, params)); const responseData = this.safeValue (response, 'data', {}); const orders = this.safeValue (responseData, 'items', []); return this.parseOrders (orders, market, since, limit); } async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) { return this.fetchOrdersByStatus ('done', symbol, since, limit, params); } async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) { return this.fetchOrdersByStatus ('active', symbol, since, limit, params); } async fetchOrder (id, symbol = undefined, params = {}) { await this.loadMarkets (); const request = { 'orderId': id, }; let market = undefined; if (symbol !== undefined) { market = this.market (symbol); } const response = await this.privateGetOrdersOrderId (this.extend (request, params)); const responseData = response['data']; return this.parseOrder (responseData, market); } parseOrder (order, market = undefined) { // // { "id": "5c35c02703aa673ceec2a168", // "symbol": "BTC-USDT", // "opType": "DEAL", // "type": "limit", // "side": "buy", // "price": "10", // "size": "2", // "funds": "0", // "dealFunds": "0.166", // "dealSize": "2", // "fee": "0", // "feeCurrency": "USDT", // "stp": "", // "stop": "", // "stopTriggered": false, // "stopPrice": "0", // "timeInForce": "GTC", // "postOnly": false, // "hidden": false, // "iceberge": false, // "visibleSize": "0", // "cancelAfter": 0, // "channel": "IOS", // "clientOid": "", // "remark": "", // "tags": "", // "isActive": false, // "cancelExist": false, // "createdAt": 1547026471000 } // let symbol = undefined; const marketId = this.safeString (order, 'symbol'); if (marketId !== undefined) { if (marketId in this.markets_by_id) { market = this.markets_by_id[marketId]; symbol = market['symbol']; } else { const [ baseId, quoteId ] = marketId.split ('-'); const base = this.commonCurrencyCode (baseId); const quote = this.commonCurrencyCode (quoteId); symbol = base + '/' + quote; } market = this.safeValue (this.markets_by_id, marketId); } if (symbol === undefined) { if (market !== undefined) { symbol = market['symbol']; } } const orderId = this.safeString (order, 'id'); const type = this.safeString (order, 'type'); const timestamp = this.safeInteger (order, 'createdAt'); const datetime = this.iso8601 (timestamp); const price = this.safeFloat (order, 'price'); const side = this.safeString (order, 'side'); const feeCurrencyId = this.safeString (order, 'feeCurrency'); const feeCurrency = this.commonCurrencyCode (feeCurrencyId); const feeCost = this.safeFloat (order, 'fee'); const amount = this.safeFloat (order, 'size'); const filled = this.safeFloat (order, 'dealSize'); const cost = this.safeFloat (order, 'dealFunds'); const remaining = amount - filled; // bool const status = order['isActive'] ? 'open' : 'closed'; let fee = { 'currency': feeCurrency, 'cost': feeCost, }; return { 'id': orderId, 'symbol': symbol, 'type': type, 'side': side, 'amount': amount, 'price': price, 'cost': cost, 'filled': filled, 'remaining': remaining, 'timestamp': timestamp, 'datetime': datetime, 'fee': fee, 'status': status, 'info': order, }; } async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); let request = {}; let market = undefined; if (symbol !== undefined) { market = this.market (symbol); request['symbol'] = market['id']; } if (since !== undefined) { request['startAt'] = since; } if (limit !== undefined) { request['pageSize'] = limit; } const response = await this.privateGetFills (this.extend (request, params)); const data = this.safeValue (response, 'data', {}); const trades = this.safeValue (data, 'items', []); return this.parseTrades (trades, market, since, limit); } async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); const market = this.market (symbol); let request = { 'symbol': market['id'], }; if (since !== undefined) { request['startAt'] = Math.floor (since / 1000); } if (limit !== undefined) { request['pageSize'] = limit; } const response = await this.publicGetMarketHistories (this.extend (request, params)); // { // "code": "200000", // "data": [ // { // "sequence": "1548764654235", // "side": "sell", // "size":"0.6841354", // "price":"0.03202", // "time":1548848575203567174 // } // ] // } // const trades = this.safeValue (response, 'data', []); return this.parseTrades (trades, market, since, limit); } parseTrade (trade, market = undefined) { // // fetchTrades (public) // // { // "sequence": "1548764654235", // "side": "sell", // "size":"0.6841354", // "price":"0.03202", // "time":1548848575203567174 // } // // fetchMyTrades (private) // // { // "symbol":"BTC-USDT", // "tradeId":"5c35c02709e4f67d5266954e", // "orderId":"5c35c02703aa673ceec2a168", // "counterOrderId":"5c1ab46003aa676e487fa8e3", // "side":"buy", // "liquidity":"taker", // "forceTaker":true, // "price":"0.083", // "size":"0.8424304", // "funds":"0.0699217232", // "fee":"0", // "feeRate":"0", // "feeCurrency":"USDT", // "stop":"", // "type":"limit", // "createdAt":1547026472000 // } // let symbol = undefined; const marketId = this.safeString (trade, 'symbol'); if (marketId !== undefined) { if (marketId in this.markets_by_id) { market = this.markets_by_id[marketId]; symbol = market['symbol']; } else { const [ baseId, quoteId ] = marketId.split ('-'); const base = this.commonCurrencyCode (baseId); const quote = this.commonCurrencyCode (quoteId); symbol = base + '/' + quote; } market = this.safeValue (this.markets_by_id, marketId); } if (symbol === undefined) { if (market !== undefined) { symbol = market['symbol']; } } let id = this.safeString (trade, 'tradeId'); if (id !== undefined) { id = id.toString (); } const orderId = this.safeString (trade, 'orderId'); const amount = this.safeFloat (trade, 'size'); let timestamp = this.safeInteger (trade, 'time'); if (timestamp !== undefined) { timestamp = parseInt (timestamp / 1000000); } else { timestamp = this.safeInteger (trade, 'createdAt'); } const price = this.safeFloat (trade, 'price'); const side = this.safeString (trade, 'side'); const fee = { 'cost': this.safeFloat (trade, 'fee'), 'rate': this.safeFloat (trade, 'feeRate'), 'currency': this.safeString (trade, 'feeCurrency'), }; const type = this.safeString (trade, 'type'); let cost = this.safeFloat (trade, 'funds'); if (amount !== undefined) { if (price !== undefined) { cost = amount * price; } } return { 'info': trade, 'id': id, 'order': orderId, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'symbol': symbol, 'type': type, 'side': side, 'price': price, 'amount': amount, 'cost': cost, 'fee': fee, }; } async withdraw (code, amount, address, tag = undefined, params = {}) { await this.loadMarkets (); this.checkAddress (address); const currency = this.currencyId (code); let request = { 'currency': currency, 'address': address, 'amount': amount, }; if (tag !== undefined) { request['memo'] = tag; } const response = await this.privatePostWithdrawals (this.extend (request, params)); // // { "withdrawalId": "5bffb63303aa675e8bbe18f9" } // const responseData = response['data']; return { 'id': this.safeString (responseData, 'withdrawalId'), 'info': responseData, }; } parseTransactionStatus (status) { const statuses = { 'SUCCESS': 'ok', 'PROCESSING': 'ok', 'FAILURE': 'failed', }; return this.safeString (statuses, status); } parseTransaction (transaction, currency = undefined) { // // Deposits // { "address": "0x5f047b29041bcfdbf0e4478cdfa753a336ba6989", // "memo": "5c247c8a03aa677cea2a251d", // "amount": 1, // "fee": 0.0001, // "currency": "KCS", // "isInner": false, // "walletTxId": "5bbb57386d99522d9f954c5a@test004", // "status": "SUCCESS", // "createdAt": 1544178843000, // "updatedAt": 1544178891000 } // Withdrawals // { "id": "5c2dc64e03aa675aa263f1ac", // "address": "0x5bedb060b8eb8d823e2414d82acce78d38be7fe9", // "memo": "", // "currency": "ETH", // "amount": 1.0000000, // "fee": 0.0100000, // "walletTxId": "3e2414d82acce78d38be7fe9", // "isInner": false, // "status": "FAILURE", // "createdAt": 1546503758000, // "updatedAt": 1546504603000 } // let code = undefined; let currencyId = this.safeString (transaction, 'currency'); currency = this.safeValue (this.currencies_by_id, currencyId); if (currency !== undefined) { code = currency['code']; } else { code = this.commonCurrencyCode (currencyId); } const address = this.safeString (transaction, 'address'); const amount = this.safeFloat (transaction, 'amount'); const txid = this.safeString (transaction, 'walletTxId'); const type = txid === undefined ? 'withdrawal' : 'deposit'; const rawStatus = this.safeString (transaction, 'status'); const status = this.parseTransactionStatus (rawStatus); let fees = { 'cost': this.safeFloat (transaction, 'fee'), }; if (fees['cost'] !== undefined && amount !== undefined) { fees['rate'] = fees['cost'] / amount; } const tag = this.safeString (transaction, 'memo'); const timestamp = this.safeInteger2 (transaction, 'updatedAt', 'createdAt'); const datetime = this.iso8601 (timestamp); return { 'address': address, 'tag': tag, 'currency': code, 'amount': amount, 'txid': txid, 'type': type, 'status': status, 'fee': fees, 'timestamp': timestamp, 'datetime': datetime, 'info': transaction, }; } async fetchDeposits (code = undefined, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); let request = {}; let currency = undefined; if (code !== undefined) { currency = this.currency (code); request['currency'] = currency['id']; } if (since !== undefined) { request['startAt'] = since; } if (limit !== undefined) { request['pageSize'] = limit; } const response = await this.privateGetDeposits (this.extend (request, params)); // // paginated // { code: '200000', // data: // { totalNum: 0, // totalPage: 0, // pageSize: 10, // currentPage: 1, // items: [...] // } } // const responseData = response['data']['items']; return this.parseTransactions (responseData, currency, since, limit); } async fetchWithdrawals (code = undefined, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); let request = {}; let currency = undefined; if (code !== undefined) { currency = this.currency (code); request['currency'] = currency['id']; } if (since !== undefined) { request['startAt'] = since; } if (limit !== undefined) { request['pageSize'] = limit; } const response = await this.privateGetWithdrawals (this.extend (request, params)); // // paginated // { code: '200000', // data: // { totalNum: 0, // totalPage: 0, // pageSize: 10, // currentPage: 1, // items: [...] } } // const responseData = response['data']['items']; return this.parseTransactions (responseData, currency, since, limit); } async fetchBalance (params = {}) { await this.loadMarkets (); const request = { 'type': 'trade', }; const response = await this.privateGetAccounts (this.extend (request, params)); const responseData = response['data']; let result = { 'info': responseData }; for (let i = 0; i < responseData.length; i++) { const entry = responseData[i]; const currencyId = entry['currency']; const code = this.commonCurrencyCode (currencyId); let account = {}; account['total'] = this.safeFloat (entry, 'balance', 0); account['free'] = this.safeFloat (entry, 'available', 0); account['used'] = this.safeFloat (entry, 'holds', 0); result[code] = account; } return this.parseBalance (result); } sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) { // // the v2 URL is https://openapi-v2.kucoin.com/api/v1/endpoint // † ↑ // let endpoint = '/api/' + this.options['version'] + '/' + this.implodeParams (path, params); let query = this.omit (params, this.extractParams (path)); let endpart = ''; headers = headers !== undefined ? headers : {}; if (Object.keys (query).length) { if (method !== 'GET') { body = this.json (query); endpart = body; headers['Content-Type'] = 'application/json'; } else { endpoint += '?' + this.urlencode (query); } } let url = this.urls['api'][api] + endpoint; if (api === 'private') { this.checkRequiredCredentials (); const timestamp = this.nonce ().toString (); headers = this.extend ({ 'KC-API-KEY': this.apiKey, 'KC-API-TIMESTAMP': timestamp, 'KC-API-PASSPHRASE': this.password, }, headers); const payload = timestamp + method + endpoint + endpart; const signature = this.hmac (this.encode (payload), this.encode (this.secret), 'sha256', 'base64'); headers['KC-API-SIGN'] = this.decode (signature); } return { 'url': url, 'method': method, 'body': body, 'headers': headers }; } handleErrors (code, reason, url, method, headers, body, response) { if (!response) { return; } // // bad // { "code": "400100", "msg": "validation.createOrder.clientOidIsRequired" } // good // { code: '200000', data: { ... }} // let errorCode = this.safeString (response, 'code'); let message = this.safeString (response, 'msg', ''); let ExceptionClass = this.safeValue2 (this.exceptions, message, errorCode); if (ExceptionClass !== undefined) { throw new ExceptionClass (this.id + ' ' + message); } } };
js/kucoin2.js
'use strict'; // --------------------------------------------------------------------------- const Exchange = require ('./base/Exchange'); const { ExchangeError, ArgumentsRequired, ExchangeNotAvailable, InsufficientFunds, OrderNotFound, InvalidOrder, AccountSuspended, InvalidNonce, DDoSProtection, NotSupported, BadRequest, AuthenticationError } = require ('./base/errors'); // --------------------------------------------------------------------------- module.exports = class kucoin2 extends Exchange { describe () { return this.deepExtend (super.describe (), { 'id': 'kucoin2', 'name': 'KuCoin', 'countries': [ 'SC' ], 'rateLimit': 334, 'version': 'v2', 'certified': true, 'comment': 'Platform 2.0', 'has': { 'fetchMarkets': true, 'fetchCurrencies': true, 'fetchTicker': true, 'fetchTickers': true, 'fetchOrderBook': true, 'fetchOrder': true, 'fetchClosedOrders': true, 'fetchOpenOrders': true, 'fetchDepositAddress': true, 'createDepositAddress': true, 'withdraw': true, 'fetchDeposits': true, 'fetchWithdrawals': true, 'fetchBalance': true, 'fetchTrades': true, 'fetchMyTrades': true, 'createOrder': true, 'cancelOrder': true, 'fetchAccounts': true, 'fetchFundingFee': true, 'fetchOHLCV': true, }, 'urls': { 'logo': 'https://user-images.githubusercontent.com/1294454/51909432-b0a72780-23dd-11e9-99ba-73d23c8d4eed.jpg', 'referral': 'https://www.kucoin.com/ucenter/signup?rcode=E5wkqe', 'api': { 'public': 'https://openapi-v2.kucoin.com', 'private': 'https://openapi-v2.kucoin.com', }, 'test': { 'public': 'https://openapi-sandbox.kucoin.com', 'private': 'https://openapi-sandbox.kucoin.com', }, 'www': 'https://www.kucoin.com', 'doc': [ 'https://docs.kucoin.com', ], }, 'requiredCredentials': { 'apiKey': true, 'secret': true, 'password': true, }, 'api': { 'public': { 'get': [ 'timestamp', 'symbols', 'market/allTickers', 'market/orderbook/level{level}', 'market/histories', 'market/candles', 'market/stats', 'currencies', 'currencies/{currency}', ], 'post': [ 'bullet-public', ], }, 'private': { 'get': [ 'accounts', 'accounts/{accountId}', 'accounts/{accountId}/ledgers', 'accounts/{accountId}/holds', 'deposit-addresses', 'deposits', 'withdrawals', 'withdrawals/quotas', 'orders', 'orders/{orderId}', 'fills', ], 'post': [ 'accounts', 'accounts/inner-transfer', 'deposit-addresses', 'withdrawals', 'orders', 'bullet-private', ], 'delete': [ 'withdrawals/{withdrawalId}', 'orders/{orderId}', ], }, }, 'timeframes': { '1m': '1min', '3m': '3min', '5m': '5min', '15m': '15min', '30m': '30min', '1h': '1hour', '2h': '2hour', '4h': '4hour', '6h': '6hour', '8h': '8hour', '12h': '12hour', '1d': '1day', '1w': '1week', }, 'exceptions': { '400': BadRequest, '401': AuthenticationError, '403': NotSupported, '404': NotSupported, '405': NotSupported, '429': DDoSProtection, '500': ExchangeError, '503': ExchangeNotAvailable, '200004': InsufficientFunds, '300000': InvalidOrder, '400001': AuthenticationError, '400002': InvalidNonce, '400003': AuthenticationError, '400004': AuthenticationError, '400005': AuthenticationError, '400006': AuthenticationError, '400007': AuthenticationError, '400008': NotSupported, '400100': ArgumentsRequired, '411100': AccountSuspended, '500000': ExchangeError, 'order_not_exist': OrderNotFound, // {"code":"order_not_exist","msg":"order_not_exist"} ¯\_(ツ)_/¯ }, 'fees': { 'trading': { 'tierBased': false, 'percentage': true, 'taker': 0.001, 'maker': 0.001, }, 'funding': { 'tierBased': false, 'percentage': false, 'withdraw': {}, 'deposit': {}, }, }, 'options': { 'version': 'v1', 'symbolSeparator': '-', }, }); } nonce () { return this.milliseconds (); } async loadTimeDifference () { const response = await this.publicGetTimestamp (); const after = this.milliseconds (); const kucoinTime = this.safeInteger (response, 'data'); this.options['timeDifference'] = parseInt (after - kucoinTime); return this.options['timeDifference']; } async fetchMarkets (params = {}) { const response = await this.publicGetSymbols (params); // // { quoteCurrency: 'BTC', // symbol: 'KCS-BTC', // quoteMaxSize: '9999999', // quoteIncrement: '0.000001', // baseMinSize: '0.01', // quoteMinSize: '0.00001', // enableTrading: true, // priceIncrement: '0.00000001', // name: 'KCS-BTC', // baseIncrement: '0.01', // baseMaxSize: '9999999', // baseCurrency: 'KCS' } // const data = response['data']; const result = {}; for (let i = 0; i < data.length; i++) { const market = data[i]; const id = market['name']; const baseId = market['baseCurrency']; const quoteId = market['quoteCurrency']; const base = this.commonCurrencyCode (baseId); const quote = this.commonCurrencyCode (quoteId); const symbol = base + '/' + quote; const active = market['enableTrading']; const baseMaxSize = this.safeFloat (market, 'baseMaxSize'); const baseMinSize = this.safeFloat (market, 'baseMinSize'); const quoteMaxSize = this.safeFloat (market, 'quoteMaxSize'); const quoteMinSize = this.safeFloat (market, 'quoteMinSize'); const quoteIncrement = this.safeFloat (market, 'quoteIncrement'); const precision = { 'amount': this.precisionFromString (this.safeString (market, 'baseIncrement')), 'price': this.precisionFromString (this.safeString (market, 'priceIncrement')), }; const limits = { 'amount': { 'min': baseMinSize, 'max': baseMaxSize, }, 'price': { 'min': Math.max (baseMinSize / quoteMaxSize, quoteIncrement), 'max': baseMaxSize / quoteMinSize, }, 'cost': { 'min': quoteMinSize, 'max': quoteMaxSize, }, }; result[symbol] = { 'id': id, 'symbol': symbol, 'baseId': baseId, 'quoteId': quoteId, 'base': base, 'quote': quote, 'active': active, 'precision': precision, 'limits': limits, 'info': market, }; } return result; } async fetchCurrencies (params = {}) { const response = await this.publicGetCurrencies (params); // // { precision: 10, // name: 'KCS', // fullName: 'KCS shares', // currency: 'KCS' } // const responseData = response['data']; let result = {}; for (let i = 0; i < responseData.length; i++) { const entry = responseData[i]; const id = this.safeString (entry, 'name'); const name = entry['fullName']; const code = this.commonCurrencyCode (id); const precision = this.safeInteger (entry, 'precision'); result[code] = { 'id': id, 'name': name, 'code': code, 'precision': precision, 'info': entry, }; } return result; } async fetchAccounts (params = {}) { const response = await this.privateGetAccounts (params); // // { code: "200000", // data: [ { balance: "0.00009788", // available: "0.00009788", // holds: "0", // currency: "BTC", // id: "5c6a4fd399a1d81c4f9cc4d0", // type: "trade" }, // ..., // { balance: "0.00000001", // available: "0.00000001", // holds: "0", // currency: "ETH", // id: "5c6a49ec99a1d819392e8e9f", // type: "trade" } ] } // const data = this.safeValue (response, 'data'); let result = []; for (let i = 0; i < data.length; i++) { const account = data[i]; const accountId = this.safeString (account, 'id'); const currencyId = this.safeString (account, 'currency'); const code = this.commonCurrencyCode (currencyId); const type = this.safeString (account, 'type'); // main or trade result.push ({ 'id': accountId, 'type': type, 'currency': code, 'info': account, }); } return result; } async fetchFundingFee (code, params = {}) { const currencyId = this.currencyId (code); const request = { 'currency': currencyId, }; const response = await this.privateGetWithdrawalsQuotas (this.extend (request, params)); const data = response['data']; let withdrawFees = {}; withdrawFees[code] = this.safeFloat (data, 'withdrawMinFee'); return { 'info': response, 'withdraw': withdrawFees, 'deposit': {}, }; } parseTicker (ticker, market = undefined) { // // { // 'buy': '0.00001168', // 'changePrice': '-0.00000018', // 'changeRate': '-0.0151', // 'datetime': 1550661146316, // 'high': '0.0000123', // 'last': '0.00001169', // 'low': '0.00001159', // 'sell': '0.00001182', // 'symbol': 'LOOM-BTC', // 'vol': '44399.5669' // } // let percentage = this.safeFloat (ticker, 'changeRate'); if (percentage !== undefined) { percentage = percentage * 100; } const last = this.safeFloat (ticker, 'last'); let symbol = undefined; const marketId = this.safeString (ticker, 'symbol'); if (marketId !== undefined) { if (marketId in this.markets_by_id) { market = this.markets_by_id[marketId]; symbol = market['symbol']; } else { const [ baseId, quoteId ] = marketId.split ('-'); const base = this.commonCurrencyCode (baseId); const quote = this.commonCurrencyCode (quoteId); symbol = base + '/' + quote; } } if (symbol === undefined) { if (market !== undefined) { symbol = market['symbol']; } } return { 'symbol': symbol, 'timestamp': undefined, 'datetime': undefined, 'high': this.safeFloat (ticker, 'high'), 'low': this.safeFloat (ticker, 'low'), 'bid': this.safeFloat (ticker, 'buy'), 'bidVolume': undefined, 'ask': this.safeFloat (ticker, 'sell'), 'askVolume': undefined, 'vwap': undefined, 'open': this.safeFloat (ticker, 'open'), 'close': last, 'last': last, 'previousClose': undefined, 'change': this.safeFloat (ticker, 'changePrice'), 'percentage': percentage, 'average': undefined, 'baseVolume': this.safeFloat (ticker, 'vol'), 'quoteVolume': this.safeFloat (ticker, 'volValue'), 'info': ticker, }; } async fetchTickers (symbols = undefined, params = {}) { await this.loadMarkets (); const response = await this.publicGetMarketAllTickers (params); // // { // "code": "200000", // "data": { // "date": 1550661940645, // "ticker": [ // 'buy': '0.00001168', // 'changePrice': '-0.00000018', // 'changeRate': '-0.0151', // 'datetime': 1550661146316, // 'high': '0.0000123', // 'last': '0.00001169', // 'low': '0.00001159', // 'sell': '0.00001182', // 'symbol': 'LOOM-BTC', // 'vol': '44399.5669' // }, // ] // } // const data = this.safeValue (response, 'data', {}); const tickers = this.safeValue (data, 'ticker', []); const result = {}; for (let i = 0; i < tickers.length; i++) { const ticker = this.parseTicker (tickers[i]); const symbol = this.safeString (ticker, 'symbol'); if (symbol !== undefined) { result[symbol] = ticker; } } return result; } async fetchTicker (symbol, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'symbol': market['id'], }; const response = await this.publicGetMarketStats (this.extend (request, params)); // // { // "code": "200000", // "data": { // 'buy': '0.00001168', // 'changePrice': '-0.00000018', // 'changeRate': '-0.0151', // 'datetime': 1550661146316, // 'high': '0.0000123', // 'last': '0.00001169', // 'low': '0.00001159', // 'sell': '0.00001182', // 'symbol': 'LOOM-BTC', // 'vol': '44399.5669' // }, // } // return this.parseTicker (response['data'], market); } parseOHLCV (ohlcv, market = undefined, timeframe = '1m', since = undefined, limit = undefined) { // // [ // "1545904980", // Start time of the candle cycle // "0.058", // opening price // "0.049", // closing price // "0.058", // highest price // "0.049", // lowest price // "0.018", // base volume // "0.000945", // quote volume // ] // return [ parseInt (ohlcv[0]) * 1000, parseFloat (ohlcv[1]), parseFloat (ohlcv[3]), parseFloat (ohlcv[4]), parseFloat (ohlcv[2]), parseFloat (ohlcv[5]), ]; } async fetchOHLCV (symbol, timeframe = '15m', since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const marketId = market['id']; let request = { 'symbol': marketId, 'endAt': this.seconds (), // required param 'type': this.timeframes[timeframe], }; if (since !== undefined) { request['startAt'] = Math.floor (since / 1000); } const response = await this.publicGetMarketCandles (this.extend (request, params)); const responseData = response['data']; return this.parseOHLCVs (responseData, market, timeframe, since, limit); } async createDepositAddress (code, params = {}) { await this.loadMarkets (); const currencyId = this.currencyId (code); const request = { 'currency': currencyId }; const response = await this.privatePostDepositAddresses (this.extend (request, params)); // BCH {"code":"200000","data":{"address":"bitcoincash:qza3m4nj9rx7l9r0cdadfqxts6f92shvhvr5ls4q7z","memo":""}} // BTC {"code":"200000","data":{"address":"36SjucKqQpQSvsak9A7h6qzFjrVXpRNZhE","memo":""}} const data = this.safeValue (response, 'data', {}); let address = this.safeString (data, 'address'); // BCH/BSV is returned with a "bitcoincash:" prefix, which we cut off here and only keep the address address = address.replace ('bitcoincash:', ''); const tag = this.safeString (data, 'memo'); this.checkAddress (address); return { 'info': response, 'currency': code, 'address': address, 'tag': tag, }; } async fetchDepositAddress (code, params = {}) { await this.loadMarkets (); const currencyId = this.currencyId (code); const request = { 'currency': currencyId }; const response = await this.privateGetDepositAddresses (this.extend (request, params)); // BCH {"code":"200000","data":{"address":"bitcoincash:qza3m4nj9rx7l9r0cdadfqxts6f92shvhvr5ls4q7z","memo":""}} // BTC {"code":"200000","data":{"address":"36SjucKqQpQSvsak9A7h6qzFjrVXpRNZhE","memo":""}} const data = this.safeValue (response, 'data', {}); let address = this.safeString (data, 'address'); // BCH/BSV is returned with a "bitcoincash:" prefix, which we cut off here and only keep the address if (address !== undefined) { address = address.replace ('bitcoincash:', ''); } const tag = this.safeString (data, 'memo'); this.checkAddress (address); return { 'info': response, 'currency': code, 'address': address, 'tag': tag, }; } async fetchOrderBook (symbol, limit = undefined, params = {}) { await this.loadMarkets (); const marketId = this.marketId (symbol); const request = this.extend ({ 'symbol': marketId, 'level': 2 }, params); const response = await this.publicGetMarketOrderbookLevelLevel (request); // // { sequence: '1547731421688', // asks: [ [ '5c419328ef83c75456bd615c', '0.9', '0.09' ], ... ], // bids: [ [ '5c419328ef83c75456bd615c', '0.9', '0.09' ], ... ], } // const data = response['data']; const timestamp = this.safeInteger (data, 'sequence'); // level can be a string such as 2_20 or 2_100 const levelString = this.safeString (request, 'level'); const levelParts = levelString.split ('_'); const level = parseInt (levelParts[0]); return this.parseOrderBook (data, timestamp, 'bids', 'asks', level - 2, level - 1); } async createOrder (symbol, type, side, amount, price = undefined, params = {}) { await this.loadMarkets (); const marketId = this.marketId (symbol); // required param, cannot be used twice const clientOid = this.uuid (); const request = { 'clientOid': clientOid, 'price': this.priceToPrecision (symbol, price), 'side': side, 'size': this.amountToPrecision (symbol, amount), 'symbol': marketId, 'type': type, }; const response = await this.privatePostOrders (this.extend (request, params)); const responseData = response['data']; return { 'id': responseData['orderId'], 'symbol': symbol, 'type': type, 'side': side, 'status': 'open', 'clientOid': clientOid, 'info': responseData, }; } async cancelOrder (id, symbol = undefined, params = {}) { const request = { 'orderId': id }; const response = this.privateDeleteOrdersOrderId (this.extend (request, params)); return response; } async fetchOrdersByStatus (status, symbol = undefined, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); let request = { 'status': status, }; let market = undefined; if (symbol !== undefined) { market = this.market (symbol); request['symbol'] = market['id']; } if (since !== undefined) { request['startAt'] = since; } if (limit !== undefined) { request['pageSize'] = limit; } const response = await this.privateGetOrders (this.extend (request, params)); const responseData = this.safeValue (response, 'data', {}); const orders = this.safeValue (responseData, 'items', []); return this.parseOrders (orders, market, since, limit); } async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) { return this.fetchOrdersByStatus ('done', symbol, since, limit, params); } async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) { return this.fetchOrdersByStatus ('active', symbol, since, limit, params); } async fetchOrder (id, symbol = undefined, params = {}) { await this.loadMarkets (); const request = { 'orderId': id, }; let market = undefined; if (symbol !== undefined) { market = this.market (symbol); } const response = await this.privateGetOrdersOrderId (this.extend (request, params)); const responseData = response['data']; return this.parseOrder (responseData, market); } parseOrder (order, market = undefined) { // // { "id": "5c35c02703aa673ceec2a168", // "symbol": "BTC-USDT", // "opType": "DEAL", // "type": "limit", // "side": "buy", // "price": "10", // "size": "2", // "funds": "0", // "dealFunds": "0.166", // "dealSize": "2", // "fee": "0", // "feeCurrency": "USDT", // "stp": "", // "stop": "", // "stopTriggered": false, // "stopPrice": "0", // "timeInForce": "GTC", // "postOnly": false, // "hidden": false, // "iceberge": false, // "visibleSize": "0", // "cancelAfter": 0, // "channel": "IOS", // "clientOid": "", // "remark": "", // "tags": "", // "isActive": false, // "cancelExist": false, // "createdAt": 1547026471000 } // let symbol = undefined; const marketId = this.safeString (order, 'symbol'); if (marketId !== undefined) { if (marketId in this.markets_by_id) { market = this.markets_by_id[marketId]; symbol = market['symbol']; } else { const [ baseId, quoteId ] = marketId.split ('-'); const base = this.commonCurrencyCode (baseId); const quote = this.commonCurrencyCode (quoteId); symbol = base + '/' + quote; } market = this.safeValue (this.markets_by_id, marketId); } if (symbol === undefined) { if (market !== undefined) { symbol = market['symbol']; } } const orderId = this.safeString (order, 'id'); const type = this.safeString (order, 'type'); const timestamp = this.safeInteger (order, 'createdAt'); const datetime = this.iso8601 (timestamp); const price = this.safeFloat (order, 'price'); const side = this.safeString (order, 'side'); const feeCurrencyId = this.safeString (order, 'feeCurrency'); const feeCurrency = this.commonCurrencyCode (feeCurrencyId); const feeCost = this.safeFloat (order, 'fee'); const amount = this.safeFloat (order, 'size'); const filled = this.safeFloat (order, 'dealSize'); const cost = this.safeFloat (order, 'dealFunds'); const remaining = amount - filled; // bool const status = order['isActive'] ? 'open' : 'closed'; let fee = { 'currency': feeCurrency, 'cost': feeCost, }; return { 'id': orderId, 'symbol': symbol, 'type': type, 'side': side, 'amount': amount, 'price': price, 'cost': cost, 'filled': filled, 'remaining': remaining, 'timestamp': timestamp, 'datetime': datetime, 'fee': fee, 'status': status, 'info': order, }; } async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); let request = {}; let market = undefined; if (symbol !== undefined) { market = this.market (symbol); request['symbol'] = market['id']; } if (since !== undefined) { request['startAt'] = since; } if (limit !== undefined) { request['pageSize'] = limit; } const response = await this.privateGetFills (this.extend (request, params)); const data = this.safeValue (response, 'data', {}); const trades = this.safeValue (data, 'items', []); return this.parseTrades (trades, market, since, limit); } async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); const market = this.market (symbol); let request = { 'symbol': market['id'], }; if (since !== undefined) { request['startAt'] = Math.floor (since / 1000); } if (limit !== undefined) { request['pageSize'] = limit; } const response = await this.publicGetMarketHistories (this.extend (request, params)); // { // "code": "200000", // "data": [ // { // "sequence": "1548764654235", // "side": "sell", // "size":"0.6841354", // "price":"0.03202", // "time":1548848575203567174 // } // ] // } // const trades = this.safeValue (response, 'data', []); return this.parseTrades (trades, market, since, limit); } parseTrade (trade, market = undefined) { // // fetchTrades (public) // // { // "sequence": "1548764654235", // "side": "sell", // "size":"0.6841354", // "price":"0.03202", // "time":1548848575203567174 // } // // fetchMyTrades (private) // // { // "symbol":"BTC-USDT", // "tradeId":"5c35c02709e4f67d5266954e", // "orderId":"5c35c02703aa673ceec2a168", // "counterOrderId":"5c1ab46003aa676e487fa8e3", // "side":"buy", // "liquidity":"taker", // "forceTaker":true, // "price":"0.083", // "size":"0.8424304", // "funds":"0.0699217232", // "fee":"0", // "feeRate":"0", // "feeCurrency":"USDT", // "stop":"", // "type":"limit", // "createdAt":1547026472000 // } // let symbol = undefined; const marketId = this.safeString (trade, 'symbol'); if (marketId !== undefined) { if (marketId in this.markets_by_id) { market = this.markets_by_id[marketId]; symbol = market['symbol']; } else { const [ baseId, quoteId ] = marketId.split ('-'); const base = this.commonCurrencyCode (baseId); const quote = this.commonCurrencyCode (quoteId); symbol = base + '/' + quote; } market = this.safeValue (this.markets_by_id, marketId); } if (symbol === undefined) { if (market !== undefined) { symbol = market['symbol']; } } let id = this.safeString (trade, 'tradeId'); if (id !== undefined) { id = id.toString (); } const orderId = this.safeString (trade, 'orderId'); const amount = this.safeFloat (trade, 'size'); let timestamp = this.safeInteger (trade, 'time'); if (timestamp !== undefined) { timestamp = parseInt (timestamp / 1000000); } else { timestamp = this.safeInteger (trade, 'createdAt'); } const price = this.safeFloat (trade, 'price'); const side = this.safeString (trade, 'side'); const fee = { 'cost': this.safeFloat (trade, 'fee'), 'rate': this.safeFloat (trade, 'feeRate'), 'currency': this.safeString (trade, 'feeCurrency'), }; const type = this.safeString (trade, 'type'); let cost = this.safeFloat (trade, 'funds'); if (amount !== undefined) { if (price !== undefined) { cost = amount * price; } } return { 'info': trade, 'id': id, 'order': orderId, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'symbol': symbol, 'type': type, 'side': side, 'price': price, 'amount': amount, 'cost': cost, 'fee': fee, }; } async withdraw (code, amount, address, tag = undefined, params = {}) { await this.loadMarkets (); this.checkAddress (address); const currency = this.currencyId (code); let request = { 'currency': currency, 'address': address, 'amount': amount, }; if (tag !== undefined) { request['memo'] = tag; } const response = await this.privatePostWithdrawals (this.extend (request, params)); // // { "withdrawalId": "5bffb63303aa675e8bbe18f9" } // const responseData = response['data']; return { 'id': this.safeString (responseData, 'withdrawalId'), 'info': responseData, }; } parseTransactionStatus (status) { const statuses = { 'SUCCESS': 'ok', 'PROCESSING': 'ok', 'FAILURE': 'failed', }; return this.safeString (statuses, status); } parseTransaction (transaction, currency = undefined) { // // Deposits // { "address": "0x5f047b29041bcfdbf0e4478cdfa753a336ba6989", // "memo": "5c247c8a03aa677cea2a251d", // "amount": 1, // "fee": 0.0001, // "currency": "KCS", // "isInner": false, // "walletTxId": "5bbb57386d99522d9f954c5a@test004", // "status": "SUCCESS", // "createdAt": 1544178843000, // "updatedAt": 1544178891000 } // Withdrawals // { "id": "5c2dc64e03aa675aa263f1ac", // "address": "0x5bedb060b8eb8d823e2414d82acce78d38be7fe9", // "memo": "", // "currency": "ETH", // "amount": 1.0000000, // "fee": 0.0100000, // "walletTxId": "3e2414d82acce78d38be7fe9", // "isInner": false, // "status": "FAILURE", // "createdAt": 1546503758000, // "updatedAt": 1546504603000 } // let code = undefined; let currencyId = this.safeString (transaction, 'currency'); currency = this.safeValue (this.currencies_by_id, currencyId); if (currency !== undefined) { code = currency['code']; } else { code = this.commonCurrencyCode (currencyId); } const address = this.safeString (transaction, 'address'); const amount = this.safeFloat (transaction, 'amount'); const txid = this.safeString (transaction, 'walletTxId'); const type = txid === undefined ? 'withdrawal' : 'deposit'; const rawStatus = this.safeString (transaction, 'status'); const status = this.parseTransactionStatus (rawStatus); let fees = { 'cost': this.safeFloat (transaction, 'fee'), }; if (fees['cost'] !== undefined && amount !== undefined) { fees['rate'] = fees['cost'] / amount; } const tag = this.safeString (transaction, 'memo'); const timestamp = this.safeInteger2 (transaction, 'updatedAt', 'createdAt'); const datetime = this.iso8601 (timestamp); return { 'address': address, 'tag': tag, 'currency': code, 'amount': amount, 'txid': txid, 'type': type, 'status': status, 'fee': fees, 'timestamp': timestamp, 'datetime': datetime, 'info': transaction, }; } async fetchDeposits (code = undefined, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); let request = {}; let currency = undefined; if (code !== undefined) { currency = this.currency (code); request['currency'] = currency['id']; } if (since !== undefined) { request['startAt'] = since; } if (limit !== undefined) { request['pageSize'] = limit; } const response = await this.privateGetDeposits (this.extend (request, params)); // // paginated // { code: '200000', // data: // { totalNum: 0, // totalPage: 0, // pageSize: 10, // currentPage: 1, // items: [...] // } } // const responseData = response['data']['items']; return this.parseTransactions (responseData, currency, since, limit); } async fetchWithdrawals (code = undefined, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); let request = {}; let currency = undefined; if (code !== undefined) { currency = this.currency (code); request['currency'] = currency['id']; } if (since !== undefined) { request['startAt'] = since; } if (limit !== undefined) { request['pageSize'] = limit; } const response = await this.privateGetWithdrawals (this.extend (request, params)); // // paginated // { code: '200000', // data: // { totalNum: 0, // totalPage: 0, // pageSize: 10, // currentPage: 1, // items: [...] } } // const responseData = response['data']['items']; return this.parseTransactions (responseData, currency, since, limit); } async fetchBalance (params = {}) { await this.loadMarkets (); const request = { 'type': 'trade', }; const response = await this.privateGetAccounts (this.extend (request, params)); const responseData = response['data']; let result = { 'info': responseData }; for (let i = 0; i < responseData.length; i++) { const entry = responseData[i]; const currencyId = entry['currency']; const code = this.commonCurrencyCode (currencyId); let account = {}; account['total'] = this.safeFloat (entry, 'balance', 0); account['free'] = this.safeFloat (entry, 'available', 0); account['used'] = this.safeFloat (entry, 'holds', 0); result[code] = account; } return this.parseBalance (result); } sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) { // // the v2 URL is https://openapi-v2.kucoin.com/api/v1/endpoint // † ↑ // let endpoint = '/api/' + this.options['version'] + '/' + this.implodeParams (path, params); let query = this.omit (params, this.extractParams (path)); let endpart = ''; headers = headers !== undefined ? headers : {}; if (Object.keys (query).length) { if (method !== 'GET') { body = this.json (query); endpart = body; headers['Content-Type'] = 'application/json'; } else { endpoint += '?' + this.urlencode (query); } } let url = this.urls['api'][api] + endpoint; if (api === 'private') { this.checkRequiredCredentials (); const timestamp = this.nonce ().toString (); headers = this.extend ({ 'KC-API-KEY': this.apiKey, 'KC-API-TIMESTAMP': timestamp, 'KC-API-PASSPHRASE': this.password, }, headers); const payload = timestamp + method + endpoint + endpart; const signature = this.hmac (this.encode (payload), this.encode (this.secret), 'sha256', 'base64'); headers['KC-API-SIGN'] = this.decode (signature); } return { 'url': url, 'method': method, 'body': body, 'headers': headers }; } handleErrors (code, reason, url, method, headers, body, response) { if (!response) { return; } // // bad // { "code": "400100", "msg": "validation.createOrder.clientOidIsRequired" } // good // { code: '200000', data: { ... }} // let errorCode = this.safeString (response, 'code'); if (errorCode in this.exceptions) { const message = this.safeString (response, 'msg', ''); if (message === 'order_not_exist_or_not_allow_to_cancel') { throw new InvalidOrder (this.id + ' ' + message); } let Exception = this.exceptions[errorCode]; throw new Exception (this.id + ' ' + message); } } };
kucoin2 cancel order exception rewrite
js/kucoin2.js
kucoin2 cancel order exception rewrite
<ide><path>s/kucoin2.js <ide> '411100': AccountSuspended, <ide> '500000': ExchangeError, <ide> 'order_not_exist': OrderNotFound, // {"code":"order_not_exist","msg":"order_not_exist"} ¯\_(ツ)_/¯ <add> 'order_not_exist_or_not_allow_to_cancel': InvalidOrder, <ide> }, <ide> 'fees': { <ide> 'trading': { <ide> // { code: '200000', data: { ... }} <ide> // <ide> let errorCode = this.safeString (response, 'code'); <del> if (errorCode in this.exceptions) { <del> const message = this.safeString (response, 'msg', ''); <del> if (message === 'order_not_exist_or_not_allow_to_cancel') { <del> throw new InvalidOrder (this.id + ' ' + message); <del> } <del> let Exception = this.exceptions[errorCode]; <del> throw new Exception (this.id + ' ' + message); <add> let message = this.safeString (response, 'msg', ''); <add> let ExceptionClass = this.safeValue2 (this.exceptions, message, errorCode); <add> if (ExceptionClass !== undefined) { <add> throw new ExceptionClass (this.id + ' ' + message); <ide> } <ide> } <ide> };
Java
apache-2.0
bc1aa5b4c64696a650800888c29d9b02c2306968
0
daniellemayne/dasein-cloud-google,greese/dasein-cloud-google,unwin/dasein-cloud-google,daniellemayne/dasein-cloud-google_old,dasein-cloud/dasein-cloud-google
/** * Copyright (C) 2009-2014 Dell, Inc. * See annotations for authorship information * * ==================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ package org.dasein.cloud.google.network; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.log4j.Logger; import org.dasein.cloud.CloudErrorType; import org.dasein.cloud.CloudException; import org.dasein.cloud.InternalException; import org.dasein.cloud.OperationNotSupportedException; import org.dasein.cloud.ProviderContext; import org.dasein.cloud.ResourceStatus; import org.dasein.cloud.compute.VirtualMachine; import org.dasein.cloud.google.Google; import org.dasein.cloud.google.GoogleException; import org.dasein.cloud.google.GoogleMethod; import org.dasein.cloud.google.GoogleOperationType; import org.dasein.cloud.google.capabilities.GCELoadBalancerCapabilities; import org.dasein.cloud.network.AbstractLoadBalancerSupport; import org.dasein.cloud.network.HealthCheckFilterOptions; import org.dasein.cloud.network.HealthCheckOptions; import org.dasein.cloud.network.IPVersion; import org.dasein.cloud.network.LbAlgorithm; import org.dasein.cloud.network.LbEndpointState; import org.dasein.cloud.network.LbEndpointType; import org.dasein.cloud.network.LbListener; import org.dasein.cloud.network.LbPersistence; import org.dasein.cloud.network.LbProtocol; import org.dasein.cloud.network.LbType; import org.dasein.cloud.network.LoadBalancer; import org.dasein.cloud.network.LoadBalancerAddressType; import org.dasein.cloud.network.LoadBalancerCapabilities; import org.dasein.cloud.network.LoadBalancerCreateOptions; import org.dasein.cloud.network.LoadBalancerEndpoint; import org.dasein.cloud.network.LoadBalancerHealthCheck; import org.dasein.cloud.network.LoadBalancerHealthCheck.HCProtocol; import org.dasein.cloud.network.LoadBalancerState; import org.dasein.cloud.util.APITrace; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.services.compute.Compute; import com.google.api.services.compute.Compute.TargetPools.AddHealthCheck; import com.google.api.services.compute.model.ForwardingRule; import com.google.api.services.compute.model.ForwardingRuleList; import com.google.api.services.compute.model.HealthCheckReference; import com.google.api.services.compute.model.HttpHealthCheck; import com.google.api.services.compute.model.InstanceReference; import com.google.api.services.compute.model.Operation; import com.google.api.services.compute.model.TargetPool; import com.google.api.services.compute.model.TargetPoolList; import com.google.api.services.compute.model.TargetPoolsAddHealthCheckRequest; import com.google.api.services.compute.model.TargetPoolsAddInstanceRequest; import com.google.api.services.compute.model.TargetPoolsRemoveInstanceRequest; /** * @author Roger Unwin * */ public class LoadBalancerSupport extends AbstractLoadBalancerSupport<Google> { static private final Logger logger = Logger.getLogger(AbstractLoadBalancerSupport.class); private volatile transient GCELoadBalancerCapabilities capabilities; private Google provider = null; private ProviderContext ctx = null; private Compute gce = null; public LoadBalancerSupport(Google provider) { super(provider); this.provider = provider; ctx = provider.getContext(); } @Override public boolean isDataCenterLimited() { return false; } @Nonnull public LoadBalancerCapabilities getCapabilities() throws CloudException, InternalException { if( capabilities == null ) { capabilities = new GCELoadBalancerCapabilities(provider); } return capabilities; } @Override public String getProviderTermForLoadBalancer(Locale locale) { return "target pool"; } @Override public boolean isSubscribed() throws CloudException, InternalException { return true; } @Override public void removeLoadBalancer(@Nonnull String loadBalancerId) throws CloudException, InternalException { APITrace.begin(provider, "LB.removeLoadBalancer"); gce = provider.getGoogleCompute(); List<String> forwardingRuleNames = getForwardingRule(loadBalancerId); for (String forwardingRuleName : forwardingRuleNames) if (forwardingRuleName != null) removeLoadBalancerForwardingRule(forwardingRuleName); String healthCheckName = getLoadBalancerHealthCheckName(loadBalancerId); try { Operation job = gce.targetPools().delete(ctx.getAccountNumber(), ctx.getRegionId(), loadBalancerId).execute(); GoogleMethod method = new GoogleMethod(provider); method.getOperationComplete(ctx, job, GoogleOperationType.REGION_OPERATION, ctx.getRegionId(), ""); if (healthCheckName != null) removeLoadBalancerHealthCheck(healthCheckName); } catch (CloudException e) { throw new CloudException(e); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } } public String getLoadBalancerHealthCheckName(@Nonnull String loadBalancerId) throws CloudException, InternalException { gce = provider.getGoogleCompute(); TargetPool tp; try { tp = gce.targetPools().get(ctx.getAccountNumber(), ctx.getRegionId(), loadBalancerId).execute(); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } List<String> hcs = tp.getHealthChecks(); String healthCheck = null; if ((hcs != null) && (hcs.size() > 0)) { healthCheck = hcs.get(0); healthCheck = healthCheck.substring(healthCheck.lastIndexOf("/") + 1); } return healthCheck; } private List<String> getForwardingRule(String targetPoolName) throws CloudException, InternalException { APITrace.begin(provider, "LB.getForwardingRule"); gce = provider.getGoogleCompute(); List<String> forwardingRuleNames = new ArrayList<String>(); try { ForwardingRuleList result = gce.forwardingRules().list(ctx.getAccountNumber(), ctx.getRegionId()).execute(); if (result != null) for (ForwardingRule fr : result.getItems()) { String forwardingRuleTarget = fr.getTarget(); forwardingRuleTarget = forwardingRuleTarget.substring(forwardingRuleTarget.lastIndexOf("/") + 1); if (targetPoolName.equals(forwardingRuleTarget)) forwardingRuleNames.add(fr.getName()); } } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } return forwardingRuleNames; } private void removeLoadBalancerForwardingRule(String forwardingRuleName) throws CloudException, InternalException { APITrace.begin(provider, "LB.removeLoadBalancerForwardingRule"); gce = provider.getGoogleCompute(); try { Operation job = gce.forwardingRules().delete(ctx.getAccountNumber(), ctx.getRegionId(), forwardingRuleName).execute(); GoogleMethod method = new GoogleMethod(provider); method.getOperationComplete(ctx, job, GoogleOperationType.REGION_OPERATION, ctx.getRegionId(), ""); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } } @Override public @Nonnull String createLoadBalancer(@Nonnull LoadBalancerCreateOptions options) throws CloudException, InternalException { APITrace.begin(provider, "LB.create"); gce = provider.getGoogleCompute(); try { TargetPool tp = new TargetPool(); tp.setRegion(ctx.getRegionId()); tp.setName(options.getName()); tp.setInstances(null); try { GoogleMethod method = new GoogleMethod(provider); Operation job = gce.targetPools().insert(ctx.getAccountNumber(), ctx.getRegionId(), tp).execute(); boolean result = method.getOperationComplete(ctx, job, GoogleOperationType.REGION_OPERATION, ctx.getRegionId(), ""); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } HealthCheckOptions hco = options.getHealthCheckOptions(); if (hco != null) { LoadBalancerHealthCheck hc = createLoadBalancerHealthCheck(hco.getName(), hco.getDescription(), hco.getHost(), hco.getProtocol(), hco.getPort(), hco.getPath(), hco.getInterval(), hco.getTimeout(), hco.getHealthyCount(), hco.getUnhealthyCount()); attachHealthCheckToLoadBalancer(options.getName(), options.getHealthCheckOptions().getName()); } createLoadBalancerForwardingRule(options); return options.getName(); } finally { APITrace.end(); } } void createLoadBalancerForwardingRule(@Nonnull LoadBalancerCreateOptions options) throws CloudException, InternalException { APITrace.begin(provider, "LB.createLoadBalancerForwardingRule"); gce = provider.getGoogleCompute(); LbListener[] listeners = options.getListeners(); String targetPoolSelfLink = null; try { TargetPool tp = gce.targetPools().get(ctx.getAccountNumber(), ctx.getRegionId(), options.getName()).execute(); targetPoolSelfLink = tp.getSelfLink(); if (listeners.length > 0) { // listeners specified int index = 0; for ( LbListener listener : listeners) { ForwardingRule forwardingRule = new ForwardingRule(); if (listeners.length > 1) forwardingRule.setName(options.getName() + "-" + index++); else forwardingRule.setName(options.getName()); forwardingRule.setDescription(options.getDescription()); //forwardingRule.setKind("compute#forwardingRule"); forwardingRule.setIPAddress(options.getProviderIpAddressId()); forwardingRule.setIPProtocol("TCP"); forwardingRule.setPortRange("" + listener.getPublicPort()); forwardingRule.setRegion(ctx.getRegionId()); forwardingRule.setTarget(targetPoolSelfLink); Operation result = gce.forwardingRules().insert(ctx.getAccountNumber(), ctx.getRegionId(), forwardingRule).execute(); } } else { // no listeners specified, default to ephemeral, all ports, TCP ForwardingRule forwardingRule = new ForwardingRule(); forwardingRule.setName(options.getName()); forwardingRule.setDescription("Default Forwarding Rule"); //forwardingRule.setKind("compute#forwardingRule"); //forwardingRule.setIPAddress(""); forwardingRule.setIPProtocol("TCP"); forwardingRule.setPortRange( "1-65535"); forwardingRule.setRegion(ctx.getRegionId()); forwardingRule.setTarget(targetPoolSelfLink); GoogleMethod method = new GoogleMethod(provider); Operation job = gce.forwardingRules().insert(ctx.getAccountNumber(), ctx.getRegionId(), forwardingRule).execute(); boolean result = method.getOperationComplete(ctx, job, GoogleOperationType.REGION_OPERATION, ctx.getRegionId(), ""); } } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } } @Override public LoadBalancerHealthCheck createLoadBalancerHealthCheck(@Nonnull HealthCheckOptions options) throws CloudException, InternalException{ return createLoadBalancerHealthCheck( options.getName(), options.getDescription(), options.getHost(), LoadBalancerHealthCheck.HCProtocol.HTTP, options.getPort(), options.getPath(), options.getInterval(), options.getTimeout(), options.getHealthyCount(), options.getUnhealthyCount()); } @Override public LoadBalancerHealthCheck createLoadBalancerHealthCheck(@Nullable String name, @Nullable String description, @Nullable String host, @Nullable LoadBalancerHealthCheck.HCProtocol protocol, int port, @Nullable String path, int interval, int timeout, int healthyCount, int unhealthyCount) throws CloudException, InternalException{ APITrace.begin(provider, "LB.createLoadBalancerHealthCheck"); gce = provider.getGoogleCompute(); HttpHealthCheck hc = new HttpHealthCheck(); try { hc.setName(name); hc.setDescription(description); hc.setHost(host); // protocol hc.setPort(port); hc.setRequestPath(path); hc.setCheckIntervalSec(interval); hc.setTimeoutSec(timeout); hc.setHealthyThreshold(healthyCount); hc.setUnhealthyThreshold(unhealthyCount); GoogleMethod method = new GoogleMethod(provider); Operation job = gce.httpHealthChecks().insert(ctx.getAccountNumber(), hc).execute(); boolean result = method.getOperationComplete(ctx, job, GoogleOperationType.GLOBAL_OPERATION, ctx.getRegionId(), ""); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } return getLoadBalancerHealthCheck(name); } @Override public void attachHealthCheckToLoadBalancer(@Nonnull String providerLoadBalancerId, @Nonnull String providerLBHealthCheckId)throws CloudException, InternalException{ APITrace.begin(provider, "LB.attachHealthCheckToLoadBalancer"); gce = provider.getGoogleCompute(); HttpHealthCheck hc = null; try { hc = (gce.httpHealthChecks().get(ctx.getAccountNumber(), providerLBHealthCheckId)).execute(); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } ArrayList <HealthCheckReference>hcl = new ArrayList<HealthCheckReference>(); HealthCheckReference hcr = new HealthCheckReference(); hcr.setHealthCheck(hc.getSelfLink()); hcl.add(hcr); TargetPoolsAddHealthCheckRequest tphcr = new TargetPoolsAddHealthCheckRequest(); tphcr.setHealthChecks(hcl); try { AddHealthCheck op = gce.targetPools().addHealthCheck(ctx.getAccountNumber(), ctx.getRegionId(), providerLoadBalancerId, tphcr); Operation result = op.execute(); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } } public LoadBalancerHealthCheck toLoadBalancerHealthCheck(String loadBalancerName, HttpHealthCheck hc) throws CloudException, InternalException { if (loadBalancerName == null) throw new InternalException("loadBalancerName was null. Name is required"); if (hc == null) throw new InternalException("HttpHealthCheck was null"); Integer port = -1; if (hc.getPort() != null) port = hc.getPort(); Integer checkIntervalSecond = -1; if (hc.getCheckIntervalSec() != null) checkIntervalSecond = hc.getCheckIntervalSec(); Integer timeoutSec = -1; if (hc.getTimeoutSec() != null) timeoutSec = hc.getTimeoutSec(); Integer healthyThreshold = -1; if (hc.getHealthyThreshold() != null) healthyThreshold = hc.getHealthyThreshold(); Integer unhealthyThreshold = -1; if (hc.getUnhealthyThreshold() != null) unhealthyThreshold = hc.getUnhealthyThreshold(); LoadBalancerHealthCheck lbhc = LoadBalancerHealthCheck.getInstance( loadBalancerName, hc.getName(), hc.getDescription(), hc.getHost(), HCProtocol.TCP, port, hc.getRequestPath(), checkIntervalSecond, timeoutSec, healthyThreshold, unhealthyThreshold); lbhc.addProviderLoadBalancerId(loadBalancerName); return lbhc; } /* * Inventory Load Balancers and list their associated Health Checks. * Caveat, will only show FIRST health check */ @Override public Iterable<LoadBalancerHealthCheck> listLBHealthChecks(@Nullable HealthCheckFilterOptions opts) throws CloudException, InternalException { APITrace.begin(provider, "LB.listLBHealthChecks"); gce = provider.getGoogleCompute(); ArrayList<LoadBalancerHealthCheck> lbhc = new ArrayList<LoadBalancerHealthCheck>(); try { TargetPoolList tpl = gce.targetPools().list(ctx.getAccountNumber(), ctx.getRegionId()).execute(); if ((tpl != null) && (tpl.getItems() != null)) { Iterator<TargetPool> loadBalancers = tpl.getItems().iterator(); while (loadBalancers.hasNext()) { TargetPool lb = loadBalancers.next(); String loadBalancerName = lb.getName(); List<String> hcs = lb.getHealthChecks(); if ((hcs != null) && (!hcs.isEmpty())) { String healthCheckName = hcs.get(0); if (healthCheckName != null) { healthCheckName = healthCheckName.substring(healthCheckName.lastIndexOf("/") + 1); HttpHealthCheck hc = gce.httpHealthChecks().get(ctx.getAccountNumber(), healthCheckName).execute(); LoadBalancerHealthCheck healthCheckItem = toLoadBalancerHealthCheck(loadBalancerName, hc); lbhc.add(healthCheckItem); } } } } } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } return lbhc; } @Override public void removeLoadBalancerHealthCheck(@Nonnull String providerLoadBalancerId) throws CloudException, InternalException{ APITrace.begin(provider, "LB.removeLoadBalancerHealthCheck"); gce = provider.getGoogleCompute(); try { Operation job = (gce.httpHealthChecks().delete(ctx.getAccountNumber(), providerLoadBalancerId)).execute(); GoogleMethod method = new GoogleMethod(provider); method.getOperationComplete(ctx, job, GoogleOperationType.GLOBAL_OPERATION, ctx.getRegionId(), ""); // Causes CloudException if HC still in use. } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } } @Override public LoadBalancerHealthCheck modifyHealthCheck(@Nonnull String providerLBHealthCheckId, @Nonnull HealthCheckOptions options) throws InternalException, CloudException{ APITrace.begin(provider, "LB.modifyHealthCheck"); gce = provider.getGoogleCompute(); HttpHealthCheck hc = null; try { hc = (gce.httpHealthChecks().get(ctx.getAccountNumber(), providerLBHealthCheckId)).execute(); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } if ((options.getName() != null) && (!options.getName().equals(providerLBHealthCheckId))) throw new CloudException("Cannot rename loadbalancer health checks in GCE"); if (options.getDescription() != null) hc.setDescription(options.getDescription()); if (options.getHost() != null) hc.setHost(options.getHost()); hc.setRequestPath(options.getPath()); // TODO: Is protocol to be supported? hc.setPort(options.getPort()); hc.setCheckIntervalSec(options.getInterval()); hc.setTimeoutSec(options.getTimeout()); hc.setHealthyThreshold(options.getHealthyCount()); hc.setUnhealthyThreshold(options.getUnhealthyCount()); try { Operation op = gce.httpHealthChecks().update(ctx.getAccountNumber(), providerLBHealthCheckId, hc).execute(); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } return getLoadBalancerHealthCheck(providerLBHealthCheckId); } @Override public LoadBalancerHealthCheck getLoadBalancerHealthCheck(@Nullable String providerLBHealthCheckId, @Nullable String providerLoadBalancerId)throws CloudException, InternalException{ return getLoadBalancerHealthCheck(providerLBHealthCheckId); } public LoadBalancerHealthCheck getLoadBalancerHealthCheck(@Nullable String providerLBHealthCheckId)throws CloudException, InternalException{ APITrace.begin(provider, "LB.getLoadBalancerHealthCheck"); gce = provider.getGoogleCompute(); HttpHealthCheck hc = null; LoadBalancerHealthCheck lbhc = null; try { hc = (gce.httpHealthChecks().get(ctx.getAccountNumber(), providerLBHealthCheckId)).execute(); lbhc = toLoadBalancerHealthCheck(providerLBHealthCheckId, hc); //lbhc.addProviderLoadBalancerId(hc.getName()); } catch (NullPointerException e) { // not found, return null } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } return lbhc; } @Override public @Nullable LoadBalancer getLoadBalancer(@Nonnull String loadBalancerId) throws CloudException, InternalException { APITrace.begin(provider, "LB.getLoadBalancer"); gce = provider.getGoogleCompute(); LoadBalancer lb = null; try { TargetPool tp = gce.targetPools().get(ctx.getAccountNumber(), ctx.getRegionId(), loadBalancerId).execute(); lb = toLoadBalancer(tp); } catch (Exception e) { lb = null; } finally { APITrace.end(); } return lb; } @Override public void addServers(@Nonnull String toLoadBalancerId, @Nonnull String ... serverIdsToAdd) throws CloudException, InternalException { APITrace.begin(provider, "LB.addServers"); gce = provider.getGoogleCompute(); String vmRegion = null; try { List<InstanceReference> instances = new ArrayList<InstanceReference>(); for (String server : serverIdsToAdd) { VirtualMachine vm = provider.getComputeServices().getVirtualMachineSupport().getVirtualMachine(server); vmRegion = vm.getProviderRegionId(); instances.add(new InstanceReference().setInstance((String) vm.getTag("contentLink"))); } gce.targetPools().addInstance(ctx.getAccountNumber(), vmRegion, toLoadBalancerId, new TargetPoolsAddInstanceRequest().setInstances(instances)).execute(); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } } @Override public void removeServers(@Nonnull String fromLoadBalancerId, @Nonnull String ... serverIdsToRemove) throws CloudException, InternalException { APITrace.begin(provider, "LB.removeServers"); gce = provider.getGoogleCompute(); List<InstanceReference> replacementInstances = new ArrayList<InstanceReference>(); try { TargetPool tp = gce.targetPools().get(ctx.getAccountNumber(), ctx.getRegionId(), fromLoadBalancerId).execute(); List<String> instances = tp.getInstances(); for (String i : instances) for (String serverToRemove : serverIdsToRemove) if (i.endsWith(serverToRemove)) replacementInstances.add(new InstanceReference().setInstance(i)); TargetPoolsRemoveInstanceRequest content = new TargetPoolsRemoveInstanceRequest(); content.setInstances(replacementInstances); gce.targetPools().removeInstance(ctx.getAccountNumber(), ctx.getRegionId(), fromLoadBalancerId, content).execute(); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } } @Override public @Nonnull Iterable<LoadBalancerEndpoint> listEndpoints(@Nonnull String forLoadBalancerId) throws CloudException, InternalException { APITrace.begin(provider, "LB.listEndpoints"); gce = provider.getGoogleCompute(); TargetPool tp = null; try { tp = gce.targetPools().get(ctx.getAccountNumber(), ctx.getRegionId(), forLoadBalancerId).execute(); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } try { ArrayList<LoadBalancerEndpoint> list = new ArrayList<LoadBalancerEndpoint>(); List<String> instances = tp.getInstances(); if (instances != null) for (String instance : instances) list.add(LoadBalancerEndpoint.getInstance(LbEndpointType.VM, instance.substring(1 + instance.lastIndexOf("/")), LbEndpointState.ACTIVE)); return list; } finally { APITrace.end(); } } @Override public @Nonnull Iterable<ResourceStatus> listLoadBalancerStatus() throws CloudException, InternalException { APITrace.begin(provider, "LB.listLoadBalancers"); gce = provider.getGoogleCompute(); ArrayList<ResourceStatus> list = new ArrayList<ResourceStatus>(); try { TargetPoolList tpl = gce.targetPools().list(ctx.getAccountNumber(), ctx.getRegionId()).execute(); if (tpl.getItems() != null) { Iterator<TargetPool> loadBalancers = tpl.getItems().iterator(); while (loadBalancers.hasNext()) { TargetPool lb = loadBalancers.next(); List<String> healthChecks = lb.getHealthChecks(); for (String healthCheckName : healthChecks) { healthCheckName = healthCheckName.substring(healthCheckName.lastIndexOf("/") + 1); LoadBalancerHealthCheck healthCheck = getLoadBalancerHealthCheck(healthCheckName); list.add(new ResourceStatus(lb.getName(), "UNKNOWN")); } } } return list; } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } } @Override public @Nonnull Iterable<LoadBalancer> listLoadBalancers() throws CloudException, InternalException { APITrace.begin(provider, "LB.listLoadBalancers"); gce = provider.getGoogleCompute(); ArrayList<LoadBalancer> list = new ArrayList<LoadBalancer>(); try { TargetPoolList tpl = gce.targetPools().list(ctx.getAccountNumber(), ctx.getRegionId()).execute(); List<TargetPool> x = tpl.getItems(); if (tpl.getItems() != null) { Iterator<TargetPool> loadBalancers = tpl.getItems().iterator(); while (loadBalancers.hasNext()) { TargetPool lb = loadBalancers.next(); LoadBalancer loadBalancer = toLoadBalancer(lb); if( loadBalancer != null ) { list.add(loadBalancer); } } } return list; } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } } private LoadBalancer toLoadBalancer(TargetPool tp) throws CloudException, InternalException { gce = provider.getGoogleCompute(); List<String> hcl = tp.getHealthChecks(); String healthCheckName = null; if ((hcl != null) && (!hcl.isEmpty())) { healthCheckName = hcl.get(0); healthCheckName = healthCheckName.substring(healthCheckName.lastIndexOf("/") + 1); } long created = 0; try { created = provider.parseTime(tp.getCreationTimestamp()); } catch (CloudException e) { throw new CloudException(e); } ForwardingRule fr = null; String forwardingRuleAddress = null; String forwardingRulePortRange = null; int ports[] = null; List<LbListener> listeners = new ArrayList<LbListener>(); try { List<String> forwardingRuleNames = getForwardingRule(tp.getName()); for (String forwardingRuleName : forwardingRuleNames) { fr = gce.forwardingRules().get(ctx.getAccountNumber(), ctx.getRegionId(), forwardingRuleName).execute(); forwardingRuleAddress = fr.getIPAddress(); //foreardingRuleProtocol = fr.getIPProtocol(); forwardingRulePortRange = fr.getPortRange(); ports = portsToRange(forwardingRulePortRange); String protocol = fr.getIPProtocol(); if (protocol.equals("TCP")) protocol = "RAW_TCP"; for (int port : ports) // Hard Coded Algorithm and persistence, havent found a dynamic source yet. listeners.add(LbListener.getInstance(LbAlgorithm.SOURCE, LbPersistence.SUBNET, LbProtocol.valueOf(protocol), port, port)); } } catch (IOException e) { // Guess no forwarding rules for this one. } String region = tp.getRegion(); region = region.substring(region.lastIndexOf("/") + 1); LoadBalancer lb = LoadBalancer.getInstance( ctx.getAccountNumber(), region, tp.getName(), LoadBalancerState.ACTIVE, tp.getName(), tp.getDescription(), LbType.EXTERNAL, LoadBalancerAddressType.DNS, forwardingRuleAddress, healthCheckName, // TODO: need to modify setProviderLBHealthCheckId to accept lists or arrays ports ).supportingTraffic(IPVersion.IPV4).createdAt(created); LbListener LBListeners[] = new LbListener[listeners.size()]; LBListeners = listeners.toArray(LBListeners); if (!listeners.isEmpty()) lb = lb.withListeners(LBListeners); return lb; } private int[] portsToRange(String portRange) { int[] ports; if (portRange.contains("-")) { String[] parts = portRange.split("-"); int start = new Integer(parts[0]); int end = new Integer(parts[1]); ports = new int[(1 + end - start)]; for (int x = 0; x< (1 + end - start); x++) { ports[x] = start + x; } } else ports = new int[]{new Integer(portRange)}; return ports; } }
src/main/java/org/dasein/cloud/google/network/LoadBalancerSupport.java
/** * Copyright (C) 2009-2014 Dell, Inc. * See annotations for authorship information * * ==================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ package org.dasein.cloud.google.network; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.log4j.Logger; import org.dasein.cloud.CloudErrorType; import org.dasein.cloud.CloudException; import org.dasein.cloud.InternalException; import org.dasein.cloud.OperationNotSupportedException; import org.dasein.cloud.ProviderContext; import org.dasein.cloud.ResourceStatus; import org.dasein.cloud.compute.VirtualMachine; import org.dasein.cloud.google.Google; import org.dasein.cloud.google.GoogleException; import org.dasein.cloud.google.GoogleMethod; import org.dasein.cloud.google.GoogleOperationType; import org.dasein.cloud.google.capabilities.GCELoadBalancerCapabilities; import org.dasein.cloud.network.AbstractLoadBalancerSupport; import org.dasein.cloud.network.HealthCheckFilterOptions; import org.dasein.cloud.network.HealthCheckOptions; import org.dasein.cloud.network.IPVersion; import org.dasein.cloud.network.LbAlgorithm; import org.dasein.cloud.network.LbEndpointState; import org.dasein.cloud.network.LbEndpointType; import org.dasein.cloud.network.LbListener; import org.dasein.cloud.network.LbPersistence; import org.dasein.cloud.network.LbProtocol; import org.dasein.cloud.network.LbType; import org.dasein.cloud.network.LoadBalancer; import org.dasein.cloud.network.LoadBalancerAddressType; import org.dasein.cloud.network.LoadBalancerCapabilities; import org.dasein.cloud.network.LoadBalancerCreateOptions; import org.dasein.cloud.network.LoadBalancerEndpoint; import org.dasein.cloud.network.LoadBalancerHealthCheck; import org.dasein.cloud.network.LoadBalancerHealthCheck.HCProtocol; import org.dasein.cloud.network.LoadBalancerState; import org.dasein.cloud.util.APITrace; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.services.compute.Compute; import com.google.api.services.compute.Compute.TargetPools.AddHealthCheck; import com.google.api.services.compute.model.ForwardingRule; import com.google.api.services.compute.model.ForwardingRuleList; import com.google.api.services.compute.model.HealthCheckReference; import com.google.api.services.compute.model.HttpHealthCheck; import com.google.api.services.compute.model.InstanceReference; import com.google.api.services.compute.model.Operation; import com.google.api.services.compute.model.TargetPool; import com.google.api.services.compute.model.TargetPoolList; import com.google.api.services.compute.model.TargetPoolsAddHealthCheckRequest; import com.google.api.services.compute.model.TargetPoolsAddInstanceRequest; import com.google.api.services.compute.model.TargetPoolsRemoveInstanceRequest; /** * @author Roger Unwin * */ public class LoadBalancerSupport extends AbstractLoadBalancerSupport<Google> { static private final Logger logger = Logger.getLogger(AbstractLoadBalancerSupport.class); private volatile transient GCELoadBalancerCapabilities capabilities; private Google provider = null; private ProviderContext ctx = null; private Compute gce = null; public LoadBalancerSupport(Google provider) { super(provider); this.provider = provider; ctx = provider.getContext(); } @Override public boolean isDataCenterLimited() { return false; } @Nonnull public LoadBalancerCapabilities getCapabilities() throws CloudException, InternalException { if( capabilities == null ) { capabilities = new GCELoadBalancerCapabilities(provider); } return capabilities; } @Override public String getProviderTermForLoadBalancer(Locale locale) { return "target pool"; } @Override public boolean isSubscribed() throws CloudException, InternalException { return true; } @Override public void removeLoadBalancer(@Nonnull String loadBalancerId) throws CloudException, InternalException { APITrace.begin(provider, "LB.removeLoadBalancer"); gce = provider.getGoogleCompute(); List<String> forwardingRuleNames = getForwardingRule(loadBalancerId); for (String forwardingRuleName : forwardingRuleNames) if (forwardingRuleName != null) removeLoadBalancerForwardingRule(forwardingRuleName); String healthCheckName = getLoadBalancerHealthCheckName(loadBalancerId); try { Operation job = gce.targetPools().delete(ctx.getAccountNumber(), ctx.getRegionId(), loadBalancerId).execute(); GoogleMethod method = new GoogleMethod(provider); method.getOperationComplete(ctx, job, GoogleOperationType.REGION_OPERATION, ctx.getRegionId(), ""); if (healthCheckName != null) removeLoadBalancerHealthCheck(healthCheckName); } catch (CloudException e) { throw new CloudException(e); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } } public String getLoadBalancerHealthCheckName(@Nonnull String loadBalancerId) throws CloudException, InternalException { gce = provider.getGoogleCompute(); TargetPool tp; try { tp = gce.targetPools().get(ctx.getAccountNumber(), ctx.getRegionId(), loadBalancerId).execute(); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } List<String> hcs = tp.getHealthChecks(); String healthCheck = null; if ((hcs != null) && (hcs.size() > 0)) { healthCheck = hcs.get(0); healthCheck = healthCheck.substring(healthCheck.lastIndexOf("/") + 1); } return healthCheck; } private List<String> getForwardingRule(String targetPoolName) throws CloudException, InternalException { APITrace.begin(provider, "LB.getForwardingRule"); gce = provider.getGoogleCompute(); List<String> forwardingRuleNames = new ArrayList<String>(); try { ForwardingRuleList result = gce.forwardingRules().list(ctx.getAccountNumber(), ctx.getRegionId()).execute(); for (ForwardingRule fr : result.getItems()) { String forwardingRuleTarget = fr.getTarget(); forwardingRuleTarget = forwardingRuleTarget.substring(forwardingRuleTarget.lastIndexOf("/") + 1); if (targetPoolName.equals(forwardingRuleTarget)) forwardingRuleNames.add(fr.getName()); } } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } return forwardingRuleNames; } private void removeLoadBalancerForwardingRule(String forwardingRuleName) throws CloudException, InternalException { APITrace.begin(provider, "LB.removeLoadBalancerForwardingRule"); gce = provider.getGoogleCompute(); try { Operation job = gce.forwardingRules().delete(ctx.getAccountNumber(), ctx.getRegionId(), forwardingRuleName).execute(); GoogleMethod method = new GoogleMethod(provider); method.getOperationComplete(ctx, job, GoogleOperationType.REGION_OPERATION, ctx.getRegionId(), ""); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } } @Override public @Nonnull String createLoadBalancer(@Nonnull LoadBalancerCreateOptions options) throws CloudException, InternalException { APITrace.begin(provider, "LB.create"); gce = provider.getGoogleCompute(); try { TargetPool tp = new TargetPool(); tp.setRegion(ctx.getRegionId()); tp.setName(options.getName()); tp.setInstances(null); try { GoogleMethod method = new GoogleMethod(provider); Operation job = gce.targetPools().insert(ctx.getAccountNumber(), ctx.getRegionId(), tp).execute(); boolean result = method.getOperationComplete(ctx, job, GoogleOperationType.REGION_OPERATION, ctx.getRegionId(), ""); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } HealthCheckOptions hco = options.getHealthCheckOptions(); if (hco != null) { LoadBalancerHealthCheck hc = createLoadBalancerHealthCheck(hco.getName(), hco.getDescription(), hco.getHost(), hco.getProtocol(), hco.getPort(), hco.getPath(), hco.getInterval(), hco.getTimeout(), hco.getHealthyCount(), hco.getUnhealthyCount()); attachHealthCheckToLoadBalancer(options.getName(), options.getHealthCheckOptions().getName()); } createLoadBalancerForwardingRule(options); return options.getName(); } finally { APITrace.end(); } } void createLoadBalancerForwardingRule(@Nonnull LoadBalancerCreateOptions options) throws CloudException, InternalException { APITrace.begin(provider, "LB.createLoadBalancerForwardingRule"); gce = provider.getGoogleCompute(); LbListener[] listeners = options.getListeners(); String targetPoolSelfLink = null; try { TargetPool tp = gce.targetPools().get(ctx.getAccountNumber(), ctx.getRegionId(), options.getName()).execute(); targetPoolSelfLink = tp.getSelfLink(); if (listeners.length > 0) { // listeners specified int index = 0; for ( LbListener listener : listeners) { ForwardingRule forwardingRule = new ForwardingRule(); if (listeners.length > 1) forwardingRule.setName(options.getName() + "-" + index++); else forwardingRule.setName(options.getName()); forwardingRule.setDescription(options.getDescription()); //forwardingRule.setKind("compute#forwardingRule"); forwardingRule.setIPAddress(options.getProviderIpAddressId()); forwardingRule.setIPProtocol("TCP"); forwardingRule.setPortRange("" + listener.getPublicPort()); forwardingRule.setRegion(ctx.getRegionId()); forwardingRule.setTarget(targetPoolSelfLink); Operation result = gce.forwardingRules().insert(ctx.getAccountNumber(), ctx.getRegionId(), forwardingRule).execute(); } } else { // no listeners specified, default to ephemeral, all ports, TCP ForwardingRule forwardingRule = new ForwardingRule(); forwardingRule.setName(options.getName()); forwardingRule.setDescription("Default Forwarding Rule"); //forwardingRule.setKind("compute#forwardingRule"); //forwardingRule.setIPAddress(""); forwardingRule.setIPProtocol("TCP"); forwardingRule.setPortRange( "1-65535"); forwardingRule.setRegion(ctx.getRegionId()); forwardingRule.setTarget(targetPoolSelfLink); GoogleMethod method = new GoogleMethod(provider); Operation job = gce.forwardingRules().insert(ctx.getAccountNumber(), ctx.getRegionId(), forwardingRule).execute(); boolean result = method.getOperationComplete(ctx, job, GoogleOperationType.REGION_OPERATION, ctx.getRegionId(), ""); } } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } } @Override public LoadBalancerHealthCheck createLoadBalancerHealthCheck(@Nonnull HealthCheckOptions options) throws CloudException, InternalException{ return createLoadBalancerHealthCheck( options.getName(), options.getDescription(), options.getHost(), LoadBalancerHealthCheck.HCProtocol.HTTP, options.getPort(), options.getPath(), options.getInterval(), options.getTimeout(), options.getHealthyCount(), options.getUnhealthyCount()); } @Override public LoadBalancerHealthCheck createLoadBalancerHealthCheck(@Nullable String name, @Nullable String description, @Nullable String host, @Nullable LoadBalancerHealthCheck.HCProtocol protocol, int port, @Nullable String path, int interval, int timeout, int healthyCount, int unhealthyCount) throws CloudException, InternalException{ APITrace.begin(provider, "LB.createLoadBalancerHealthCheck"); gce = provider.getGoogleCompute(); HttpHealthCheck hc = new HttpHealthCheck(); try { hc.setName(name); hc.setDescription(description); hc.setHost(host); // protocol hc.setPort(port); hc.setRequestPath(path); hc.setCheckIntervalSec(interval); hc.setTimeoutSec(timeout); hc.setHealthyThreshold(healthyCount); hc.setUnhealthyThreshold(unhealthyCount); GoogleMethod method = new GoogleMethod(provider); Operation job = gce.httpHealthChecks().insert(ctx.getAccountNumber(), hc).execute(); boolean result = method.getOperationComplete(ctx, job, GoogleOperationType.GLOBAL_OPERATION, ctx.getRegionId(), ""); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } return getLoadBalancerHealthCheck(name); } @Override public void attachHealthCheckToLoadBalancer(@Nonnull String providerLoadBalancerId, @Nonnull String providerLBHealthCheckId)throws CloudException, InternalException{ APITrace.begin(provider, "LB.attachHealthCheckToLoadBalancer"); gce = provider.getGoogleCompute(); HttpHealthCheck hc = null; try { hc = (gce.httpHealthChecks().get(ctx.getAccountNumber(), providerLBHealthCheckId)).execute(); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } ArrayList <HealthCheckReference>hcl = new ArrayList<HealthCheckReference>(); HealthCheckReference hcr = new HealthCheckReference(); hcr.setHealthCheck(hc.getSelfLink()); hcl.add(hcr); TargetPoolsAddHealthCheckRequest tphcr = new TargetPoolsAddHealthCheckRequest(); tphcr.setHealthChecks(hcl); try { AddHealthCheck op = gce.targetPools().addHealthCheck(ctx.getAccountNumber(), ctx.getRegionId(), providerLoadBalancerId, tphcr); Operation result = op.execute(); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } } public LoadBalancerHealthCheck toLoadBalancerHealthCheck(String loadBalancerName, HttpHealthCheck hc) throws CloudException, InternalException { if (loadBalancerName == null) throw new InternalException("loadBalancerName was null. Name is required"); if (hc == null) throw new InternalException("HttpHealthCheck was null"); Integer port = -1; if (hc.getPort() != null) port = hc.getPort(); Integer checkIntervalSecond = -1; if (hc.getCheckIntervalSec() != null) checkIntervalSecond = hc.getCheckIntervalSec(); Integer timeoutSec = -1; if (hc.getTimeoutSec() != null) timeoutSec = hc.getTimeoutSec(); Integer healthyThreshold = -1; if (hc.getHealthyThreshold() != null) healthyThreshold = hc.getHealthyThreshold(); Integer unhealthyThreshold = -1; if (hc.getUnhealthyThreshold() != null) unhealthyThreshold = hc.getUnhealthyThreshold(); LoadBalancerHealthCheck lbhc = LoadBalancerHealthCheck.getInstance( loadBalancerName, hc.getName(), hc.getDescription(), hc.getHost(), HCProtocol.TCP, port, hc.getRequestPath(), checkIntervalSecond, timeoutSec, healthyThreshold, unhealthyThreshold); lbhc.addProviderLoadBalancerId(loadBalancerName); return lbhc; } /* * Inventory Load Balancers and list their associated Health Checks. * Caveat, will only show FIRST health check */ @Override public Iterable<LoadBalancerHealthCheck> listLBHealthChecks(@Nullable HealthCheckFilterOptions opts) throws CloudException, InternalException { APITrace.begin(provider, "LB.listLBHealthChecks"); gce = provider.getGoogleCompute(); ArrayList<LoadBalancerHealthCheck> lbhc = new ArrayList<LoadBalancerHealthCheck>(); try { TargetPoolList tpl = gce.targetPools().list(ctx.getAccountNumber(), ctx.getRegionId()).execute(); if ((tpl != null) && (tpl.getItems() != null)) { Iterator<TargetPool> loadBalancers = tpl.getItems().iterator(); while (loadBalancers.hasNext()) { TargetPool lb = loadBalancers.next(); String loadBalancerName = lb.getName(); List<String> hcs = lb.getHealthChecks(); if ((hcs != null) && (!hcs.isEmpty())) { String healthCheckName = hcs.get(0); if (healthCheckName != null) { healthCheckName = healthCheckName.substring(healthCheckName.lastIndexOf("/") + 1); HttpHealthCheck hc = gce.httpHealthChecks().get(ctx.getAccountNumber(), healthCheckName).execute(); LoadBalancerHealthCheck healthCheckItem = toLoadBalancerHealthCheck(loadBalancerName, hc); lbhc.add(healthCheckItem); } } } } } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } return lbhc; } @Override public void removeLoadBalancerHealthCheck(@Nonnull String providerLoadBalancerId) throws CloudException, InternalException{ APITrace.begin(provider, "LB.removeLoadBalancerHealthCheck"); gce = provider.getGoogleCompute(); try { Operation job = (gce.httpHealthChecks().delete(ctx.getAccountNumber(), providerLoadBalancerId)).execute(); GoogleMethod method = new GoogleMethod(provider); method.getOperationComplete(ctx, job, GoogleOperationType.GLOBAL_OPERATION, ctx.getRegionId(), ""); // Causes CloudException if HC still in use. } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } } @Override public LoadBalancerHealthCheck modifyHealthCheck(@Nonnull String providerLBHealthCheckId, @Nonnull HealthCheckOptions options) throws InternalException, CloudException{ APITrace.begin(provider, "LB.modifyHealthCheck"); gce = provider.getGoogleCompute(); HttpHealthCheck hc = null; try { hc = (gce.httpHealthChecks().get(ctx.getAccountNumber(), providerLBHealthCheckId)).execute(); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } if ((options.getName() != null) && (!options.getName().equals(providerLBHealthCheckId))) throw new CloudException("Cannot rename loadbalancer health checks in GCE"); if (options.getDescription() != null) hc.setDescription(options.getDescription()); if (options.getHost() != null) hc.setHost(options.getHost()); hc.setRequestPath(options.getPath()); // TODO: Is protocol to be supported? hc.setPort(options.getPort()); hc.setCheckIntervalSec(options.getInterval()); hc.setTimeoutSec(options.getTimeout()); hc.setHealthyThreshold(options.getHealthyCount()); hc.setUnhealthyThreshold(options.getUnhealthyCount()); try { Operation op = gce.httpHealthChecks().update(ctx.getAccountNumber(), providerLBHealthCheckId, hc).execute(); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } return getLoadBalancerHealthCheck(providerLBHealthCheckId); } @Override public LoadBalancerHealthCheck getLoadBalancerHealthCheck(@Nullable String providerLBHealthCheckId, @Nullable String providerLoadBalancerId)throws CloudException, InternalException{ return getLoadBalancerHealthCheck(providerLBHealthCheckId); } public LoadBalancerHealthCheck getLoadBalancerHealthCheck(@Nullable String providerLBHealthCheckId)throws CloudException, InternalException{ APITrace.begin(provider, "LB.getLoadBalancerHealthCheck"); gce = provider.getGoogleCompute(); HttpHealthCheck hc = null; LoadBalancerHealthCheck lbhc = null; try { hc = (gce.httpHealthChecks().get(ctx.getAccountNumber(), providerLBHealthCheckId)).execute(); lbhc = toLoadBalancerHealthCheck(providerLBHealthCheckId, hc); //lbhc.addProviderLoadBalancerId(hc.getName()); } catch (NullPointerException e) { // not found, return null } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } return lbhc; } @Override public @Nullable LoadBalancer getLoadBalancer(@Nonnull String loadBalancerId) throws CloudException, InternalException { APITrace.begin(provider, "LB.getLoadBalancer"); gce = provider.getGoogleCompute(); LoadBalancer lb = null; try { TargetPool tp = gce.targetPools().get(ctx.getAccountNumber(), ctx.getRegionId(), loadBalancerId).execute(); lb = toLoadBalancer(tp); } catch (Exception e) { lb = null; } finally { APITrace.end(); } return lb; } @Override public void addServers(@Nonnull String toLoadBalancerId, @Nonnull String ... serverIdsToAdd) throws CloudException, InternalException { APITrace.begin(provider, "LB.addServers"); gce = provider.getGoogleCompute(); String vmRegion = null; try { List<InstanceReference> instances = new ArrayList<InstanceReference>(); for (String server : serverIdsToAdd) { VirtualMachine vm = provider.getComputeServices().getVirtualMachineSupport().getVirtualMachine(server); vmRegion = vm.getProviderRegionId(); instances.add(new InstanceReference().setInstance((String) vm.getTag("contentLink"))); } gce.targetPools().addInstance(ctx.getAccountNumber(), vmRegion, toLoadBalancerId, new TargetPoolsAddInstanceRequest().setInstances(instances)).execute(); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } } @Override public void removeServers(@Nonnull String fromLoadBalancerId, @Nonnull String ... serverIdsToRemove) throws CloudException, InternalException { APITrace.begin(provider, "LB.removeServers"); gce = provider.getGoogleCompute(); List<InstanceReference> replacementInstances = new ArrayList<InstanceReference>(); try { TargetPool tp = gce.targetPools().get(ctx.getAccountNumber(), ctx.getRegionId(), fromLoadBalancerId).execute(); List<String> instances = tp.getInstances(); for (String i : instances) for (String serverToRemove : serverIdsToRemove) if (i.endsWith(serverToRemove)) replacementInstances.add(new InstanceReference().setInstance(i)); TargetPoolsRemoveInstanceRequest content = new TargetPoolsRemoveInstanceRequest(); content.setInstances(replacementInstances); gce.targetPools().removeInstance(ctx.getAccountNumber(), ctx.getRegionId(), fromLoadBalancerId, content).execute(); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } } @Override public @Nonnull Iterable<LoadBalancerEndpoint> listEndpoints(@Nonnull String forLoadBalancerId) throws CloudException, InternalException { APITrace.begin(provider, "LB.listEndpoints"); gce = provider.getGoogleCompute(); TargetPool tp = null; try { tp = gce.targetPools().get(ctx.getAccountNumber(), ctx.getRegionId(), forLoadBalancerId).execute(); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } try { ArrayList<LoadBalancerEndpoint> list = new ArrayList<LoadBalancerEndpoint>(); List<String> instances = tp.getInstances(); if (instances != null) for (String instance : instances) list.add(LoadBalancerEndpoint.getInstance(LbEndpointType.VM, instance.substring(1 + instance.lastIndexOf("/")), LbEndpointState.ACTIVE)); return list; } finally { APITrace.end(); } } @Override public @Nonnull Iterable<ResourceStatus> listLoadBalancerStatus() throws CloudException, InternalException { APITrace.begin(provider, "LB.listLoadBalancers"); gce = provider.getGoogleCompute(); ArrayList<ResourceStatus> list = new ArrayList<ResourceStatus>(); try { TargetPoolList tpl = gce.targetPools().list(ctx.getAccountNumber(), ctx.getRegionId()).execute(); if (tpl.getItems() != null) { Iterator<TargetPool> loadBalancers = tpl.getItems().iterator(); while (loadBalancers.hasNext()) { TargetPool lb = loadBalancers.next(); List<String> healthChecks = lb.getHealthChecks(); for (String healthCheckName : healthChecks) { healthCheckName = healthCheckName.substring(healthCheckName.lastIndexOf("/") + 1); LoadBalancerHealthCheck healthCheck = getLoadBalancerHealthCheck(healthCheckName); list.add(new ResourceStatus(lb.getName(), "UNKNOWN")); } } } return list; } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } } @Override public @Nonnull Iterable<LoadBalancer> listLoadBalancers() throws CloudException, InternalException { APITrace.begin(provider, "LB.listLoadBalancers"); gce = provider.getGoogleCompute(); ArrayList<LoadBalancer> list = new ArrayList<LoadBalancer>(); try { TargetPoolList tpl = gce.targetPools().list(ctx.getAccountNumber(), ctx.getRegionId()).execute(); List<TargetPool> x = tpl.getItems(); if (tpl.getItems() != null) { Iterator<TargetPool> loadBalancers = tpl.getItems().iterator(); while (loadBalancers.hasNext()) { TargetPool lb = loadBalancers.next(); LoadBalancer loadBalancer = toLoadBalancer(lb); if( loadBalancer != null ) { list.add(loadBalancer); } } } return list; } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } finally { APITrace.end(); } } private LoadBalancer toLoadBalancer(TargetPool tp) throws CloudException, InternalException { gce = provider.getGoogleCompute(); List<String> hcl = tp.getHealthChecks(); String healthCheckName = null; if ((hcl != null) && (!hcl.isEmpty())) { healthCheckName = hcl.get(0); healthCheckName = healthCheckName.substring(healthCheckName.lastIndexOf("/") + 1); } long created = 0; try { created = provider.parseTime(tp.getCreationTimestamp()); } catch (CloudException e) { throw new CloudException(e); } ForwardingRule fr = null; String forwardingRuleAddress = null; String forwardingRulePortRange = null; int ports[] = null; List<LbListener> listeners = new ArrayList<LbListener>(); try { List<String> forwardingRuleNames = getForwardingRule(tp.getName()); for (String forwardingRuleName : forwardingRuleNames) { fr = gce.forwardingRules().get(ctx.getAccountNumber(), ctx.getRegionId(), forwardingRuleName).execute(); forwardingRuleAddress = fr.getIPAddress(); //foreardingRuleProtocol = fr.getIPProtocol(); forwardingRulePortRange = fr.getPortRange(); ports = portsToRange(forwardingRulePortRange); String protocol = fr.getIPProtocol(); if (protocol.equals("TCP")) protocol = "RAW_TCP"; for (int port : ports) // Hard Coded Algorithm and persistence, havent found a dynamic source yet. listeners.add(LbListener.getInstance(LbAlgorithm.SOURCE, LbPersistence.SUBNET, LbProtocol.valueOf(protocol), port, port)); } } catch (IOException e) { // Guess no forwarding rules for this one. } String region = tp.getRegion(); region = region.substring(region.lastIndexOf("/") + 1); LoadBalancer lb = LoadBalancer.getInstance( ctx.getAccountNumber(), region, tp.getName(), LoadBalancerState.ACTIVE, tp.getName(), tp.getDescription(), LbType.EXTERNAL, LoadBalancerAddressType.DNS, forwardingRuleAddress, healthCheckName, // TODO: need to modify setProviderLBHealthCheckId to accept lists or arrays ports ).supportingTraffic(IPVersion.IPV4).createdAt(created); LbListener LBListeners[] = new LbListener[listeners.size()]; LBListeners = listeners.toArray(LBListeners); if (!listeners.isEmpty()) lb = lb.withListeners(LBListeners); return lb; } private int[] portsToRange(String portRange) { int[] ports; if (portRange.contains("-")) { String[] parts = portRange.split("-"); int start = new Integer(parts[0]); int end = new Integer(parts[1]); ports = new int[(1 + end - start)]; for (int x = 0; x< (1 + end - start); x++) { ports[x] = start + x; } } else ports = new int[]{new Integer(portRange)}; return ports; } }
NPE caught by labisso
src/main/java/org/dasein/cloud/google/network/LoadBalancerSupport.java
NPE caught by labisso
<ide><path>rc/main/java/org/dasein/cloud/google/network/LoadBalancerSupport.java <ide> List<String> forwardingRuleNames = new ArrayList<String>(); <ide> try { <ide> ForwardingRuleList result = gce.forwardingRules().list(ctx.getAccountNumber(), ctx.getRegionId()).execute(); <del> for (ForwardingRule fr : result.getItems()) { <del> String forwardingRuleTarget = fr.getTarget(); <del> forwardingRuleTarget = forwardingRuleTarget.substring(forwardingRuleTarget.lastIndexOf("/") + 1); <del> <del> if (targetPoolName.equals(forwardingRuleTarget)) <del> forwardingRuleNames.add(fr.getName()); <del> } <add> if (result != null) <add> for (ForwardingRule fr : result.getItems()) { <add> String forwardingRuleTarget = fr.getTarget(); <add> forwardingRuleTarget = forwardingRuleTarget.substring(forwardingRuleTarget.lastIndexOf("/") + 1); <add> <add> if (targetPoolName.equals(forwardingRuleTarget)) <add> forwardingRuleNames.add(fr.getName()); <add> } <ide> } catch (IOException e) { <ide> if (e.getClass() == GoogleJsonResponseException.class) { <ide> GoogleJsonResponseException gjre = (GoogleJsonResponseException)e;
Java
mit
600c93d26ccfc5d18005d3c6477866dfeaad2db1
0
viruscamp/unluac1
package unluac.decompile; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import unluac.Version; import unluac.decompile.block.AlwaysLoop; import unluac.decompile.block.Block; import unluac.decompile.block.Break; import unluac.decompile.block.DoEndBlock; import unluac.decompile.block.ForBlock; import unluac.decompile.block.ElseEndBlock; import unluac.decompile.block.ForBlock50; import unluac.decompile.block.ForBlock51; import unluac.decompile.block.IfThenElseBlock; import unluac.decompile.block.IfThenEndBlock; import unluac.decompile.block.OnceLoop; import unluac.decompile.block.RepeatBlock; import unluac.decompile.block.SetBlock; import unluac.decompile.block.TForBlock50; import unluac.decompile.block.TForBlock51; import unluac.decompile.block.WhileBlock; import unluac.decompile.block.OuterBlock; import unluac.decompile.block.TForBlock; import unluac.decompile.condition.AndCondition; import unluac.decompile.condition.BinaryCondition; import unluac.decompile.condition.Condition; import unluac.decompile.condition.ConstantCondition; import unluac.decompile.condition.OrCondition; import unluac.decompile.condition.RegisterSetCondition; import unluac.decompile.condition.SetCondition; import unluac.decompile.condition.TestCondition; import unluac.parse.LFunction; public class ControlFlowHandler { public static boolean verbose = false; private static class Branch implements Comparable<Branch> { private static enum Type { comparison, test, testset, finalset, jump; } public Branch previous; public Branch next; public int line; public int target; public Type type; public Condition cond; public int targetFirst; public int targetSecond; public boolean inverseValue; public Branch(int line, Type type, Condition cond, int targetFirst, int targetSecond) { this.line = line; this.type = type; this.cond = cond; this.targetFirst = targetFirst; this.targetSecond = targetSecond; this.inverseValue = false; this.target = -1; } @Override public int compareTo(Branch other) { return this.line - other.line; } } private static class State { public Decompiler d; public LFunction function; public Registers r; public Code code; public Branch begin_branch; public Branch end_branch; public Branch[] branches; public Branch[] setbranches; public Branch[] finalsetbranches; public boolean[] reverse_targets; public int[] resolved; public List<Block> blocks; } public static List<Block> process(Decompiler d, Registers r) { State state = new State(); state.d = d; state.function = d.function; state.r = r; state.code = d.code; find_reverse_targets(state); find_branches(state); combine_branches(state); resolve_lines(state); initialize_blocks(state); find_fixed_blocks(state); find_while_loops(state); find_repeat_loops(state); //find_break_statements(state); //find_if_blocks(state); find_other_statements(state, d.declList); find_set_blocks(state); //find_pseudo_goto_statements(state, d.declList); find_do_blocks(state, d.declList); Collections.sort(state.blocks); // DEBUG: print branches stuff /* Branch b = state.begin_branch; while(b != null) { System.out.println("Branch at " + b.line); System.out.println("\tcondition: " + b.cond); b = b.next; } */ return state.blocks; } private static void find_reverse_targets(State state) { Code code = state.code; boolean[] reverse_targets = state.reverse_targets = new boolean[state.code.length + 1]; for(int line = 1; line <= code.length; line++) { if(is_jmp(state, line)) { int target = code.target(line); if(target <= line) { reverse_targets[target] = true; } } } } private static void resolve_lines(State state) { int[] resolved = new int[state.code.length + 1]; Arrays.fill(resolved, -1); for(int line = 1; line <= state.code.length; line++) { int r = line; Branch b = state.branches[line]; while(b != null && b.type == Branch.Type.jump) { if(resolved[r] >= 1) { r = resolved[r]; break; } else if(resolved[r] == -2) { r = b.targetSecond; break; } else { resolved[r] = -2; r = b.targetSecond; b = state.branches[r]; } } resolved[line] = r; } state.resolved = resolved; } private static int find_loadboolblock(State state, int target) { int loadboolblock = -1; if(state.code.op(target) == Op.LOADBOOL) { if(state.code.C(target) != 0) { loadboolblock = target; } else if(target - 1 >= 1 && state.code.op(target - 1) == Op.LOADBOOL && state.code.C(target - 1) != 0) { loadboolblock = target - 1; } } return loadboolblock; } private static void handle_loadboolblock(State state, boolean[] skip, int loadboolblock, Condition c, int line, int target) { int loadboolvalue = state.code.B(target); int final_line = -1; if(loadboolblock - 1 >= 1 && is_jmp(state, loadboolblock - 1)) { int boolskip_target = state.code.target(loadboolblock - 1); int boolskip_target_redirected = -1; if(is_jmp_raw(state, loadboolblock + 2)) { boolskip_target_redirected = state.code.target(loadboolblock + 2); } if(boolskip_target == loadboolblock + 2 || boolskip_target == boolskip_target_redirected) { skip[loadboolblock - 1] = true; final_line = loadboolblock - 2; } } boolean inverse = false; if(loadboolvalue == 1) { inverse = true; c = c.inverse(); } boolean constant = is_jmp(state, line); Branch b; int begin = line + 2; if(constant) { begin--; b = new Branch(line, Branch.Type.testset, c, begin, loadboolblock + 2); } else if(line + 2 == loadboolblock) { b = new Branch(line, Branch.Type.finalset, c, begin, loadboolblock + 2); } else { b = new Branch(line, Branch.Type.testset, c, begin, loadboolblock + 2); } b.target = state.code.A(loadboolblock); b.inverseValue = inverse; insert_branch(state, b); if(constant && final_line < begin && state.finalsetbranches[final_line + 1] == null) { c = new TestCondition(final_line + 1, state.code.A(target)); b = new Branch(final_line + 1, Branch.Type.finalset, c, final_line, loadboolblock + 2); b.target = state.code.A(loadboolblock); insert_branch(state, b); } if(final_line >= begin && state.finalsetbranches[final_line] == null) { c = new SetCondition(final_line, get_target(state, final_line)); b = new Branch(final_line, Branch.Type.finalset, c, final_line, loadboolblock + 2); b.target = state.code.A(loadboolblock); insert_branch(state, b); } if(final_line + 1 == begin && state.finalsetbranches[final_line + 1] == null) { c = new RegisterSetCondition(loadboolblock, get_target(state, loadboolblock)); b = new Branch(final_line + 1, Branch.Type.finalset, c, final_line, loadboolblock + 2); b.target = state.code.A(loadboolblock); insert_branch(state, b); } } private static void find_branches(State state) { Code code = state.code; state.branches = new Branch[state.code.length + 1]; state.setbranches = new Branch[state.code.length + 1]; state.finalsetbranches = new Branch[state.code.length + 1]; boolean[] skip = new boolean[code.length + 1]; for(int line = 1; line <= code.length; line++) { if(!skip[line]) { switch(code.op(line)) { case EQ: case LT: case LE: { BinaryCondition.Operator op = BinaryCondition.Operator.EQ; if(code.op(line) == Op.LT) op = BinaryCondition.Operator.LT; if(code.op(line) == Op.LE) op = BinaryCondition.Operator.LE; int left = code.B(line); int right = code.C(line); int target = code.target(line + 1); Condition c = new BinaryCondition(op, line, left, right); if(code.A(line) == 1) { c = c.inverse(); } int loadboolblock = find_loadboolblock(state, target); if(loadboolblock >= 1) { handle_loadboolblock(state, skip, loadboolblock, c, line, target); } else { Branch b = new Branch(line, Branch.Type.comparison, c, line + 2, target); if(code.A(line) == 1) { b.inverseValue = true; } insert_branch(state, b); } skip[line + 1] = true; break; } case TEST50: { Condition c = new TestCondition(line, code.B(line)); int target = code.target(line + 1); if(code.A(line) == code.B(line)) { if(code.C(line) != 0) c = c.inverse(); int loadboolblock = find_loadboolblock(state, target); if(loadboolblock >= 1) { handle_loadboolblock(state, skip, loadboolblock, c, line, target); } else { Branch b = new Branch(line, Branch.Type.test, c, line + 2, target); b.target = code.A(line); if(code.C(line) != 0) b.inverseValue = true; insert_branch(state, b); } } else { Branch b = new Branch(line, Branch.Type.testset, c, line + 2, target); b.target = code.A(line); if(code.C(line) != 0) b.inverseValue = true; skip[line + 1] = true; insert_branch(state, b); int final_line = target - 1; if(state.finalsetbranches[final_line] == null) { int loadboolblock = find_loadboolblock(state, target - 2); if(loadboolblock == -1) { if(line + 2 == target) { c = new RegisterSetCondition(line, get_target(state, line)); final_line = final_line + 1; } else { c = new SetCondition(final_line, get_target(state, final_line)); } b = new Branch(final_line, Branch.Type.finalset, c, target, target); b.target = code.A(line); insert_branch(state, b); } } break; } skip[line + 1] = true; break; } case TEST: { Condition c = new TestCondition(line, code.A(line)); if(code.C(line) != 0) c = c.inverse(); int target = code.target(line + 1); int loadboolblock = find_loadboolblock(state, target); if(loadboolblock >= 1) { handle_loadboolblock(state, skip, loadboolblock, c, line, target); } else { Branch b = new Branch(line, Branch.Type.test, c, line + 2, target); b.target = code.A(line); if(code.C(line) != 0) b.inverseValue = true; insert_branch(state, b); } skip[line + 1] = true; break; } case TESTSET: { Condition c = new TestCondition(line, code.B(line)); int target = code.target(line + 1); Branch b = new Branch(line, Branch.Type.testset, c, line + 2, target); b.target = code.A(line); if(code.C(line) != 0) b.inverseValue = true; skip[line + 1] = true; insert_branch(state, b); int final_line = target - 1; if(state.finalsetbranches[final_line] == null) { int loadboolblock = find_loadboolblock(state, target - 2); if(loadboolblock == -1) { if(line + 2 == target) { c = new RegisterSetCondition(line, get_target(state, line)); final_line = final_line + 1; } else { c = new SetCondition(final_line, get_target(state, final_line)); } b = new Branch(final_line, Branch.Type.finalset, c, target, target); b.target = code.A(line); insert_branch(state, b); } } break; } case JMP: case JMP52: { if(is_jmp(state, line)) { int target = code.target(line); int loadboolblock = find_loadboolblock(state, target); if(loadboolblock >= 1) { handle_loadboolblock(state, skip, loadboolblock, new ConstantCondition(-1, false), line, target); } else { Branch b = new Branch(line, Branch.Type.jump, null, target, target); insert_branch(state, b); } } break; } default: break; } } } link_branches(state); } private static void combine_branches(State state) { Branch b; b = state.end_branch; while(b != null) { b = combine_left(state, b).previous; } } private static void initialize_blocks(State state) { state.blocks = new LinkedList<Block>(); } private static void find_fixed_blocks(State state) { List<Block> blocks = state.blocks; Registers r = state.r; Code code = state.code; Op tforTarget = state.function.header.version.getTForTarget(); Op forTarget = state.function.header.version.getForTarget(); blocks.add(new OuterBlock(state.function, state.code.length)); boolean[] loop = new boolean[state.code.length + 1]; Branch b = state.begin_branch; while(b != null) { if(b.type == Branch.Type.jump) { int line = b.line; int target = b.targetFirst; if(code.op(target) == tforTarget && !loop[target]) { loop[target] = true; int A = code.A(target); int C = code.C(target); if(C == 0) throw new IllegalStateException(); remove_branch(state, state.branches[line]); if(state.branches[target + 1] != null) { remove_branch(state, state.branches[target + 1]); } boolean forvarClose = false; boolean innerClose = false; int close = target - 1; if(close >= line + 1 && is_close(state, close) && code.A(close) == A + 3) { forvarClose = true; close--; } if(close >= line + 1 && is_close(state, close) && code.A(close) <= A + 3 + C) { innerClose = true; } TForBlock block = new TForBlock51(state.function, line + 1, target + 2, A, C, forvarClose, innerClose); block.handleVariableDeclarations(r); blocks.add(block); } else if(code.op(target) == forTarget && !loop[target]) { loop[target] = true; int A = code.A(target); boolean innerClose = false; int close = target - 1; if(close >= line + 1 && is_close(state, close) && code.A(close) == A + 3) { innerClose = true; } ForBlock block = new ForBlock50(state.function, line + 1, target + 1, A, innerClose); block.handleVariableDeclarations(r); blocks.add(block); remove_branch(state, b); } } b = b.next; } for(int line = 1; line <= code.length; line++) { switch(code.op(line)) { case FORPREP: { int A = code.A(line); int target = code.target(line); boolean forvarClose = false; boolean innerClose = false; int close = target - 1; if(close >= line + 1 && is_close(state, close) && code.A(close) == A + 3) { forvarClose = true; close--; } if(close >= line + 1 && is_close(state, close) && code.A(close) <= A + 4) { innerClose = true; } ForBlock block = new ForBlock51(state.function, line + 1, target + 1, A, forvarClose, innerClose); block.handleVariableDeclarations(r); blocks.add(block); break; } case TFORPREP: { int target = code.target(line); int A = code.A(target); int C = code.C(target); boolean innerClose = false; int close = target - 1; if(close >= line + 1 && is_close(state, close) && code.A(close) == A + 3 + C) { innerClose = true; } TForBlock block = new TForBlock50(state.function, line + 1, target + 2, A, C, innerClose); block.handleVariableDeclarations(r); blocks.add(block); remove_branch(state, state.branches[target + 1]); break; } default: break; } } } private static void unredirect(State state, int begin, int end, int line, int target) { Branch b = state.begin_branch; while(b != null) { if(b.line >= begin && b.line < end && b.targetSecond == target) { b.targetSecond = line; if(b.targetFirst == target) { b.targetFirst = line; } } b = b.next; } } private static void find_while_loops(State state) { List<Block> blocks = state.blocks; Branch j = state.end_branch; while(j != null) { if(j.type == Branch.Type.jump && j.targetFirst <= j.line) { int line = j.targetFirst; int loopback = line; int end = j.line + 1; Branch b = state.begin_branch; while(b != null) { if(is_conditional(b) && b.line >= loopback && b.line < j.line && state.resolved[b.targetSecond] == state.resolved[end]) { break; } b = b.next; } if(b != null) { boolean reverse = state.reverse_targets[loopback]; state.reverse_targets[loopback] = false; if(has_statement(state, loopback, b.line - 1)) { b = null; } state.reverse_targets[loopback] = reverse; } if(state.function.header.version == Version.LUA50) { b = null; // while loop aren't this style } Block loop; if(b != null) { b.targetSecond = end; remove_branch(state, b); //System.err.println("while " + b.targetFirst + " " + b.targetSecond); loop = new WhileBlock(state.function, b.cond, b.targetFirst, b.targetSecond); unredirect(state, loopback, end, j.line, loopback); } else { boolean repeat = false; if(state.function.header.version == Version.LUA50) { repeat = true; if(loopback - 1 >= 1 && state.branches[loopback - 1] != null) { Branch head = state.branches[loopback - 1]; if(head.type == Branch.Type.jump && head.targetFirst == j.line) { remove_branch(state, head); repeat = false; } } } loop = new AlwaysLoop(state.function, loopback, end, repeat); unredirect(state, loopback, end, j.line, loopback); } remove_branch(state, j); blocks.add(loop); } j = j.previous; } } private static void find_repeat_loops(State state) { List<Block> blocks = state.blocks; Branch b = state.begin_branch; while(b != null) { if(is_conditional(b)) { if(b.targetSecond < b.targetFirst) { Block block = null; if(state.function.header.version == Version.LUA50) { int head = b.targetSecond - 1; if(head >= 1 && state.branches[head] != null && state.branches[head].type == Branch.Type.jump) { Branch headb = state.branches[head]; if(headb.targetSecond <= b.line) { if(has_statement(state, headb.targetSecond, b.line - 1)) { headb = null; } if(headb != null) { block = new WhileBlock(state.function, b.cond.inverse(), head + 1, b.targetFirst); remove_branch(state, headb); unredirect(state, 1, headb.line, headb.line, headb.targetSecond); } } } } if(block == null) { block = new RepeatBlock(state.function, b.cond, b.targetSecond, b.targetFirst); } remove_branch(state, b); blocks.add(block); } } b = b.next; } } private static void find_if_blocks(State state) { Branch b = state.begin_branch; while(b != null) { if(is_conditional(b)) { Block enclosing; enclosing = enclosing_unprotected_block(state, b.line); if(enclosing != null && !enclosing.contains(b.targetSecond)) { if(b.targetSecond == enclosing.getUnprotectedTarget()) { b.targetSecond = enclosing.getUnprotectedLine(); } } Branch tail = b.targetSecond >= 1 ? state.branches[b.targetSecond - 1] : null; if(tail != null && !is_conditional(tail)) { enclosing = enclosing_unprotected_block(state, tail.line); if(enclosing != null && !enclosing.contains(tail.targetSecond)) { if(tail.targetSecond == state.resolved[enclosing.getUnprotectedTarget()]) { tail.targetSecond = enclosing.getUnprotectedLine(); } } //System.err.println("else end " + b.targetFirst + " " + b.targetSecond + " " + tail.targetSecond + " enclosing " + (enclosing != null ? enclosing.begin : -1) + " " + + (enclosing != null ? enclosing.end : -1)); state.blocks.add(new IfThenElseBlock(state.function, b.cond, b.targetFirst, b.targetSecond, tail.targetSecond)); if(b.targetSecond != tail.targetSecond) { state.blocks.add(new ElseEndBlock(state.function, b.targetSecond, tail.targetSecond)); } // else "empty else" case remove_branch(state, tail); unredirect(state, b.targetFirst, b.targetSecond, b.targetSecond - 1, tail.targetSecond); } else { //System.err.println("if end " + b.targetFirst + " " + b.targetSecond); Block breakable = enclosing_breakable_block(state, b.line); if(breakable != null && breakable.end == b.targetSecond) { // 5.2-style if-break Block block = new IfThenEndBlock(state.function, state.r, b.cond.inverse(), b.targetFirst - 1, b.targetFirst - 1, false); block.addStatement(new Break(state.function, b.targetFirst - 1, b.targetSecond)); state.blocks.add(block); } else { int literalEnd = state.code.target(b.targetFirst - 1); state.blocks.add(new IfThenEndBlock(state.function, state.r, b.cond, b.targetFirst, b.targetSecond, literalEnd != b.targetSecond)); } } remove_branch(state, b); } b = b.next; } } private static void find_set_blocks(State state) { List<Block> blocks = state.blocks; Branch b = state.begin_branch; while(b != null) { if(is_assignment(b) || b.type == Branch.Type.finalset) { Block block = new SetBlock(state.function, b.cond, b.target, b.line, b.targetFirst, b.targetSecond, state.r); blocks.add(block); remove_branch(state, b); } b = b.next; } } private static Block enclosing_breakable_block(State state, int line) { Block enclosing = null; for(Block block : state.blocks) { if(block.contains(line) && block.breakable()) { if(enclosing == null || enclosing.contains(block)) { enclosing = block; } } } return enclosing; } private static Block enclosing_unprotected_block(State state, int line) { Block enclosing = null; for(Block block : state.blocks) { if(block.contains(line) && block.isUnprotected()) { if(enclosing == null || enclosing.contains(block)) { enclosing = block; } } } return enclosing; } private static void unredirect_break(State state, int line, Block enclosing) { Branch b = state.begin_branch; while(b != null) { Block breakable = enclosing_breakable_block(state, b.line); if(b.line != line && breakable != null && b.type == Branch.Type.jump && breakable == enclosing && b.targetFirst == enclosing.end) { //System.err.println("redirect break " + b.line + " from " + b.targetFirst + " to " + line); boolean condsplit = false; Branch c = state.begin_branch; while(c != null) { if(is_conditional(c) && c.targetSecond < breakable.end) { if(c.targetFirst <= line && line < c.targetSecond) { if(c.targetFirst <= b.line && b.line < c.targetSecond) { } else { condsplit = true; break; } } } c = c.next; } if(!condsplit) { b.targetFirst = line; b.targetSecond = line; } } b = b.next; } } private static class ResolutionState { ResolutionState(State state, Block container) { this.container = container; resolution = new BranchResolution[state.code.length + 1]; results = new ArrayList<ResolutionResult>(); } Block container; BranchResolution[] resolution; List<ResolutionResult> results; } private static class BranchResolution { enum Type { IF_END, IF_ELSE, IF_BREAK, ELSE, BREAK, PSEUDO_GOTO, }; Type type; int line; boolean matched; } private static class Pair { Pair(int begin, int end) { this.begin = begin; this.end = end; } int begin; int end; } private static class ResolutionResult { List<Block> blocks = new ArrayList<Block>(); } private static ResolutionResult finishResolution(State state, Declaration[] declList, ResolutionState rstate) { ResolutionResult result = new ResolutionResult(); for(int i = 0; i < rstate.resolution.length; i++) { BranchResolution r = rstate.resolution[i]; if(r != null) { Branch b = state.branches[i]; if(b == null) throw new IllegalStateException(); switch(r.type) { case ELSE: break; case BREAK: result.blocks.add(new Break(state.function, b.line, r.line)); break; case PSEUDO_GOTO: // handled in second pass break; case IF_END: int literalEnd = state.code.target(b.targetFirst - 1); result.blocks.add(new IfThenEndBlock(state.function, state.r, b.cond, b.targetFirst, r.line, literalEnd != r.line)); break; case IF_ELSE: BranchResolution r_else = rstate.resolution[r.line - 1]; if(r_else == null) throw new IllegalStateException(); result.blocks.add(new IfThenElseBlock(state.function, b.cond, b.targetFirst, r.line, r_else.line)); if(r.line != r_else.line) { result.blocks.add(new ElseEndBlock(state.function, r.line, r_else.line)); } // else "empty else" case break; case IF_BREAK: Block block = new IfThenEndBlock(state.function, state.r, b.cond.inverse(), b.targetFirst - 1, b.targetFirst - 1, false); block.addStatement(new Break(state.function, b.targetFirst - 1, r.line)); result.blocks.add(block); break; default: throw new IllegalStateException(); } } } for(int i = 0; i < rstate.resolution.length; i++) { BranchResolution r = rstate.resolution[i]; if(r != null) { Branch b = state.branches[i]; if(b == null) throw new IllegalStateException(); if(r.type == BranchResolution.Type.PSEUDO_GOTO) { Block smallest = rstate.container; if(smallest == null) smallest = state.blocks.get(0); // outer block TODO cleaner way to get for(Block newblock : result.blocks) { if(smallest.contains(newblock) && newblock.contains(b.line) && newblock.contains(r.line - 1)) { smallest = newblock; } } Block wrapping = null; for(Block block : result.blocks) { if(block != smallest && smallest.contains(block) && block.contains(b.line)) { if(wrapping == null || block.contains(wrapping)) { wrapping = block; } } } for(Block block : state.blocks) { if(block != smallest && smallest.contains(block) && block.contains(b.line)) { if(wrapping == null || block.contains(wrapping)) { wrapping = block; } } } int begin; if(wrapping != null) { begin = wrapping.begin - 1; } else { begin = b.line; } for(Declaration decl : declList) { if(decl.begin >= begin && decl.begin < r.line) { } if(decl.end >= begin && decl.end < r.line) { if(decl.begin < begin) { begin = decl.begin; } } } result.blocks.add(new OnceLoop(state.function, begin, r.line)); result.blocks.add(new Break(state.function, b.line, r.line)); } } } return result; } private static boolean debug_resolution = false; private static boolean checkResolution(State state, ResolutionState rstate) { List<Pair> blocks = new ArrayList<Pair>(); List<Pair> pseudoGotos = new ArrayList<Pair>(); for(int i = 0; i < rstate.resolution.length; i++) { BranchResolution r = rstate.resolution[i]; if(r != null) { Branch b = state.branches[i]; if(b == null) throw new IllegalStateException(); switch(r.type) { case ELSE: if(!r.matched) { if(debug_resolution) System.err.println("unmatched else"); return false; } if(rstate.container != null && r.line >= rstate.container.end) { if(debug_resolution) System.err.println("invalid else"); return false; } break; case BREAK: if(rstate.container == null || r.line < rstate.container.end) { if(debug_resolution) System.err.println("invalid break"); return false; } break; case PSEUDO_GOTO: if(rstate.container != null && r.line >= rstate.container.end) { if(debug_resolution) System.err.println("invalid pseudo goto"); return false; } pseudoGotos.add(new Pair(b.line, r.line)); break; case IF_END: if(rstate.container != null && r.line >= rstate.container.end) { if(debug_resolution) System.err.println("invalid if end"); return false; } blocks.add(new Pair(b.targetFirst, r.line)); break; case IF_ELSE: if(rstate.container != null && r.line >= rstate.container.end) { if(debug_resolution) System.err.println("invalid if else"); return false; } BranchResolution r_else = rstate.resolution[r.line - 1]; if(r_else == null) throw new IllegalStateException(); blocks.add(new Pair(b.targetFirst, r.line - 1)); blocks.add(new Pair(r.line, r_else.line)); blocks.add(new Pair(b.targetFirst, r_else.line)); break; case IF_BREAK: if(rstate.container == null || r.line < rstate.container.end) { if(debug_resolution) System.err.println("invalid if break"); return false; } break; default: throw new IllegalStateException(); } } } for(int i = 0; i < blocks.size(); i++) { for(int j = i + 1; j < blocks.size(); j++) { Pair block1 = blocks.get(i); Pair block2 = blocks.get(j); if(block1.end <= block2.begin) { // okay } else if(block2.end <= block1.begin) { // okay } else if(block1.begin <= block2.begin && block2.end <= block1.end) { // okay } else if(block2.begin <= block1.begin && block1.end <= block2.end) { // okay } else { if(debug_resolution) System.err.println("invalid block overlap"); return false; } } } for(Pair pseudoGoto : pseudoGotos) { for(Pair block : blocks) { if(block.begin <= pseudoGoto.end && block.end > pseudoGoto.end) { // block contains end if(block.begin > pseudoGoto.begin || block.end <= pseudoGoto.begin) { // doesn't contain goto if(debug_resolution) System.err.println("invalid pseudo goto block overlap"); return false; } } } } for(int i = 0; i < pseudoGotos.size(); i++) { for(int j = 0; j < pseudoGotos.size(); j++) { Pair goto1 = pseudoGotos.get(i); Pair goto2 = pseudoGotos.get(j); if(goto1.begin >= goto2.begin && goto1.begin < goto2.end) { if(debug_resolution) System.err.println("invalid pseudo goto overlap"); if(goto1.end > goto2.end) return false; } if(goto2.begin >= goto1.begin && goto2.begin < goto1.end) { if(debug_resolution) System.err.println("invalid pseudo goto overlap"); if(goto2.end > goto1.end) return false; } } } // TODO: check for break out of OnceBlock return true; } private static void printResolution(State state, ResolutionState rstate) { for(int i = 0; i < rstate.resolution.length; i++) { BranchResolution r = rstate.resolution[i]; if(r != null) { Branch b = state.branches[i]; if(b == null) throw new IllegalStateException(); System.out.print(r.type + " " + b.line + " " + r.line); if(b.cond != null) System.out.print(" " + b.cond); System.out.println(); } } } private static boolean is_break(State state, Block container, int line) { if(container == null || line < container.end) return false; if(line == container.end) return true; return state.resolved[container.end] == state.resolved[line]; } private static void resolve(State state, Declaration[] declList, ResolutionState rstate, Branch b) { if(b == null) { if(checkResolution(state, rstate)) { // printResolution(state, container, resolution); // System.out.println(); rstate.results.add(finishResolution(state, declList, rstate)); } else { // System.out.println("failed resolution:"); // printResolution(state, container, resolution); } return; } Branch next = b.previous; while(next != null && enclosing_breakable_block(state, next.line) != rstate.container) { next = next.previous; } if(is_conditional(b)) { BranchResolution r = new BranchResolution(); rstate.resolution[b.line] = r; if(is_break(state, rstate.container, b.targetSecond)) { if(state.function.header.version.usesIfBreakRewrite()) { r.type = BranchResolution.Type.IF_BREAK; r.line = rstate.container.end; resolve(state, declList, rstate, next); } } Branch p = state.end_branch; while(p != b) { if(p.type == Branch.Type.jump && enclosing_breakable_block(state, p.line) == rstate.container) { if(p.targetFirst == b.targetSecond) { r.line = p.line; BranchResolution prevlineres = null; if(p.line - 1 >= 1) { prevlineres = rstate.resolution[p.line - 1]; } if(prevlineres != null && prevlineres.type == BranchResolution.Type.ELSE && !prevlineres.matched) { r.type = BranchResolution.Type.IF_ELSE; prevlineres.matched = true; resolve(state, declList, rstate, next); prevlineres.matched = false; } r.type = BranchResolution.Type.IF_END; resolve(state, declList, rstate, next); } } p = p.previous; } BranchResolution prevlineres = null; r.line = b.targetSecond; if(b.targetSecond - 1 >= 1) { prevlineres = rstate.resolution[b.targetSecond - 1]; } if(prevlineres != null && prevlineres.type == BranchResolution.Type.ELSE && !prevlineres.matched) { r.type = BranchResolution.Type.IF_ELSE; prevlineres.matched = true; resolve(state, declList, rstate, next); prevlineres.matched = false; } r.type = BranchResolution.Type.IF_END; resolve(state, declList, rstate, next); rstate.resolution[b.line] = null; } else if(b.type == Branch.Type.jump) { BranchResolution r = new BranchResolution(); rstate.resolution[b.line] = r; if(is_break(state, rstate.container, b.targetFirst)) { r.type = BranchResolution.Type.BREAK; r.line = rstate.container.end; resolve(state, declList, rstate, next); } Branch p = state.end_branch; while(p != b) { if(p.type == Branch.Type.jump && enclosing_breakable_block(state, p.line) == rstate.container) { if(p.targetFirst == b.targetFirst) { r.type = BranchResolution.Type.ELSE; r.line = p.line; resolve(state, declList, rstate, next); } } p = p.previous; } r.type = BranchResolution.Type.ELSE; r.line = b.targetFirst; resolve(state, declList, rstate, next); r.type = BranchResolution.Type.PSEUDO_GOTO; resolve(state, declList, rstate, next); rstate.resolution[b.line] = null; } else { resolve(state, declList, rstate, next); } } private static void find_other_statements(State state, Declaration[] declList) { List<Block> containers = new ArrayList<Block>(); for(Block block : state.blocks) { if(block.breakable()) { containers.add(block); } } containers.add(null); for(Block container : containers) { Branch b = state.end_branch; while(b != null && enclosing_breakable_block(state, b.line) != container) { b = b.previous; } //System.out.println("resolve " + (container == null ? 0 : container.begin)); ResolutionState rstate = new ResolutionState(state, container); resolve(state, declList, rstate, b); if(rstate.results.isEmpty()) throw new IllegalStateException("couldn't resolve breaks for " + (container == null ? 0 : container.begin)); state.blocks.addAll(rstate.results.get(0).blocks); } } private static void find_break_statements(State state) { List<Block> blocks = state.blocks; Branch b = state.end_branch; LinkedList<Branch> breaks = new LinkedList<Branch>(); while(b != null) { if(b.type == Branch.Type.jump) { int line = b.line; Block enclosing = enclosing_breakable_block(state, line); if(enclosing != null && (b.targetFirst == enclosing.end || b.targetFirst == state.resolved[enclosing.end])) { Break block = new Break(state.function, b.line, b.targetFirst); unredirect_break(state, line, enclosing); blocks.add(block); breaks.addFirst(b); } } b = b.previous; } b = state.begin_branch; List<Branch> ifStack = new ArrayList<Branch>(); while(b != null) { Block enclosing = enclosing_breakable_block(state, b.line); while(!ifStack.isEmpty()) { Block outer = enclosing_breakable_block(state, ifStack.get(ifStack.size() - 1).line); if(enclosing == null || (outer != enclosing && !outer.contains(enclosing))) { ifStack.remove(ifStack.size() - 1); } else { break; } } if(is_conditional(b)) { //System.err.println("conditional " + b.line + " " + b.targetSecond); if(enclosing != null && b.targetSecond >= enclosing.end) { ifStack.add(b); } } else if(b.type == Branch.Type.jump) { //System.err.println("lingering jump " + b.line); if(enclosing != null && b.targetFirst < enclosing.end && !ifStack.isEmpty()) { if(b.line <= state.code.length - 1 && state.branches[b.line + 1] != null) { Branch prev = state.branches[b.line + 1]; if(prev.type == Branch.Type.jump && (prev.targetFirst == enclosing.end || prev.targetFirst == state.resolved[enclosing.end])) { Branch candidate = ifStack.get(ifStack.size() - 1); if(state.resolved[candidate.targetSecond] == state.resolved[prev.targetFirst]) { candidate.targetSecond = prev.line; ifStack.remove(ifStack.size() - 1); } } } } } b = b.next; } b = state.begin_branch; while(b != null) { if(is_conditional(b)) { Block enclosing = enclosing_breakable_block(state, b.line); if(enclosing != null && (b.targetSecond >= enclosing.end || b.targetSecond < enclosing.begin)) { if(state.function.header.version.usesIfBreakRewrite()) { Block block = new IfThenEndBlock(state.function, state.r, b.cond.inverse(), b.targetFirst - 1, b.targetFirst - 1, false); block.addStatement(new Break(state.function, b.targetFirst - 1, b.targetSecond)); state.blocks.add(block); remove_branch(state, b); } else { for(Branch br : breaks) { if(br.line >= b.targetFirst && br.line < b.targetSecond && br.line < enclosing.end) { Branch tbr = br; while(b.targetSecond != tbr.targetSecond) { Branch next = state.branches[tbr.targetSecond]; if(next != null && next.type == Branch.Type.jump) { tbr = next; // TODO: guard against infinite loop } else { break; } } if(b.targetSecond == tbr.targetSecond) { b.targetSecond = br.line; } } } } } } b = b.next; } for(Branch br : breaks) { remove_branch(state, br); } } private static void find_pseudo_goto_statements(State state, Declaration[] declList) { Branch b = state.begin_branch; while(b != null) { if(b.type == Branch.Type.jump && b.targetFirst > b.line) { int end = b.targetFirst; Block smallestEnclosing = null; for(Block block : state.blocks) { if(block.contains(b.line) && block.contains(end - 1)) { if(smallestEnclosing == null || smallestEnclosing.contains(block)) { smallestEnclosing = block; } } } if(smallestEnclosing != null) { // Should always find the outer block at least... Block wrapping = null; for(Block block : state.blocks) { if(block != smallestEnclosing && smallestEnclosing.contains(block) && block.contains(b.line)) { if(wrapping == null || block.contains(wrapping)) { wrapping = block; } } } int begin = smallestEnclosing.begin; //int beginMin = begin; //int beginMax = b.line; if(wrapping != null) { begin = Math.max(wrapping.begin - 1, smallestEnclosing.begin); //beginMax = begin; } for(Declaration decl : declList) { if(decl.begin >= begin && decl.begin < end) { } if(decl.end >= begin && decl.end < end) { if(decl.begin < begin) { begin = decl.begin; } } } state.blocks.add(new OnceLoop(state.function, begin, end)); state.blocks.add(new Break(state.function, b.line, b.targetFirst)); remove_branch(state, b); } } b = b.next; } } private static void find_do_blocks(State state, Declaration[] declList) { for(Declaration decl : declList) { int begin = decl.begin; if(!decl.forLoop && !decl.forLoopExplicit) { boolean needsDoEnd = true; for(Block block : state.blocks) { if(block.contains(decl.begin)) { if(block.scopeEnd() == decl.end) { block.useScope(); needsDoEnd = false; break; } else if(block.scopeEnd() < decl.end) { begin = Math.min(begin, block.begin); } } } if(needsDoEnd) { // Without accounting for the order of declarations, we might // create another do..end block later that would eliminate the // need for this one. But order of decls should fix this. state.blocks.add(new DoEndBlock(state.function, begin, decl.end + 1)); } } } } private static boolean is_conditional(Branch b) { return b.type == Branch.Type.comparison || b.type == Branch.Type.test; } private static boolean is_assignment(Branch b) { return b.type == Branch.Type.testset; } private static boolean is_assignment(Branch b, int r) { return b.type == Branch.Type.testset || b.type == Branch.Type.test && b.target == r; } private static boolean adjacent(State state, Branch branch0, Branch branch1) { if(branch0 == null || branch1 == null) { return false; } else { boolean adjacent = branch0.targetFirst <= branch1.line; if(adjacent) { adjacent = !has_statement(state, branch0.targetFirst, branch1.line - 1); adjacent = adjacent && !state.reverse_targets[branch1.line]; } return adjacent; } } private static Branch combine_left(State state, Branch branch1) { if(is_conditional(branch1)) { return combine_conditional(state, branch1); } else if(is_assignment(branch1) || branch1.type == Branch.Type.finalset) { return combine_assignment(state, branch1); } else { return branch1; } } private static Branch combine_conditional(State state, Branch branch1) { Branch branch0 = branch1.previous; Branch branchn = branch1; while(branch0 != null && branchn == branch1) { branchn = combine_conditional_helper(state, branch0, branch1); if(branch0.targetSecond > branch1.targetFirst) break; branch0 = branch0.previous; } return branchn; } private static Branch combine_conditional_helper(State state, Branch branch0, Branch branch1) { if(adjacent(state, branch0, branch1) && is_conditional(branch0) && is_conditional(branch1)) { int branch0TargetSecond = branch0.targetSecond; if(is_jmp(state, branch1.targetFirst) && state.code.target(branch1.targetFirst) == branch0TargetSecond) { // Handle redirected target branch0TargetSecond = branch1.targetFirst; } if(branch0TargetSecond == branch1.targetFirst) { // Combination if not branch0 or branch1 then branch0 = combine_conditional(state, branch0); Condition c = new OrCondition(branch0.cond.inverse(), branch1.cond); Branch branchn = new Branch(branch0.line, Branch.Type.comparison, c, branch1.targetFirst, branch1.targetSecond); branchn.inverseValue = branch1.inverseValue; if(verbose) System.err.println("conditional or " + branchn.line); replace_branch(state, branch0, branch1, branchn); return combine_conditional(state, branchn); } else if(branch0TargetSecond == branch1.targetSecond) { // Combination if branch0 and branch1 then branch0 = combine_conditional(state, branch0); Condition c = new AndCondition(branch0.cond, branch1.cond); Branch branchn = new Branch(branch0.line, Branch.Type.comparison, c, branch1.targetFirst, branch1.targetSecond); branchn.inverseValue = branch1.inverseValue; if(verbose) System.err.println("conditional and " + branchn.line); replace_branch(state, branch0, branch1, branchn); return combine_conditional(state, branchn); } } return branch1; } private static Branch combine_assignment(State state, Branch branch1) { Branch branch0 = branch1.previous; Branch branchn = branch1; while(branch0 != null && branchn == branch1) { branchn = combine_assignment_helper(state, branch0, branch1); if(branch0.targetSecond > branch1.targetFirst) break; branch0 = branch0.previous; } return branchn; } private static Branch combine_assignment_helper(State state, Branch branch0, Branch branch1) { if(adjacent(state, branch0, branch1)) { int register = branch1.target; if(branch1.target == -1) { throw new IllegalStateException(); } //System.err.println("blah " + branch1.line + " " + branch0.line); if(is_conditional(branch0) && is_assignment(branch1)) { //System.err.println("bridge cand " + branch1.line + " " + branch0.line); if(branch0.targetSecond == branch1.targetFirst) { boolean inverse = branch0.inverseValue; if(verbose) System.err.println("bridge " + (inverse ? "or" : "and") + " " + branch1.line + " " + branch0.line); branch0 = combine_conditional(state, branch0); if(inverse != branch0.inverseValue) throw new IllegalStateException(); Condition c; if(!branch1.inverseValue) { //System.err.println("bridge or " + branch0.line + " " + branch0.inverseValue); c = new OrCondition(branch0.cond.inverse(), branch1.cond); } else { //System.err.println("bridge and " + branch0.line + " " + branch0.inverseValue); c = new AndCondition(branch0.cond, branch1.cond); } Branch branchn = new Branch(branch0.line, branch1.type, c, branch1.targetFirst, branch1.targetSecond); branchn.inverseValue = branch1.inverseValue; branchn.target = register; replace_branch(state, branch0, branch1, branchn); return combine_assignment(state, branchn); } else if(branch0.targetSecond == branch1.targetSecond) { /* Condition c = new AndCondition(branch0.cond, branch1.cond); Branch branchn = new Branch(branch0.line, Branch.Type.comparison, c, branch1.targetFirst, branch1.targetSecond); replace_branch(state, branch0, branch1, branchn); return branchn; */ } } if(is_assignment(branch0, register) && is_assignment(branch1) && branch0.inverseValue == branch1.inverseValue) { if(branch0.targetSecond == branch1.targetSecond) { Condition c; //System.err.println("preassign " + branch1.line + " " + branch0.line + " " + branch0.targetSecond); if(verbose) System.err.println("assign " + (branch0.inverseValue ? "or" : "and") + " " + branch1.line + " " + branch0.line); if(is_conditional(branch0)) { branch0 = combine_conditional(state, branch0); if(branch0.inverseValue) { branch0.cond = branch0.cond.inverse(); // inverse has been double handled; undo it } } else { boolean inverse = branch0.inverseValue; branch0 = combine_assignment(state, branch0); if(inverse != branch0.inverseValue) throw new IllegalStateException(); } if(branch0.inverseValue) { //System.err.println("assign and " + branch1.line + " " + branch0.line); c = new OrCondition(branch0.cond, branch1.cond); } else { //System.err.println("assign or " + branch1.line + " " + branch0.line); c = new AndCondition(branch0.cond, branch1.cond); } Branch branchn = new Branch(branch0.line, branch1.type, c, branch1.targetFirst, branch1.targetSecond); branchn.inverseValue = branch1.inverseValue; branchn.target = register; replace_branch(state, branch0, branch1, branchn); return combine_assignment(state, branchn); } } if(is_assignment(branch0, register) && branch1.type == Branch.Type.finalset) { if(branch0.targetSecond == branch1.targetSecond) { Condition c; //System.err.println("final preassign " + branch1.line + " " + branch0.line); if(is_conditional(branch0)) { branch0 = combine_conditional(state, branch0); if(branch0.inverseValue) { branch0.cond = branch0.cond.inverse(); // inverse has been double handled; undo it } } else { boolean inverse = branch0.inverseValue; branch0 = combine_assignment(state, branch0); if(inverse != branch0.inverseValue) throw new IllegalStateException(); } if(verbose) System.err.println("final assign " + (branch0.inverseValue ? "or" : "and") + " " + branch1.line + " " + branch0.line); if(branch0.inverseValue) { //System.err.println("final assign or " + branch1.line + " " + branch0.line); c = new OrCondition(branch0.cond, branch1.cond); } else { //System.err.println("final assign and " + branch1.line + " " + branch0.line); c = new AndCondition(branch0.cond, branch1.cond); } Branch branchn = new Branch(branch0.line, Branch.Type.finalset, c, branch1.targetFirst, branch1.targetSecond); branchn.target = register; replace_branch(state, branch0, branch1, branchn); return combine_assignment(state, branchn); } } } return branch1; } private static Branch[] branches(State state, Branch b) { if(b.type == Branch.Type.finalset) { return state.finalsetbranches; } else if(b.type == Branch.Type.testset) { return state.setbranches; } else { return state.branches; } } private static void replace_branch(State state, Branch branch0, Branch branch1, Branch branchn) { remove_branch(state, branch0); branches(state, branch1)[branch1.line] = null; branchn.previous = branch1.previous; if(branchn.previous == null) { state.begin_branch = branchn; } else { branchn.previous.next = branchn; } branchn.next = branch1.next; if(branchn.next == null) { state.end_branch = branchn; } else { branchn.next.previous = branchn; } branches(state, branchn)[branchn.line] = branchn; } private static void remove_branch(State state, Branch b) { branches(state, b)[b.line] = null; Branch prev = b.previous; Branch next = b.next; if(prev != null) { prev.next = next; } else { state.begin_branch = next; } if(next != null) { next.previous = prev; } else { state.end_branch = prev; } } private static void insert_branch(State state, Branch b) { branches(state, b)[b.line] = b; } private static void link_branches(State state) { Branch previous = null; for(int index = 0; index < state.branches.length; index++) { for(int array = 0; array < 3; array ++) { Branch[] branches; if(array == 0) { branches = state.finalsetbranches; } else if(array == 1) { branches = state.setbranches; } else { branches = state.branches; } Branch b = branches[index]; if(b != null) { b.previous = previous; if(previous != null) { previous.next = b; } else { state.begin_branch = b; } previous = b; } } } state.end_branch = previous; } private static int get_target(State state, int line) { Code code = state.code; if(code.isUpvalueDeclaration(line)) { line--; while(code.op(line) != Op.CLOSURE) line--; int codepoint = code.codepoint(line); int target = Op.CLOSURE.target(codepoint, code.getExtractor()); return target; } else { Op op = code.op(line); int codepoint = code.codepoint(line); int target = op.target(codepoint, code.getExtractor()); if(target == -1) { // Special handling for table literals switch(op) { case SETLIST: case SETLISTO: case SETLIST50: case SETLIST52: case SETTABLE: target = code.A(line); break; case EXTRABYTE: if(line >= 2 && code.op(line - 1) == Op.SETLIST) { target = code.A(line - 1); } break; case EXTRAARG: if(line >= 2 && code.op(line - 1) == Op.SETLIST52) { target = code.A(line - 1); } break; default: break; } } return target; } } private static boolean is_jmp_raw(State state, int line) { Op op = state.code.op(line); return op == Op.JMP || op == Op.JMP52; } private static boolean is_jmp(State state, int line) { Code code = state.code; Op op = code.op(line); if(op == Op.JMP) { return true; } else if(op == Op.JMP52) { return !is_close(state, line); } else { return false; } } private static boolean is_close(State state, int line) { Code code = state.code; Op op = code.op(line); if(op == Op.CLOSE) { return true; } else if(op == Op.JMP52) { int target = code.target(line); if(target == line + 1) { return code.A(line) != 0; } else { if(line + 1 <= code.length && code.op(line + 1) == Op.JMP52) { return target == code.target(line + 1) && code.A(line) != 0; } else { return false; } } } else { return false; } } private static boolean has_statement(State state, int begin, int end) { for(int line = begin; line <= end; line++) { if(is_statement(state, line)) { return true; } } return state.d.hasStatement(begin, end); } private static boolean is_statement(State state, int line) { if(state.reverse_targets[line]) return true; Registers r = state.r; if(!r.getNewLocals(line).isEmpty()) return true; Code code = state.code; if(code.isUpvalueDeclaration(line)) return false; switch(code.op(line)) { case MOVE: case LOADK: case LOADKX: case LOADBOOL: case GETUPVAL: case GETTABUP: case GETGLOBAL: case GETTABLE: case NEWTABLE: case NEWTABLE50: case ADD: case SUB: case MUL: case DIV: case MOD: case POW: case IDIV: case BAND: case BOR: case BXOR: case SHL: case SHR: case UNM: case NOT: case LEN: case BNOT: case CONCAT: case CLOSURE: case TESTSET: return r.isLocal(code.A(line), line); case LOADNIL: for(int register = code.A(line); register <= code.B(line); register++) { if(r.isLocal(register, line)) { return true; } } return false; case LOADNIL52: for(int register = code.A(line); register <= code.A(line) + code.B(line); register++) { if(r.isLocal(register, line)) { return true; } } return false; case SETGLOBAL: case SETUPVAL: case SETTABUP: case TAILCALL: case RETURN: case FORLOOP: case FORPREP: case TFORCALL: case TFORLOOP: case TFORPREP: case CLOSE: return true; case TEST50: return code.A(line) != code.B(line) && r.isLocal(code.A(line), line); case SELF: return r.isLocal(code.A(line), line) || r.isLocal(code.A(line) + 1, line); case EQ: case LT: case LE: case TEST: case SETLIST: case SETLIST52: case SETLIST50: case SETLISTO: case EXTRAARG: case EXTRABYTE: return false; case JMP: case JMP52: // TODO: CLOSE? if(line == 1) { return true; } else { Op prev = line >= 2 ? code.op(line - 1) : null; Op next = line + 1 <= code.length ? code.op(line + 1) : null; if(prev == Op.EQ) return false; if(prev == Op.LT) return false; if(prev == Op.LE) return false; if(prev == Op.TEST) return false; if(prev == Op.TESTSET) return false; if(prev == Op.TEST50) return false; if(next == Op.LOADBOOL && code.C(line + 1) != 0) return false; return true; } case CALL: { int a = code.A(line); int c = code.C(line); if(c == 1) { return true; } if(c == 0) c = r.registers - a + 1; for(int register = a; register < a + c - 1; register++) { if(r.isLocal(register, line)) { return true; } } return false; } case VARARG: { int a = code.A(line); int b = code.B(line); if(b == 0) b = r.registers - a + 1; for(int register = a; register < a + b - 1; register++) { if(r.isLocal(register, line)) { return true; } } return false; } case SETTABLE: // special case -- this is actually ambiguous and must be resolved by the decompiler check return false; } throw new IllegalStateException("Illegal opcode: " + code.op(line)); } // static only private ControlFlowHandler() { } }
src/unluac/decompile/ControlFlowHandler.java
package unluac.decompile; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import unluac.Version; import unluac.decompile.block.AlwaysLoop; import unluac.decompile.block.Block; import unluac.decompile.block.Break; import unluac.decompile.block.DoEndBlock; import unluac.decompile.block.ForBlock; import unluac.decompile.block.ElseEndBlock; import unluac.decompile.block.ForBlock50; import unluac.decompile.block.ForBlock51; import unluac.decompile.block.IfThenElseBlock; import unluac.decompile.block.IfThenEndBlock; import unluac.decompile.block.OnceLoop; import unluac.decompile.block.RepeatBlock; import unluac.decompile.block.SetBlock; import unluac.decompile.block.TForBlock50; import unluac.decompile.block.TForBlock51; import unluac.decompile.block.WhileBlock; import unluac.decompile.block.OuterBlock; import unluac.decompile.block.TForBlock; import unluac.decompile.condition.AndCondition; import unluac.decompile.condition.BinaryCondition; import unluac.decompile.condition.Condition; import unluac.decompile.condition.ConstantCondition; import unluac.decompile.condition.OrCondition; import unluac.decompile.condition.RegisterSetCondition; import unluac.decompile.condition.SetCondition; import unluac.decompile.condition.TestCondition; import unluac.parse.LFunction; public class ControlFlowHandler { public static boolean verbose = false; private static class Branch implements Comparable<Branch> { private static enum Type { comparison, test, testset, finalset, jump; } public Branch previous; public Branch next; public int line; public int target; public Type type; public Condition cond; public int targetFirst; public int targetSecond; public boolean inverseValue; public Branch(int line, Type type, Condition cond, int targetFirst, int targetSecond) { this.line = line; this.type = type; this.cond = cond; this.targetFirst = targetFirst; this.targetSecond = targetSecond; this.inverseValue = false; this.target = -1; } @Override public int compareTo(Branch other) { return this.line - other.line; } } private static class State { public Decompiler d; public LFunction function; public Registers r; public Code code; public Branch begin_branch; public Branch end_branch; public Branch[] branches; public Branch[] setbranches; public Branch[] finalsetbranches; public boolean[] reverse_targets; public int[] resolved; public List<Block> blocks; } public static List<Block> process(Decompiler d, Registers r) { State state = new State(); state.d = d; state.function = d.function; state.r = r; state.code = d.code; find_reverse_targets(state); find_branches(state); combine_branches(state); resolve_lines(state); initialize_blocks(state); find_fixed_blocks(state); find_while_loops(state); find_repeat_loops(state); //find_break_statements(state); //find_if_blocks(state); find_other_statements(state, d.declList); find_set_blocks(state); //find_pseudo_goto_statements(state, d.declList); find_do_blocks(state, d.declList); Collections.sort(state.blocks); // DEBUG: print branches stuff /* Branch b = state.begin_branch; while(b != null) { System.out.println("Branch at " + b.line); System.out.println("\tcondition: " + b.cond); b = b.next; } */ return state.blocks; } private static void find_reverse_targets(State state) { Code code = state.code; boolean[] reverse_targets = state.reverse_targets = new boolean[state.code.length + 1]; for(int line = 1; line <= code.length; line++) { if(is_jmp(state, line)) { int target = code.target(line); if(target <= line) { reverse_targets[target] = true; } } } } private static void resolve_lines(State state) { int[] resolved = new int[state.code.length + 1]; Arrays.fill(resolved, -1); for(int line = 1; line <= state.code.length; line++) { int r = line; Branch b = state.branches[line]; while(b != null && b.type == Branch.Type.jump) { if(resolved[r] >= 1) { r = resolved[r]; break; } else if(resolved[r] == -2) { r = b.targetSecond; break; } else { resolved[r] = -2; r = b.targetSecond; b = state.branches[r]; } } resolved[line] = r; } state.resolved = resolved; } private static int find_loadboolblock(State state, int target) { int loadboolblock = -1; if(state.code.op(target) == Op.LOADBOOL) { if(state.code.C(target) != 0) { loadboolblock = target; } else if(target - 1 >= 1 && state.code.op(target - 1) == Op.LOADBOOL && state.code.C(target - 1) != 0) { loadboolblock = target - 1; } } return loadboolblock; } private static void handle_loadboolblock(State state, boolean[] skip, int loadboolblock, Condition c, int line, int target) { int loadboolvalue = state.code.B(target); int final_line = -1; if(loadboolblock - 1 >= 1 && is_jmp(state, loadboolblock - 1)) { int boolskip_target = state.code.target(loadboolblock - 1); int boolskip_target_redirected = -1; if(is_jmp_raw(state, loadboolblock + 2)) { boolskip_target_redirected = state.code.target(loadboolblock + 2); } if(boolskip_target == loadboolblock + 2 || boolskip_target == boolskip_target_redirected) { skip[loadboolblock - 1] = true; final_line = loadboolblock - 2; } } boolean inverse = false; if(loadboolvalue == 1) { inverse = true; c = c.inverse(); } boolean constant = is_jmp(state, line); Branch b; int begin = line + 2; if(constant) { begin--; b = new Branch(line, Branch.Type.testset, c, begin, loadboolblock + 2); } else if(line + 2 == loadboolblock) { b = new Branch(line, Branch.Type.finalset, c, begin, loadboolblock + 2); } else { b = new Branch(line, Branch.Type.testset, c, begin, loadboolblock + 2); } b.target = state.code.A(loadboolblock); b.inverseValue = inverse; insert_branch(state, b); if(constant && final_line < begin && state.finalsetbranches[final_line + 1] == null) { c = new TestCondition(final_line + 1, state.code.A(target)); b = new Branch(final_line + 1, Branch.Type.finalset, c, final_line, loadboolblock + 2); b.target = state.code.A(loadboolblock); insert_branch(state, b); } if(final_line >= begin && state.finalsetbranches[final_line] == null) { c = new SetCondition(final_line, get_target(state, final_line)); b = new Branch(final_line, Branch.Type.finalset, c, final_line, loadboolblock + 2); b.target = state.code.A(loadboolblock); insert_branch(state, b); } if(final_line + 1 == begin && state.finalsetbranches[final_line + 1] == null) { c = new RegisterSetCondition(loadboolblock, get_target(state, loadboolblock)); b = new Branch(final_line + 1, Branch.Type.finalset, c, final_line, loadboolblock + 2); b.target = state.code.A(loadboolblock); insert_branch(state, b); } } private static void find_branches(State state) { Code code = state.code; state.branches = new Branch[state.code.length + 1]; state.setbranches = new Branch[state.code.length + 1]; state.finalsetbranches = new Branch[state.code.length + 1]; boolean[] skip = new boolean[code.length + 1]; for(int line = 1; line <= code.length; line++) { if(!skip[line]) { switch(code.op(line)) { case EQ: case LT: case LE: { BinaryCondition.Operator op = BinaryCondition.Operator.EQ; if(code.op(line) == Op.LT) op = BinaryCondition.Operator.LT; if(code.op(line) == Op.LE) op = BinaryCondition.Operator.LE; int left = code.B(line); int right = code.C(line); int target = code.target(line + 1); Condition c = new BinaryCondition(op, line, left, right); if(code.A(line) == 1) { c = c.inverse(); } int loadboolblock = find_loadboolblock(state, target); if(loadboolblock >= 1) { handle_loadboolblock(state, skip, loadboolblock, c, line, target); } else { Branch b = new Branch(line, Branch.Type.comparison, c, line + 2, target); if(code.A(line) == 1) { b.inverseValue = true; } insert_branch(state, b); } skip[line + 1] = true; break; } case TEST50: { Condition c = new TestCondition(line, code.B(line)); int target = code.target(line + 1); if(code.A(line) == code.B(line)) { if(code.C(line) != 0) c = c.inverse(); int loadboolblock = find_loadboolblock(state, target); if(loadboolblock >= 1) { handle_loadboolblock(state, skip, loadboolblock, c, line, target); } else { Branch b = new Branch(line, Branch.Type.test, c, line + 2, target); b.target = code.A(line); if(code.C(line) != 0) b.inverseValue = true; insert_branch(state, b); } } else { Branch b = new Branch(line, Branch.Type.testset, c, line + 2, target); b.target = code.A(line); if(code.C(line) != 0) b.inverseValue = true; skip[line + 1] = true; insert_branch(state, b); int final_line = target - 1; if(state.finalsetbranches[final_line] == null) { int loadboolblock = find_loadboolblock(state, target - 2); if(loadboolblock == -1) { if(line + 2 == target) { c = new RegisterSetCondition(line, get_target(state, line)); final_line = final_line + 1; } else { c = new SetCondition(final_line, get_target(state, final_line)); } b = new Branch(final_line, Branch.Type.finalset, c, target, target); b.target = code.A(line); insert_branch(state, b); } } break; } skip[line + 1] = true; break; } case TEST: { Condition c = new TestCondition(line, code.A(line)); if(code.C(line) != 0) c = c.inverse(); int target = code.target(line + 1); int loadboolblock = find_loadboolblock(state, target); if(loadboolblock >= 1) { handle_loadboolblock(state, skip, loadboolblock, c, line, target); } else { Branch b = new Branch(line, Branch.Type.test, c, line + 2, target); b.target = code.A(line); if(code.C(line) != 0) b.inverseValue = true; insert_branch(state, b); } skip[line + 1] = true; break; } case TESTSET: { Condition c = new TestCondition(line, code.B(line)); int target = code.target(line + 1); Branch b = new Branch(line, Branch.Type.testset, c, line + 2, target); b.target = code.A(line); if(code.C(line) != 0) b.inverseValue = true; skip[line + 1] = true; insert_branch(state, b); int final_line = target - 1; if(state.finalsetbranches[final_line] == null) { int loadboolblock = find_loadboolblock(state, target - 2); if(loadboolblock == -1) { if(line + 2 == target) { c = new RegisterSetCondition(line, get_target(state, line)); final_line = final_line + 1; } else { c = new SetCondition(final_line, get_target(state, final_line)); } b = new Branch(final_line, Branch.Type.finalset, c, target, target); b.target = code.A(line); insert_branch(state, b); } } break; } case JMP: case JMP52: { if(is_jmp(state, line)) { int target = code.target(line); int loadboolblock = find_loadboolblock(state, target); if(loadboolblock >= 1) { handle_loadboolblock(state, skip, loadboolblock, new ConstantCondition(-1, false), line, target); } else { Branch b = new Branch(line, Branch.Type.jump, null, target, target); insert_branch(state, b); } } break; } default: break; } } } link_branches(state); } private static void combine_branches(State state) { Branch b; b = state.end_branch; while(b != null) { b = combine_left(state, b).previous; } } private static void initialize_blocks(State state) { state.blocks = new LinkedList<Block>(); } private static void find_fixed_blocks(State state) { List<Block> blocks = state.blocks; Registers r = state.r; Code code = state.code; Op tforTarget = state.function.header.version.getTForTarget(); Op forTarget = state.function.header.version.getForTarget(); blocks.add(new OuterBlock(state.function, state.code.length)); boolean[] loop = new boolean[state.code.length + 1]; Branch b = state.begin_branch; while(b != null) { if(b.type == Branch.Type.jump) { int line = b.line; int target = b.targetFirst; if(code.op(target) == tforTarget && !loop[target]) { loop[target] = true; int A = code.A(target); int C = code.C(target); if(C == 0) throw new IllegalStateException(); remove_branch(state, state.branches[line]); if(state.branches[target + 1] != null) { remove_branch(state, state.branches[target + 1]); } boolean forvarClose = false; boolean innerClose = false; int close = target - 1; if(close >= line + 1 && is_close(state, close) && code.A(close) == A + 3) { forvarClose = true; close--; } if(close >= line + 1 && is_close(state, close) && code.A(close) <= A + 3 + C) { innerClose = true; } TForBlock block = new TForBlock51(state.function, line + 1, target + 2, A, C, forvarClose, innerClose); block.handleVariableDeclarations(r); blocks.add(block); } else if(code.op(target) == forTarget && !loop[target]) { loop[target] = true; int A = code.A(target); boolean innerClose = false; int close = target - 1; if(close >= line + 1 && is_close(state, close) && code.A(close) == A + 3) { innerClose = true; } ForBlock block = new ForBlock50(state.function, line + 1, target + 1, A, innerClose); block.handleVariableDeclarations(r); blocks.add(block); remove_branch(state, b); } } b = b.next; } for(int line = 1; line <= code.length; line++) { switch(code.op(line)) { case FORPREP: { int A = code.A(line); int target = code.target(line); boolean forvarClose = false; boolean innerClose = false; int close = target - 1; if(close >= line + 1 && is_close(state, close) && code.A(close) == A + 3) { forvarClose = true; close--; } if(close >= line + 1 && is_close(state, close) && code.A(close) <= A + 4) { innerClose = true; } ForBlock block = new ForBlock51(state.function, line + 1, target + 1, A, forvarClose, innerClose); block.handleVariableDeclarations(r); blocks.add(block); break; } case TFORPREP: { int target = code.target(line); int A = code.A(target); int C = code.C(target); boolean innerClose = false; int close = target - 1; if(close >= line + 1 && is_close(state, close) && code.A(close) == A + 3 + C) { innerClose = true; } TForBlock block = new TForBlock50(state.function, line + 1, target + 2, A, C, innerClose); block.handleVariableDeclarations(r); blocks.add(block); remove_branch(state, state.branches[target + 1]); break; } default: break; } } } private static void unredirect(State state, int begin, int end, int line, int target) { Branch b = state.begin_branch; while(b != null) { if(b.line >= begin && b.line < end && b.targetSecond == target) { b.targetSecond = line; if(b.targetFirst == target) { b.targetFirst = line; } } b = b.next; } } private static void find_while_loops(State state) { List<Block> blocks = state.blocks; Branch j = state.end_branch; while(j != null) { if(j.type == Branch.Type.jump && j.targetFirst <= j.line) { int line = j.targetFirst; int loopback = line; int end = j.line + 1; Branch b = state.begin_branch; while(b != null) { if(is_conditional(b) && b.line >= loopback && b.line < j.line && state.resolved[b.targetSecond] == state.resolved[end]) { break; } b = b.next; } if(b != null) { boolean reverse = state.reverse_targets[loopback]; state.reverse_targets[loopback] = false; if(has_statement(state, loopback, b.line - 1)) { b = null; } state.reverse_targets[loopback] = reverse; } if(state.function.header.version == Version.LUA50) { b = null; // while loop aren't this style } Block loop; if(b != null) { b.targetSecond = end; remove_branch(state, b); //System.err.println("while " + b.targetFirst + " " + b.targetSecond); loop = new WhileBlock(state.function, b.cond, b.targetFirst, b.targetSecond); unredirect(state, loopback, end, j.line, loopback); } else { boolean repeat = false; if(state.function.header.version == Version.LUA50) { repeat = true; if(loopback - 1 >= 1 && state.branches[loopback - 1] != null) { Branch head = state.branches[loopback - 1]; if(head.type == Branch.Type.jump && head.targetFirst == j.line) { remove_branch(state, head); repeat = false; } } } loop = new AlwaysLoop(state.function, loopback, end, repeat); unredirect(state, loopback, end, j.line, loopback); } remove_branch(state, j); blocks.add(loop); } j = j.previous; } } private static void find_repeat_loops(State state) { List<Block> blocks = state.blocks; Branch b = state.begin_branch; while(b != null) { if(is_conditional(b)) { if(b.targetSecond < b.targetFirst) { Block block = null; if(state.function.header.version == Version.LUA50) { int head = b.targetSecond - 1; if(head >= 1 && state.branches[head] != null && state.branches[head].type == Branch.Type.jump) { Branch headb = state.branches[head]; if(headb.targetSecond <= b.line) { if(has_statement(state, headb.targetSecond, b.line - 1)) { headb = null; } if(headb != null) { block = new WhileBlock(state.function, b.cond.inverse(), head + 1, b.targetFirst); remove_branch(state, headb); unredirect(state, 1, headb.line, headb.line, headb.targetSecond); } } } } if(block == null) { block = new RepeatBlock(state.function, b.cond, b.targetSecond, b.targetFirst); } remove_branch(state, b); blocks.add(block); } } b = b.next; } } private static void find_if_blocks(State state) { Branch b = state.begin_branch; while(b != null) { if(is_conditional(b)) { Block enclosing; enclosing = enclosing_unprotected_block(state, b.line); if(enclosing != null && !enclosing.contains(b.targetSecond)) { if(b.targetSecond == enclosing.getUnprotectedTarget()) { b.targetSecond = enclosing.getUnprotectedLine(); } } Branch tail = b.targetSecond >= 1 ? state.branches[b.targetSecond - 1] : null; if(tail != null && !is_conditional(tail)) { enclosing = enclosing_unprotected_block(state, tail.line); if(enclosing != null && !enclosing.contains(tail.targetSecond)) { if(tail.targetSecond == state.resolved[enclosing.getUnprotectedTarget()]) { tail.targetSecond = enclosing.getUnprotectedLine(); } } //System.err.println("else end " + b.targetFirst + " " + b.targetSecond + " " + tail.targetSecond + " enclosing " + (enclosing != null ? enclosing.begin : -1) + " " + + (enclosing != null ? enclosing.end : -1)); state.blocks.add(new IfThenElseBlock(state.function, b.cond, b.targetFirst, b.targetSecond, tail.targetSecond)); if(b.targetSecond != tail.targetSecond) { state.blocks.add(new ElseEndBlock(state.function, b.targetSecond, tail.targetSecond)); } // else "empty else" case remove_branch(state, tail); unredirect(state, b.targetFirst, b.targetSecond, b.targetSecond - 1, tail.targetSecond); } else { //System.err.println("if end " + b.targetFirst + " " + b.targetSecond); Block breakable = enclosing_breakable_block(state, b.line); if(breakable != null && breakable.end == b.targetSecond) { // 5.2-style if-break Block block = new IfThenEndBlock(state.function, state.r, b.cond.inverse(), b.targetFirst - 1, b.targetFirst - 1, false); block.addStatement(new Break(state.function, b.targetFirst - 1, b.targetSecond)); state.blocks.add(block); } else { int literalEnd = state.code.target(b.targetFirst - 1); state.blocks.add(new IfThenEndBlock(state.function, state.r, b.cond, b.targetFirst, b.targetSecond, literalEnd != b.targetSecond)); } } remove_branch(state, b); } b = b.next; } } private static void find_set_blocks(State state) { List<Block> blocks = state.blocks; Branch b = state.begin_branch; while(b != null) { if(is_assignment(b) || b.type == Branch.Type.finalset) { Block block = new SetBlock(state.function, b.cond, b.target, b.line, b.targetFirst, b.targetSecond, state.r); blocks.add(block); remove_branch(state, b); } b = b.next; } } private static Block enclosing_breakable_block(State state, int line) { Block enclosing = null; for(Block block : state.blocks) { if(block.contains(line) && block.breakable()) { if(enclosing == null || enclosing.contains(block)) { enclosing = block; } } } return enclosing; } private static Block enclosing_unprotected_block(State state, int line) { Block enclosing = null; for(Block block : state.blocks) { if(block.contains(line) && block.isUnprotected()) { if(enclosing == null || enclosing.contains(block)) { enclosing = block; } } } return enclosing; } private static void unredirect_break(State state, int line, Block enclosing) { Branch b = state.begin_branch; while(b != null) { Block breakable = enclosing_breakable_block(state, b.line); if(b.line != line && breakable != null && b.type == Branch.Type.jump && breakable == enclosing && b.targetFirst == enclosing.end) { //System.err.println("redirect break " + b.line + " from " + b.targetFirst + " to " + line); boolean condsplit = false; Branch c = state.begin_branch; while(c != null) { if(is_conditional(c) && c.targetSecond < breakable.end) { if(c.targetFirst <= line && line < c.targetSecond) { if(c.targetFirst <= b.line && b.line < c.targetSecond) { } else { condsplit = true; break; } } } c = c.next; } if(!condsplit) { b.targetFirst = line; b.targetSecond = line; } } b = b.next; } } private static class BranchResolution { enum Type { IF_END, IF_ELSE, IF_BREAK, ELSE, BREAK, PSEUDO_GOTO, }; Type type; int line; boolean matched; } private static class Pair { Pair(int begin, int end) { this.begin = begin; this.end = end; } int begin; int end; } private static class ResolutionResult { List<Block> blocks = new ArrayList<Block>(); } private static ResolutionResult finishResolution(State state, Declaration[] declList, Block container, BranchResolution[] resolution) { ResolutionResult result = new ResolutionResult(); for(int i = 0; i < resolution.length; i++) { BranchResolution r = resolution[i]; if(r != null) { Branch b = state.branches[i]; if(b == null) throw new IllegalStateException(); switch(r.type) { case ELSE: break; case BREAK: result.blocks.add(new Break(state.function, b.line, r.line)); break; case PSEUDO_GOTO: // handled in second pass break; case IF_END: int literalEnd = state.code.target(b.targetFirst - 1); result.blocks.add(new IfThenEndBlock(state.function, state.r, b.cond, b.targetFirst, r.line, literalEnd != r.line)); break; case IF_ELSE: BranchResolution r_else = resolution[r.line - 1]; if(r_else == null) throw new IllegalStateException(); result.blocks.add(new IfThenElseBlock(state.function, b.cond, b.targetFirst, r.line, r_else.line)); if(r.line != r_else.line) { result.blocks.add(new ElseEndBlock(state.function, r.line, r_else.line)); } // else "empty else" case break; case IF_BREAK: Block block = new IfThenEndBlock(state.function, state.r, b.cond.inverse(), b.targetFirst - 1, b.targetFirst - 1, false); block.addStatement(new Break(state.function, b.targetFirst - 1, r.line)); result.blocks.add(block); break; default: throw new IllegalStateException(); } } } for(int i = 0; i < resolution.length; i++) { BranchResolution r = resolution[i]; if(r != null) { Branch b = state.branches[i]; if(b == null) throw new IllegalStateException(); if(r.type == BranchResolution.Type.PSEUDO_GOTO) { Block smallest = container; if(smallest == null) smallest = state.blocks.get(0); // outer block TODO cleaner way to get for(Block newblock : result.blocks) { if(smallest.contains(newblock) && newblock.contains(b.line) && newblock.contains(r.line - 1)) { smallest = newblock; } } Block wrapping = null; for(Block block : result.blocks) { if(block != smallest && smallest.contains(block) && block.contains(b.line)) { if(wrapping == null || block.contains(wrapping)) { wrapping = block; } } } for(Block block : state.blocks) { if(block != smallest && smallest.contains(block) && block.contains(b.line)) { if(wrapping == null || block.contains(wrapping)) { wrapping = block; } } } int begin; if(wrapping != null) { begin = wrapping.begin - 1; } else { begin = b.line; } for(Declaration decl : declList) { if(decl.begin >= begin && decl.begin < r.line) { } if(decl.end >= begin && decl.end < r.line) { if(decl.begin < begin) { begin = decl.begin; } } } result.blocks.add(new OnceLoop(state.function, begin, r.line)); result.blocks.add(new Break(state.function, b.line, r.line)); } } } return result; } private static boolean debug_resolution = false; private static boolean checkResolution(State state, Block container, BranchResolution[] resolution) { List<Pair> blocks = new ArrayList<Pair>(); List<Pair> pseudoGotos = new ArrayList<Pair>(); for(int i = 0; i < resolution.length; i++) { BranchResolution r = resolution[i]; if(r != null) { Branch b = state.branches[i]; if(b == null) throw new IllegalStateException(); switch(r.type) { case ELSE: if(!r.matched) { if(debug_resolution) System.err.println("unmatched else"); return false; } if(container != null && r.line >= container.end) { if(debug_resolution) System.err.println("invalid else"); return false; } break; case BREAK: if(container == null || r.line < container.end) { if(debug_resolution) System.err.println("invalid break"); return false; } break; case PSEUDO_GOTO: if(container != null && r.line >= container.end) { if(debug_resolution) System.err.println("invalid pseudo goto"); return false; } pseudoGotos.add(new Pair(b.line, r.line)); break; case IF_END: if(container != null && r.line >= container.end) { if(debug_resolution) System.err.println("invalid if end"); return false; } blocks.add(new Pair(b.targetFirst, r.line)); break; case IF_ELSE: if(container != null && r.line >= container.end) { if(debug_resolution) System.err.println("invalid if else"); return false; } BranchResolution r_else = resolution[r.line - 1]; if(r_else == null) throw new IllegalStateException(); blocks.add(new Pair(b.targetFirst, r.line - 1)); blocks.add(new Pair(r.line, r_else.line)); blocks.add(new Pair(b.targetFirst, r_else.line)); break; case IF_BREAK: if(container == null || r.line < container.end) { if(debug_resolution) System.err.println("invalid if break"); return false; } break; default: throw new IllegalStateException(); } } } for(int i = 0; i < blocks.size(); i++) { for(int j = i + 1; j < blocks.size(); j++) { Pair block1 = blocks.get(i); Pair block2 = blocks.get(j); if(block1.end <= block2.begin) { // okay } else if(block2.end <= block1.begin) { // okay } else if(block1.begin <= block2.begin && block2.end <= block1.end) { // okay } else if(block2.begin <= block1.begin && block1.end <= block2.end) { // okay } else { if(debug_resolution) System.err.println("invalid block overlap"); return false; } } } for(Pair pseudoGoto : pseudoGotos) { for(Pair block : blocks) { if(block.begin <= pseudoGoto.end && block.end > pseudoGoto.end) { // block contains end if(block.begin > pseudoGoto.begin || block.end <= pseudoGoto.begin) { // doesn't contain goto if(debug_resolution) System.err.println("invalid pseudo goto block overlap"); return false; } } } } for(int i = 0; i < pseudoGotos.size(); i++) { for(int j = 0; j < pseudoGotos.size(); j++) { Pair goto1 = pseudoGotos.get(i); Pair goto2 = pseudoGotos.get(j); if(goto1.begin >= goto2.begin && goto1.begin < goto2.end) { if(debug_resolution) System.err.println("invalid pseudo goto overlap"); if(goto1.end > goto2.end) return false; } if(goto2.begin >= goto1.begin && goto2.begin < goto1.end) { if(debug_resolution) System.err.println("invalid pseudo goto overlap"); if(goto2.end > goto1.end) return false; } } } // TODO: check for break out of OnceBlock return true; } private static void printResolution(State state, Block container, BranchResolution[] resolution) { List<Pair> blocks = new ArrayList<Pair>(); for(int i = 0; i < resolution.length; i++) { BranchResolution r = resolution[i]; if(r != null) { Branch b = state.branches[i]; if(b == null) throw new IllegalStateException(); System.out.print(r.type + " " + b.line + " " + r.line); if(b.cond != null) System.out.print(" " + b.cond); System.out.println(); } } } private static boolean is_break(State state, Block container, int line) { if(container == null || line < container.end) return false; if(line == container.end) return true; return state.resolved[container.end] == state.resolved[line]; } static int count = 0; private static void resolve(State state, Declaration[] declList, Block container, BranchResolution[] resolution, Branch b, List<ResolutionResult> results) { if(b == null) { if(count > 10000) { //System.err.println("here"); } if(checkResolution(state, container, resolution)) { // printResolution(state, container, resolution); // System.out.println(); results.add(finishResolution(state, declList, container, resolution)); } else { //System.err.println("complete resolution" + count); count++; // System.out.println("failed resolution:"); // printResolution(state, container, resolution); } return; } Branch next = b.previous; while(next != null && enclosing_breakable_block(state, next.line) != container) { next = next.previous; } if(is_conditional(b)) { BranchResolution r = new BranchResolution(); resolution[b.line] = r; if(is_break(state, container, b.targetSecond)) { if(state.function.header.version.usesIfBreakRewrite()) { r.type = BranchResolution.Type.IF_BREAK; r.line = container.end; resolve(state, declList, container, resolution, next, results); } } Branch p = state.end_branch; while(p != b) { if(p.type == Branch.Type.jump && enclosing_breakable_block(state, p.line) == container) { if(p.targetFirst == b.targetSecond) { r.line = p.line; BranchResolution prevlineres = null; if(p.line - 1 >= 1) { prevlineres = resolution[p.line - 1]; } if(prevlineres != null && prevlineres.type == BranchResolution.Type.ELSE && !prevlineres.matched) { r.type = BranchResolution.Type.IF_ELSE; prevlineres.matched = true; resolve(state, declList, container, resolution, next, results); prevlineres.matched = false; } r.type = BranchResolution.Type.IF_END; resolve(state, declList, container, resolution, next, results); } } p = p.previous; } BranchResolution prevlineres = null; r.line = b.targetSecond; if(b.targetSecond - 1 >= 1) { prevlineres = resolution[b.targetSecond - 1]; } if(prevlineres != null && prevlineres.type == BranchResolution.Type.ELSE && !prevlineres.matched) { r.type = BranchResolution.Type.IF_ELSE; prevlineres.matched = true; resolve(state, declList, container, resolution, next, results); prevlineres.matched = false; } r.type = BranchResolution.Type.IF_END; resolve(state, declList, container, resolution, next, results); resolution[b.line] = null; } else if(b.type == Branch.Type.jump) { BranchResolution r = new BranchResolution(); resolution[b.line] = r; if(is_break(state, container, b.targetFirst)) { r.type = BranchResolution.Type.BREAK; r.line = container.end; resolve(state, declList, container, resolution, next, results); } Branch p = state.end_branch; while(p != b) { if(p.type == Branch.Type.jump && enclosing_breakable_block(state, p.line) == container) { if(p.targetFirst == b.targetFirst) { r.type = BranchResolution.Type.ELSE; r.line = p.line; resolve(state, declList, container, resolution, next, results); } } p = p.previous; } r.type = BranchResolution.Type.ELSE; r.line = b.targetFirst; resolve(state, declList, container, resolution, next, results); r.type = BranchResolution.Type.PSEUDO_GOTO; resolve(state, declList, container, resolution, next, results); resolution[b.line] = null; } else { resolve(state, declList, container, resolution, next, results); } } private static void find_other_statements(State state, Declaration[] declList) { List<Block> containers = new ArrayList<Block>(); for(Block block : state.blocks) { if(block.breakable()) { containers.add(block); } } containers.add(null); for(Block container : containers) { List<ResolutionResult> results = new ArrayList<ResolutionResult>(); Branch b = state.end_branch; while(b != null && enclosing_breakable_block(state, b.line) != container) { b = b.previous; } //System.out.println("resolve " + (container == null ? 0 : container.begin)); resolve(state, declList, container, new BranchResolution[state.code.length + 1], b, results); if(results.isEmpty()) throw new IllegalStateException("couldn't resolve breaks for " + (container == null ? 0 : container.begin)); state.blocks.addAll(results.get(0).blocks); } } private static void find_break_statements(State state) { List<Block> blocks = state.blocks; Branch b = state.end_branch; LinkedList<Branch> breaks = new LinkedList<Branch>(); while(b != null) { if(b.type == Branch.Type.jump) { int line = b.line; Block enclosing = enclosing_breakable_block(state, line); if(enclosing != null && (b.targetFirst == enclosing.end || b.targetFirst == state.resolved[enclosing.end])) { Break block = new Break(state.function, b.line, b.targetFirst); unredirect_break(state, line, enclosing); blocks.add(block); breaks.addFirst(b); } } b = b.previous; } b = state.begin_branch; List<Branch> ifStack = new ArrayList<Branch>(); while(b != null) { Block enclosing = enclosing_breakable_block(state, b.line); while(!ifStack.isEmpty()) { Block outer = enclosing_breakable_block(state, ifStack.get(ifStack.size() - 1).line); if(enclosing == null || (outer != enclosing && !outer.contains(enclosing))) { ifStack.remove(ifStack.size() - 1); } else { break; } } if(is_conditional(b)) { //System.err.println("conditional " + b.line + " " + b.targetSecond); if(enclosing != null && b.targetSecond >= enclosing.end) { ifStack.add(b); } } else if(b.type == Branch.Type.jump) { //System.err.println("lingering jump " + b.line); if(enclosing != null && b.targetFirst < enclosing.end && !ifStack.isEmpty()) { if(b.line <= state.code.length - 1 && state.branches[b.line + 1] != null) { Branch prev = state.branches[b.line + 1]; if(prev.type == Branch.Type.jump && (prev.targetFirst == enclosing.end || prev.targetFirst == state.resolved[enclosing.end])) { Branch candidate = ifStack.get(ifStack.size() - 1); if(state.resolved[candidate.targetSecond] == state.resolved[prev.targetFirst]) { candidate.targetSecond = prev.line; ifStack.remove(ifStack.size() - 1); } } } } } b = b.next; } b = state.begin_branch; while(b != null) { if(is_conditional(b)) { Block enclosing = enclosing_breakable_block(state, b.line); if(enclosing != null && (b.targetSecond >= enclosing.end || b.targetSecond < enclosing.begin)) { if(state.function.header.version.usesIfBreakRewrite()) { Block block = new IfThenEndBlock(state.function, state.r, b.cond.inverse(), b.targetFirst - 1, b.targetFirst - 1, false); block.addStatement(new Break(state.function, b.targetFirst - 1, b.targetSecond)); state.blocks.add(block); remove_branch(state, b); } else { for(Branch br : breaks) { if(br.line >= b.targetFirst && br.line < b.targetSecond && br.line < enclosing.end) { Branch tbr = br; while(b.targetSecond != tbr.targetSecond) { Branch next = state.branches[tbr.targetSecond]; if(next != null && next.type == Branch.Type.jump) { tbr = next; // TODO: guard against infinite loop } else { break; } } if(b.targetSecond == tbr.targetSecond) { b.targetSecond = br.line; } } } } } } b = b.next; } for(Branch br : breaks) { remove_branch(state, br); } } private static void find_pseudo_goto_statements(State state, Declaration[] declList) { Branch b = state.begin_branch; while(b != null) { if(b.type == Branch.Type.jump && b.targetFirst > b.line) { int end = b.targetFirst; Block smallestEnclosing = null; for(Block block : state.blocks) { if(block.contains(b.line) && block.contains(end - 1)) { if(smallestEnclosing == null || smallestEnclosing.contains(block)) { smallestEnclosing = block; } } } if(smallestEnclosing != null) { // Should always find the outer block at least... Block wrapping = null; for(Block block : state.blocks) { if(block != smallestEnclosing && smallestEnclosing.contains(block) && block.contains(b.line)) { if(wrapping == null || block.contains(wrapping)) { wrapping = block; } } } int begin = smallestEnclosing.begin; //int beginMin = begin; //int beginMax = b.line; if(wrapping != null) { begin = Math.max(wrapping.begin - 1, smallestEnclosing.begin); //beginMax = begin; } for(Declaration decl : declList) { if(decl.begin >= begin && decl.begin < end) { } if(decl.end >= begin && decl.end < end) { if(decl.begin < begin) { begin = decl.begin; } } } state.blocks.add(new OnceLoop(state.function, begin, end)); state.blocks.add(new Break(state.function, b.line, b.targetFirst)); remove_branch(state, b); } } b = b.next; } } private static void find_do_blocks(State state, Declaration[] declList) { for(Declaration decl : declList) { int begin = decl.begin; if(!decl.forLoop && !decl.forLoopExplicit) { boolean needsDoEnd = true; for(Block block : state.blocks) { if(block.contains(decl.begin)) { if(block.scopeEnd() == decl.end) { block.useScope(); needsDoEnd = false; break; } else if(block.scopeEnd() < decl.end) { begin = Math.min(begin, block.begin); } } } if(needsDoEnd) { // Without accounting for the order of declarations, we might // create another do..end block later that would eliminate the // need for this one. But order of decls should fix this. state.blocks.add(new DoEndBlock(state.function, begin, decl.end + 1)); } } } } private static boolean is_conditional(Branch b) { return b.type == Branch.Type.comparison || b.type == Branch.Type.test; } private static boolean is_assignment(Branch b) { return b.type == Branch.Type.testset; } private static boolean is_assignment(Branch b, int r) { return b.type == Branch.Type.testset || b.type == Branch.Type.test && b.target == r; } private static boolean adjacent(State state, Branch branch0, Branch branch1) { if(branch0 == null || branch1 == null) { return false; } else { boolean adjacent = branch0.targetFirst <= branch1.line; if(adjacent) { adjacent = !has_statement(state, branch0.targetFirst, branch1.line - 1); adjacent = adjacent && !state.reverse_targets[branch1.line]; } return adjacent; } } private static Branch combine_left(State state, Branch branch1) { if(is_conditional(branch1)) { return combine_conditional(state, branch1); } else if(is_assignment(branch1) || branch1.type == Branch.Type.finalset) { return combine_assignment(state, branch1); } else { return branch1; } } private static Branch combine_conditional(State state, Branch branch1) { Branch branch0 = branch1.previous; Branch branchn = branch1; while(branch0 != null && branchn == branch1) { branchn = combine_conditional_helper(state, branch0, branch1); if(branch0.targetSecond > branch1.targetFirst) break; branch0 = branch0.previous; } return branchn; } private static Branch combine_conditional_helper(State state, Branch branch0, Branch branch1) { if(adjacent(state, branch0, branch1) && is_conditional(branch0) && is_conditional(branch1)) { int branch0TargetSecond = branch0.targetSecond; if(is_jmp(state, branch1.targetFirst) && state.code.target(branch1.targetFirst) == branch0TargetSecond) { // Handle redirected target branch0TargetSecond = branch1.targetFirst; } if(branch0TargetSecond == branch1.targetFirst) { // Combination if not branch0 or branch1 then branch0 = combine_conditional(state, branch0); Condition c = new OrCondition(branch0.cond.inverse(), branch1.cond); Branch branchn = new Branch(branch0.line, Branch.Type.comparison, c, branch1.targetFirst, branch1.targetSecond); branchn.inverseValue = branch1.inverseValue; if(verbose) System.err.println("conditional or " + branchn.line); replace_branch(state, branch0, branch1, branchn); return combine_conditional(state, branchn); } else if(branch0TargetSecond == branch1.targetSecond) { // Combination if branch0 and branch1 then branch0 = combine_conditional(state, branch0); Condition c = new AndCondition(branch0.cond, branch1.cond); Branch branchn = new Branch(branch0.line, Branch.Type.comparison, c, branch1.targetFirst, branch1.targetSecond); branchn.inverseValue = branch1.inverseValue; if(verbose) System.err.println("conditional and " + branchn.line); replace_branch(state, branch0, branch1, branchn); return combine_conditional(state, branchn); } } return branch1; } private static Branch combine_assignment(State state, Branch branch1) { Branch branch0 = branch1.previous; Branch branchn = branch1; while(branch0 != null && branchn == branch1) { branchn = combine_assignment_helper(state, branch0, branch1); if(branch0.targetSecond > branch1.targetFirst) break; branch0 = branch0.previous; } return branchn; } private static Branch combine_assignment_helper(State state, Branch branch0, Branch branch1) { if(adjacent(state, branch0, branch1)) { int register = branch1.target; if(branch1.target == -1) { throw new IllegalStateException(); } //System.err.println("blah " + branch1.line + " " + branch0.line); if(is_conditional(branch0) && is_assignment(branch1)) { //System.err.println("bridge cand " + branch1.line + " " + branch0.line); if(branch0.targetSecond == branch1.targetFirst) { boolean inverse = branch0.inverseValue; if(verbose) System.err.println("bridge " + (inverse ? "or" : "and") + " " + branch1.line + " " + branch0.line); branch0 = combine_conditional(state, branch0); if(inverse != branch0.inverseValue) throw new IllegalStateException(); Condition c; if(!branch1.inverseValue) { //System.err.println("bridge or " + branch0.line + " " + branch0.inverseValue); c = new OrCondition(branch0.cond.inverse(), branch1.cond); } else { //System.err.println("bridge and " + branch0.line + " " + branch0.inverseValue); c = new AndCondition(branch0.cond, branch1.cond); } Branch branchn = new Branch(branch0.line, branch1.type, c, branch1.targetFirst, branch1.targetSecond); branchn.inverseValue = branch1.inverseValue; branchn.target = register; replace_branch(state, branch0, branch1, branchn); return combine_assignment(state, branchn); } else if(branch0.targetSecond == branch1.targetSecond) { /* Condition c = new AndCondition(branch0.cond, branch1.cond); Branch branchn = new Branch(branch0.line, Branch.Type.comparison, c, branch1.targetFirst, branch1.targetSecond); replace_branch(state, branch0, branch1, branchn); return branchn; */ } } if(is_assignment(branch0, register) && is_assignment(branch1) && branch0.inverseValue == branch1.inverseValue) { if(branch0.targetSecond == branch1.targetSecond) { Condition c; //System.err.println("preassign " + branch1.line + " " + branch0.line + " " + branch0.targetSecond); if(verbose) System.err.println("assign " + (branch0.inverseValue ? "or" : "and") + " " + branch1.line + " " + branch0.line); if(is_conditional(branch0)) { branch0 = combine_conditional(state, branch0); if(branch0.inverseValue) { branch0.cond = branch0.cond.inverse(); // inverse has been double handled; undo it } } else { boolean inverse = branch0.inverseValue; branch0 = combine_assignment(state, branch0); if(inverse != branch0.inverseValue) throw new IllegalStateException(); } if(branch0.inverseValue) { //System.err.println("assign and " + branch1.line + " " + branch0.line); c = new OrCondition(branch0.cond, branch1.cond); } else { //System.err.println("assign or " + branch1.line + " " + branch0.line); c = new AndCondition(branch0.cond, branch1.cond); } Branch branchn = new Branch(branch0.line, branch1.type, c, branch1.targetFirst, branch1.targetSecond); branchn.inverseValue = branch1.inverseValue; branchn.target = register; replace_branch(state, branch0, branch1, branchn); return combine_assignment(state, branchn); } } if(is_assignment(branch0, register) && branch1.type == Branch.Type.finalset) { if(branch0.targetSecond == branch1.targetSecond) { Condition c; //System.err.println("final preassign " + branch1.line + " " + branch0.line); if(is_conditional(branch0)) { branch0 = combine_conditional(state, branch0); if(branch0.inverseValue) { branch0.cond = branch0.cond.inverse(); // inverse has been double handled; undo it } } else { boolean inverse = branch0.inverseValue; branch0 = combine_assignment(state, branch0); if(inverse != branch0.inverseValue) throw new IllegalStateException(); } if(verbose) System.err.println("final assign " + (branch0.inverseValue ? "or" : "and") + " " + branch1.line + " " + branch0.line); if(branch0.inverseValue) { //System.err.println("final assign or " + branch1.line + " " + branch0.line); c = new OrCondition(branch0.cond, branch1.cond); } else { //System.err.println("final assign and " + branch1.line + " " + branch0.line); c = new AndCondition(branch0.cond, branch1.cond); } Branch branchn = new Branch(branch0.line, Branch.Type.finalset, c, branch1.targetFirst, branch1.targetSecond); branchn.target = register; replace_branch(state, branch0, branch1, branchn); return combine_assignment(state, branchn); } } } return branch1; } private static Branch[] branches(State state, Branch b) { if(b.type == Branch.Type.finalset) { return state.finalsetbranches; } else if(b.type == Branch.Type.testset) { return state.setbranches; } else { return state.branches; } } private static void replace_branch(State state, Branch branch0, Branch branch1, Branch branchn) { remove_branch(state, branch0); branches(state, branch1)[branch1.line] = null; branchn.previous = branch1.previous; if(branchn.previous == null) { state.begin_branch = branchn; } else { branchn.previous.next = branchn; } branchn.next = branch1.next; if(branchn.next == null) { state.end_branch = branchn; } else { branchn.next.previous = branchn; } branches(state, branchn)[branchn.line] = branchn; } private static void remove_branch(State state, Branch b) { branches(state, b)[b.line] = null; Branch prev = b.previous; Branch next = b.next; if(prev != null) { prev.next = next; } else { state.begin_branch = next; } if(next != null) { next.previous = prev; } else { state.end_branch = prev; } } private static void insert_branch(State state, Branch b) { branches(state, b)[b.line] = b; } private static void link_branches(State state) { Branch previous = null; for(int index = 0; index < state.branches.length; index++) { for(int array = 0; array < 3; array ++) { Branch[] branches; if(array == 0) { branches = state.finalsetbranches; } else if(array == 1) { branches = state.setbranches; } else { branches = state.branches; } Branch b = branches[index]; if(b != null) { b.previous = previous; if(previous != null) { previous.next = b; } else { state.begin_branch = b; } previous = b; } } } state.end_branch = previous; } private static int get_target(State state, int line) { Code code = state.code; if(code.isUpvalueDeclaration(line)) { line--; while(code.op(line) != Op.CLOSURE) line--; int codepoint = code.codepoint(line); int target = Op.CLOSURE.target(codepoint, code.getExtractor()); return target; } else { Op op = code.op(line); int codepoint = code.codepoint(line); int target = op.target(codepoint, code.getExtractor()); if(target == -1) { // Special handling for table literals switch(op) { case SETLIST: case SETLISTO: case SETLIST50: case SETLIST52: case SETTABLE: target = code.A(line); break; case EXTRABYTE: if(line >= 2 && code.op(line - 1) == Op.SETLIST) { target = code.A(line - 1); } break; case EXTRAARG: if(line >= 2 && code.op(line - 1) == Op.SETLIST52) { target = code.A(line - 1); } break; default: break; } } return target; } } private static boolean is_jmp_raw(State state, int line) { Op op = state.code.op(line); return op == Op.JMP || op == Op.JMP52; } private static boolean is_jmp(State state, int line) { Code code = state.code; Op op = code.op(line); if(op == Op.JMP) { return true; } else if(op == Op.JMP52) { return !is_close(state, line); } else { return false; } } private static boolean is_close(State state, int line) { Code code = state.code; Op op = code.op(line); if(op == Op.CLOSE) { return true; } else if(op == Op.JMP52) { int target = code.target(line); if(target == line + 1) { return code.A(line) != 0; } else { if(line + 1 <= code.length && code.op(line + 1) == Op.JMP52) { return target == code.target(line + 1) && code.A(line) != 0; } else { return false; } } } else { return false; } } private static boolean has_statement(State state, int begin, int end) { for(int line = begin; line <= end; line++) { if(is_statement(state, line)) { return true; } } return state.d.hasStatement(begin, end); } private static boolean is_statement(State state, int line) { if(state.reverse_targets[line]) return true; Registers r = state.r; if(!r.getNewLocals(line).isEmpty()) return true; Code code = state.code; if(code.isUpvalueDeclaration(line)) return false; switch(code.op(line)) { case MOVE: case LOADK: case LOADKX: case LOADBOOL: case GETUPVAL: case GETTABUP: case GETGLOBAL: case GETTABLE: case NEWTABLE: case NEWTABLE50: case ADD: case SUB: case MUL: case DIV: case MOD: case POW: case IDIV: case BAND: case BOR: case BXOR: case SHL: case SHR: case UNM: case NOT: case LEN: case BNOT: case CONCAT: case CLOSURE: case TESTSET: return r.isLocal(code.A(line), line); case LOADNIL: for(int register = code.A(line); register <= code.B(line); register++) { if(r.isLocal(register, line)) { return true; } } return false; case LOADNIL52: for(int register = code.A(line); register <= code.A(line) + code.B(line); register++) { if(r.isLocal(register, line)) { return true; } } return false; case SETGLOBAL: case SETUPVAL: case SETTABUP: case TAILCALL: case RETURN: case FORLOOP: case FORPREP: case TFORCALL: case TFORLOOP: case TFORPREP: case CLOSE: return true; case TEST50: return code.A(line) != code.B(line) && r.isLocal(code.A(line), line); case SELF: return r.isLocal(code.A(line), line) || r.isLocal(code.A(line) + 1, line); case EQ: case LT: case LE: case TEST: case SETLIST: case SETLIST52: case SETLIST50: case SETLISTO: case EXTRAARG: case EXTRABYTE: return false; case JMP: case JMP52: // TODO: CLOSE? if(line == 1) { return true; } else { Op prev = line >= 2 ? code.op(line - 1) : null; Op next = line + 1 <= code.length ? code.op(line + 1) : null; if(prev == Op.EQ) return false; if(prev == Op.LT) return false; if(prev == Op.LE) return false; if(prev == Op.TEST) return false; if(prev == Op.TESTSET) return false; if(prev == Op.TEST50) return false; if(next == Op.LOADBOOL && code.C(line + 1) != 0) return false; return true; } case CALL: { int a = code.A(line); int c = code.C(line); if(c == 1) { return true; } if(c == 0) c = r.registers - a + 1; for(int register = a; register < a + c - 1; register++) { if(r.isLocal(register, line)) { return true; } } return false; } case VARARG: { int a = code.A(line); int b = code.B(line); if(b == 0) b = r.registers - a + 1; for(int register = a; register < a + b - 1; register++) { if(r.isLocal(register, line)) { return true; } } return false; } case SETTABLE: // special case -- this is actually ambiguous and must be resolved by the decompiler check return false; } throw new IllegalStateException("Illegal opcode: " + code.op(line)); } // static only private ControlFlowHandler() { } }
Refactor
src/unluac/decompile/ControlFlowHandler.java
Refactor
<ide><path>rc/unluac/decompile/ControlFlowHandler.java <ide> } <ide> } <ide> <add> private static class ResolutionState { <add> ResolutionState(State state, Block container) { <add> this.container = container; <add> resolution = new BranchResolution[state.code.length + 1]; <add> results = new ArrayList<ResolutionResult>(); <add> } <add> <add> Block container; <add> BranchResolution[] resolution; <add> List<ResolutionResult> results; <add> } <add> <ide> private static class BranchResolution { <ide> <ide> enum Type { <ide> <ide> } <ide> <del> private static ResolutionResult finishResolution(State state, Declaration[] declList, Block container, BranchResolution[] resolution) { <add> private static ResolutionResult finishResolution(State state, Declaration[] declList, ResolutionState rstate) { <ide> ResolutionResult result = new ResolutionResult(); <del> for(int i = 0; i < resolution.length; i++) { <del> BranchResolution r = resolution[i]; <add> for(int i = 0; i < rstate.resolution.length; i++) { <add> BranchResolution r = rstate.resolution[i]; <ide> if(r != null) { <ide> Branch b = state.branches[i]; <ide> if(b == null) throw new IllegalStateException(); <ide> result.blocks.add(new IfThenEndBlock(state.function, state.r, b.cond, b.targetFirst, r.line, literalEnd != r.line)); <ide> break; <ide> case IF_ELSE: <del> BranchResolution r_else = resolution[r.line - 1]; <add> BranchResolution r_else = rstate.resolution[r.line - 1]; <ide> if(r_else == null) throw new IllegalStateException(); <ide> result.blocks.add(new IfThenElseBlock(state.function, b.cond, b.targetFirst, r.line, r_else.line)); <ide> if(r.line != r_else.line) { <ide> } <ide> } <ide> } <del> for(int i = 0; i < resolution.length; i++) { <del> BranchResolution r = resolution[i]; <add> for(int i = 0; i < rstate.resolution.length; i++) { <add> BranchResolution r = rstate.resolution[i]; <ide> if(r != null) { <ide> Branch b = state.branches[i]; <ide> if(b == null) throw new IllegalStateException(); <ide> if(r.type == BranchResolution.Type.PSEUDO_GOTO) { <del> Block smallest = container; <add> Block smallest = rstate.container; <ide> if(smallest == null) smallest = state.blocks.get(0); // outer block TODO cleaner way to get <ide> for(Block newblock : result.blocks) { <ide> if(smallest.contains(newblock) && newblock.contains(b.line) && newblock.contains(r.line - 1)) { <ide> <ide> private static boolean debug_resolution = false; <ide> <del> private static boolean checkResolution(State state, Block container, BranchResolution[] resolution) { <add> private static boolean checkResolution(State state, ResolutionState rstate) { <ide> List<Pair> blocks = new ArrayList<Pair>(); <ide> List<Pair> pseudoGotos = new ArrayList<Pair>(); <del> for(int i = 0; i < resolution.length; i++) { <del> BranchResolution r = resolution[i]; <add> for(int i = 0; i < rstate.resolution.length; i++) { <add> BranchResolution r = rstate.resolution[i]; <ide> if(r != null) { <ide> Branch b = state.branches[i]; <ide> if(b == null) throw new IllegalStateException(); <ide> if(debug_resolution) System.err.println("unmatched else"); <ide> return false; <ide> } <del> if(container != null && r.line >= container.end) { <add> if(rstate.container != null && r.line >= rstate.container.end) { <ide> if(debug_resolution) System.err.println("invalid else"); <ide> return false; <ide> } <ide> break; <ide> case BREAK: <del> if(container == null || r.line < container.end) { <add> if(rstate.container == null || r.line < rstate.container.end) { <ide> if(debug_resolution) System.err.println("invalid break"); <ide> return false; <ide> } <ide> break; <ide> case PSEUDO_GOTO: <del> if(container != null && r.line >= container.end) { <add> if(rstate.container != null && r.line >= rstate.container.end) { <ide> if(debug_resolution) System.err.println("invalid pseudo goto"); <ide> return false; <ide> } <ide> pseudoGotos.add(new Pair(b.line, r.line)); <ide> break; <ide> case IF_END: <del> if(container != null && r.line >= container.end) { <add> if(rstate.container != null && r.line >= rstate.container.end) { <ide> if(debug_resolution) System.err.println("invalid if end"); <ide> return false; <ide> } <ide> blocks.add(new Pair(b.targetFirst, r.line)); <ide> break; <ide> case IF_ELSE: <del> if(container != null && r.line >= container.end) { <add> if(rstate.container != null && r.line >= rstate.container.end) { <ide> if(debug_resolution) System.err.println("invalid if else"); <ide> return false; <ide> } <del> BranchResolution r_else = resolution[r.line - 1]; <add> BranchResolution r_else = rstate.resolution[r.line - 1]; <ide> if(r_else == null) throw new IllegalStateException(); <ide> blocks.add(new Pair(b.targetFirst, r.line - 1)); <ide> blocks.add(new Pair(r.line, r_else.line)); <ide> blocks.add(new Pair(b.targetFirst, r_else.line)); <ide> break; <ide> case IF_BREAK: <del> if(container == null || r.line < container.end) { <add> if(rstate.container == null || r.line < rstate.container.end) { <ide> if(debug_resolution) System.err.println("invalid if break"); <ide> return false; <ide> } <ide> return true; <ide> } <ide> <del> private static void printResolution(State state, Block container, BranchResolution[] resolution) { <del> List<Pair> blocks = new ArrayList<Pair>(); <del> for(int i = 0; i < resolution.length; i++) { <del> BranchResolution r = resolution[i]; <add> private static void printResolution(State state, ResolutionState rstate) { <add> for(int i = 0; i < rstate.resolution.length; i++) { <add> BranchResolution r = rstate.resolution[i]; <ide> if(r != null) { <ide> Branch b = state.branches[i]; <ide> if(b == null) throw new IllegalStateException(); <ide> return state.resolved[container.end] == state.resolved[line]; <ide> } <ide> <del> static int count = 0; <del> <del> private static void resolve(State state, Declaration[] declList, Block container, BranchResolution[] resolution, Branch b, List<ResolutionResult> results) { <add> private static void resolve(State state, Declaration[] declList, ResolutionState rstate, Branch b) { <ide> if(b == null) { <del> if(count > 10000) { <del> //System.err.println("here"); <del> } <del> if(checkResolution(state, container, resolution)) { <del> <add> if(checkResolution(state, rstate)) { <ide> // printResolution(state, container, resolution); <ide> // System.out.println(); <del> results.add(finishResolution(state, declList, container, resolution)); <add> rstate.results.add(finishResolution(state, declList, rstate)); <ide> } else { <del> //System.err.println("complete resolution" + count); <del> count++; <del> <ide> // System.out.println("failed resolution:"); <ide> // printResolution(state, container, resolution); <ide> } <ide> return; <ide> } <ide> Branch next = b.previous; <del> while(next != null && enclosing_breakable_block(state, next.line) != container) { <add> while(next != null && enclosing_breakable_block(state, next.line) != rstate.container) { <ide> next = next.previous; <ide> } <ide> if(is_conditional(b)) { <ide> BranchResolution r = new BranchResolution(); <del> resolution[b.line] = r; <del> if(is_break(state, container, b.targetSecond)) { <add> rstate.resolution[b.line] = r; <add> if(is_break(state, rstate.container, b.targetSecond)) { <ide> if(state.function.header.version.usesIfBreakRewrite()) { <ide> r.type = BranchResolution.Type.IF_BREAK; <del> r.line = container.end; <del> resolve(state, declList, container, resolution, next, results); <add> r.line = rstate.container.end; <add> resolve(state, declList, rstate, next); <ide> } <ide> } <ide> Branch p = state.end_branch; <ide> while(p != b) { <del> if(p.type == Branch.Type.jump && enclosing_breakable_block(state, p.line) == container) { <add> if(p.type == Branch.Type.jump && enclosing_breakable_block(state, p.line) == rstate.container) { <ide> if(p.targetFirst == b.targetSecond) { <ide> r.line = p.line; <ide> BranchResolution prevlineres = null; <ide> if(p.line - 1 >= 1) { <del> prevlineres = resolution[p.line - 1]; <add> prevlineres = rstate.resolution[p.line - 1]; <ide> } <ide> if(prevlineres != null && prevlineres.type == BranchResolution.Type.ELSE && !prevlineres.matched) { <ide> r.type = BranchResolution.Type.IF_ELSE; <ide> prevlineres.matched = true; <del> resolve(state, declList, container, resolution, next, results); <add> resolve(state, declList, rstate, next); <ide> prevlineres.matched = false; <ide> } <ide> r.type = BranchResolution.Type.IF_END; <del> resolve(state, declList, container, resolution, next, results); <add> resolve(state, declList, rstate, next); <ide> } <ide> } <ide> p = p.previous; <ide> BranchResolution prevlineres = null; <ide> r.line = b.targetSecond; <ide> if(b.targetSecond - 1 >= 1) { <del> prevlineres = resolution[b.targetSecond - 1]; <add> prevlineres = rstate.resolution[b.targetSecond - 1]; <ide> } <ide> if(prevlineres != null && prevlineres.type == BranchResolution.Type.ELSE && !prevlineres.matched) { <ide> r.type = BranchResolution.Type.IF_ELSE; <ide> prevlineres.matched = true; <del> resolve(state, declList, container, resolution, next, results); <add> resolve(state, declList, rstate, next); <ide> prevlineres.matched = false; <ide> } <ide> r.type = BranchResolution.Type.IF_END; <del> resolve(state, declList, container, resolution, next, results); <del> resolution[b.line] = null; <add> resolve(state, declList, rstate, next); <add> rstate.resolution[b.line] = null; <ide> } else if(b.type == Branch.Type.jump) { <ide> BranchResolution r = new BranchResolution(); <del> resolution[b.line] = r; <del> if(is_break(state, container, b.targetFirst)) { <add> rstate.resolution[b.line] = r; <add> if(is_break(state, rstate.container, b.targetFirst)) { <ide> r.type = BranchResolution.Type.BREAK; <del> r.line = container.end; <del> resolve(state, declList, container, resolution, next, results); <add> r.line = rstate.container.end; <add> resolve(state, declList, rstate, next); <ide> } <ide> Branch p = state.end_branch; <ide> while(p != b) { <del> if(p.type == Branch.Type.jump && enclosing_breakable_block(state, p.line) == container) { <add> if(p.type == Branch.Type.jump && enclosing_breakable_block(state, p.line) == rstate.container) { <ide> if(p.targetFirst == b.targetFirst) { <ide> r.type = BranchResolution.Type.ELSE; <ide> r.line = p.line; <del> resolve(state, declList, container, resolution, next, results); <add> resolve(state, declList, rstate, next); <ide> } <ide> } <ide> p = p.previous; <ide> } <ide> r.type = BranchResolution.Type.ELSE; <ide> r.line = b.targetFirst; <del> resolve(state, declList, container, resolution, next, results); <add> resolve(state, declList, rstate, next); <ide> r.type = BranchResolution.Type.PSEUDO_GOTO; <del> resolve(state, declList, container, resolution, next, results); <del> resolution[b.line] = null; <add> resolve(state, declList, rstate, next); <add> rstate.resolution[b.line] = null; <ide> } else { <del> resolve(state, declList, container, resolution, next, results); <add> resolve(state, declList, rstate, next); <ide> } <ide> } <ide> <ide> containers.add(null); <ide> <ide> for(Block container : containers) { <del> List<ResolutionResult> results = new ArrayList<ResolutionResult>(); <del> <ide> Branch b = state.end_branch; <ide> while(b != null && enclosing_breakable_block(state, b.line) != container) { <ide> b = b.previous; <ide> } <ide> <ide> //System.out.println("resolve " + (container == null ? 0 : container.begin)); <del> resolve(state, declList, container, new BranchResolution[state.code.length + 1], b, results); <del> if(results.isEmpty()) throw new IllegalStateException("couldn't resolve breaks for " + (container == null ? 0 : container.begin)); <del> state.blocks.addAll(results.get(0).blocks); <add> ResolutionState rstate = new ResolutionState(state, container); <add> resolve(state, declList, rstate, b); <add> if(rstate.results.isEmpty()) throw new IllegalStateException("couldn't resolve breaks for " + (container == null ? 0 : container.begin)); <add> state.blocks.addAll(rstate.results.get(0).blocks); <ide> } <ide> } <ide>
Java
mit
69bf7acfd87839ad2438f29aa4925eb70e0b1b9f
0
martijn9612/fishy
package nl.github.martijn9612.fishy; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.stage.Stage; /** * Creates the fishy game and launches it */ public class Launcher extends Application { /** * Starts the game * * @param args Are not used */ public static void main(String[] args) { launch(args); } /** * Starts the initial screen for the game, the welcome screen * * @param primaryStage * @throws Exception */ @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("Fishy"); Group root = new Group(); Canvas canvas = new Canvas(300, 300); root.getChildren().add(canvas); Scene startScreen = new Scene(root); primaryStage.setScene(startScreen); primaryStage.show(); } }
src/main/java/nl/github/martijn9612/fishy/Launcher.java
package nl.github.martijn9612.fishy; /** * Created by martijn on 5-9-15. */ public class Launcher { }
Added Opening Of First Screen
src/main/java/nl/github/martijn9612/fishy/Launcher.java
Added Opening Of First Screen
<ide><path>rc/main/java/nl/github/martijn9612/fishy/Launcher.java <ide> package nl.github.martijn9612.fishy; <ide> <add>import javafx.application.Application; <add>import javafx.scene.Group; <add>import javafx.scene.Scene; <add>import javafx.scene.canvas.Canvas; <add>import javafx.stage.Stage; <add> <ide> /** <del> * Created by martijn on 5-9-15. <add> * Creates the fishy game and launches it <ide> */ <del>public class Launcher { <add>public class Launcher extends Application { <add> /** <add> * Starts the game <add> * <add> * @param args Are not used <add> */ <add> public static void main(String[] args) { <add> launch(args); <add> } <add> <add> /** <add> * Starts the initial screen for the game, the welcome screen <add> * <add> * @param primaryStage <add> * @throws Exception <add> */ <add> @Override <add> public void start(Stage primaryStage) throws Exception { <add> primaryStage.setTitle("Fishy"); <add> Group root = new Group(); <add> Canvas canvas = new Canvas(300, 300); <add> root.getChildren().add(canvas); <add> Scene startScreen = new Scene(root); <add> primaryStage.setScene(startScreen); <add> primaryStage.show(); <add> } <ide> }
Java
apache-2.0
94a69b5e89fcc4230f4fd8813f73593592427896
0
Netflix/photon,Netflix/photon
package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.st0377.header.GenericPictureEssenceDescriptor; import com.netflix.imflibrary.utils.DOMNodeObjectModel; import com.netflix.imflibrary.utils.RegXMLLibDictionary; import com.netflix.imflibrary.utils.UUIDHelper; import com.netflix.imflibrary.utils.Utilities; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; /** * A class that performs CoreConstraints st2067-2 related checks on the elements of a Composition Playlist such as VirtualTracks, Segments, Sequences and Resources. */ final class IMFCoreConstraintsChecker { private static final Set<String> VirtualTrackHomogeneityIgnoreSet = new HashSet<String>(){{ add("InstanceUID"); add("InstanceID"); add("EssenceLength"); add("AlternativeCenterCuts"); add("MCALinkID"); add("LinkedTrackID"); add("SoundfieldGroupLinkID"); add("MCAChannelID"); add("LinkedGenerationID"); add("MCATitle"); add("MCATitleVersion"); add("PixelLayout"); add("VideoLineMap"); add("CodingStyleDefault"); add("PictureComponentSizing"); add("QuantizationDefault"); add("Rsiz"); add("Xsiz"); add("Ysiz"); add("XOsiz"); add("YOsiz"); add("XTsiz"); add("YTsiz"); add("XTOsiz"); add("YTOsiz"); add("Csiz"); }}; //To prevent instantiation private IMFCoreConstraintsChecker(){ } public static List checkVirtualTracks(IMFCompositionPlaylistType compositionPlaylistType, Map<UUID, ? extends Composition.VirtualTrack> virtualTrackMap, Map<UUID, DOMNodeObjectModel> essenceDescriptorListMap) { RegXMLLibDictionary regXMLLibDictionary = new RegXMLLibDictionary(); return checkVirtualTracks(compositionPlaylistType, virtualTrackMap, essenceDescriptorListMap, regXMLLibDictionary); } public static List checkVirtualTracks(IMFCompositionPlaylistType compositionPlaylistType, Map<UUID, ? extends Composition.VirtualTrack> virtualTrackMap, Map<UUID, DOMNodeObjectModel> essenceDescriptorListMap, RegXMLLibDictionary regXMLLibDictionary){ boolean foundMainImageEssence = false; int numberOfMainImageEssences = 0; boolean foundMainAudioEssence = false; int numberOfMarkerSequences = 0; IMFErrorLogger imfErrorLogger =new IMFErrorLoggerImpl(); Iterator iterator = virtualTrackMap.entrySet().iterator(); while(iterator.hasNext()) { Composition.VirtualTrack virtualTrack = ((Map.Entry<UUID, ? extends Composition.VirtualTrack>) iterator.next()).getValue(); List<? extends IMFBaseResourceType> virtualTrackResourceList = virtualTrack.getResourceList(); imfErrorLogger.addAllErrors(checkVirtualTrackResourceList(virtualTrack.getTrackID(), virtualTrackResourceList)); if (!(virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainImageSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainAudioSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MarkerSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.SubtitlesSequence))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, String.format("CPL has a Sequence of type %s which is not fully supported sequence type in Photon", virtualTrack.getSequenceTypeEnum().toString())); continue; } if (virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainImageSequence)) { foundMainImageEssence = true; numberOfMainImageEssences++; Composition.EditRate compositionEditRate = compositionPlaylistType.getEditRate(); for (IMFBaseResourceType baseResourceType : virtualTrackResourceList) { Composition.EditRate trackResourceEditRate = baseResourceType.getEditRate(); //Section 6.4 st2067-2:2016 if (trackResourceEditRate != null && !trackResourceEditRate.equals(compositionEditRate)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("This Composition is invalid since the CompositionEditRate %s is not the same as atleast one of the MainImageSequence's Resource EditRate %s. Please refer to st2067-2:2013 Section 6.4", compositionEditRate.toString(), trackResourceEditRate.toString())); } } } else if(virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainAudioSequence)){ foundMainAudioEssence = true; } if((virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainImageSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainAudioSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.SubtitlesSequence)) && compositionPlaylistType.getEssenceDescriptorList() != null && compositionPlaylistType.getEssenceDescriptorList().size() > 0) { List<DOMNodeObjectModel> virtualTrackEssenceDescriptors = new ArrayList<>(); String refSourceEncodingElement = ""; String essenceDescriptorField = ""; String otherEssenceDescriptorField = ""; Composition.EditRate essenceEditRate = null; for(IMFBaseResourceType imfBaseResourceType : virtualTrackResourceList){ IMFTrackFileResourceType imfTrackFileResourceType = IMFTrackFileResourceType.class.cast(imfBaseResourceType); DOMNodeObjectModel domNodeObjectModel = essenceDescriptorListMap.get(UUIDHelper.fromUUIDAsURNStringToUUID(imfTrackFileResourceType.getSourceEncoding())); //Section 6.8 st2067-2:2016 if(domNodeObjectModel == null){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor ID %s referenced by a " + "VirtualTrack Resource does not have a corresponding EssenceDescriptor in the EssenceDescriptorList in the CPL", imfTrackFileResourceType.getSourceEncoding())); } else { if (!refSourceEncodingElement.equals(imfTrackFileResourceType.getSourceEncoding())) { refSourceEncodingElement = imfTrackFileResourceType.getSourceEncoding(); //Section 6.3.1 and 6.3.2 st2067-2:2016 Edit Rate check if (virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainImageSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.SubtitlesSequence)) { essenceDescriptorField = "SampleRate"; } else if (virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainAudioSequence)) { essenceDescriptorField = "SampleRate"; otherEssenceDescriptorField = "AudioSampleRate"; } String sampleRate = domNodeObjectModel.getFieldAsString(essenceDescriptorField); if(sampleRate == null && !otherEssenceDescriptorField.isEmpty()) { sampleRate = domNodeObjectModel.getFieldAsString(otherEssenceDescriptorField); } if (sampleRate != null) { Long numerator = 0L; Long denominator = 0L; String[] sampleRateElements = (sampleRate.contains(" ")) ? sampleRate.split(" ") : sampleRate.contains("/") ? sampleRate.split("/") : new String[2]; if (sampleRateElements.length == 2) { numerator = Long.valueOf(sampleRateElements[0]); denominator = Long.valueOf(sampleRateElements[1]); } else if (sampleRateElements.length == 1) { numerator = Long.valueOf(sampleRateElements[0]); denominator = 1L; } List<Long> editRate = new ArrayList<>(); Integer sampleRateToEditRateScale = 1; if(virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainImageSequence)) { CompositionImageEssenceDescriptorModel imageEssenceDescriptorModel = new CompositionImageEssenceDescriptorModel(UUIDHelper.fromUUIDAsURNStringToUUID (imfTrackFileResourceType.getSourceEncoding()), domNodeObjectModel, regXMLLibDictionary); sampleRateToEditRateScale = imageEssenceDescriptorModel.getFrameLayoutType().equals(GenericPictureEssenceDescriptor.FrameLayoutType.SeparateFields) ? 2 : 1; } editRate.add(numerator / sampleRateToEditRateScale); editRate.add(denominator); essenceEditRate = new Composition.EditRate(editRate); } } if (essenceEditRate == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("This Composition represented by the ID %s is invalid since the VirtualTrack represented by ID %s has a Resource represented by ID %s that seems to refer to a EssenceDescriptor in the CPL's EssenceDescriptorList represented by the ID %s " + "which does not have a value set for the field %s, however the Resource Edit Rate is %s" , compositionPlaylistType.getId().toString(), virtualTrack.getTrackID().toString(), imfBaseResourceType.getId(), imfTrackFileResourceType.getSourceEncoding(), essenceDescriptorField, imfBaseResourceType.getEditRate().toString())); } else if (!essenceEditRate.equals(imfBaseResourceType.getEditRate())) { //Section 6.3.1 and 6.3.2 st2067-2:2016 imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("This Composition represented by the ID %s is invalid since the VirtualTrack represented by ID %s has a Resource represented by ID %s that refers to a EssenceDescriptor in the CPL's EssenceDescriptorList represented by the ID %s " + "whose indicated %s value is %s, however the Resource Edit Rate is %s" , compositionPlaylistType.getId().toString(), virtualTrack.getTrackID().toString(), imfBaseResourceType.getId(), imfTrackFileResourceType.getSourceEncoding(), essenceDescriptorField, essenceEditRate.toString(), imfBaseResourceType.getEditRate().toString())); } virtualTrackEssenceDescriptors.add(domNodeObjectModel); } } //Section 6.8 st2067-2:2016 if(!(virtualTrackEssenceDescriptors.size() > 0)){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("This Composition represented by the ID %s is invalid since the resources comprising the VirtualTrack represented by ID %s seem to refer to EssenceDescriptor/s in the CPL's EssenceDescriptorList that are absent", compositionPlaylistType.getId().toString(), virtualTrack.getTrackID().toString())); } else if( virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainImageSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainAudioSequence)){ boolean isVirtualTrackHomogeneous = true; DOMNodeObjectModel refDOMNodeObjectModel = virtualTrackEssenceDescriptors.get(0).createDOMNodeObjectModelIgnoreSet(virtualTrackEssenceDescriptors.get(0), IMFCoreConstraintsChecker.VirtualTrackHomogeneityIgnoreSet); for (int i = 1; i < virtualTrackEssenceDescriptors.size(); i++) { isVirtualTrackHomogeneous &= refDOMNodeObjectModel.equals(virtualTrackEssenceDescriptors.get(i).createDOMNodeObjectModelIgnoreSet(virtualTrackEssenceDescriptors.get(i), IMFCoreConstraintsChecker.VirtualTrackHomogeneityIgnoreSet)); } List<DOMNodeObjectModel> modelsIgnoreSet = new ArrayList<>(); if (!isVirtualTrackHomogeneous) { for(int i = 1; i< virtualTrackEssenceDescriptors.size(); i++){ DOMNodeObjectModel other = virtualTrackEssenceDescriptors.get(i).createDOMNodeObjectModelIgnoreSet(virtualTrackEssenceDescriptors.get(i), IMFCoreConstraintsChecker.VirtualTrackHomogeneityIgnoreSet); modelsIgnoreSet.add(other); imfErrorLogger.addAllErrors(DOMNodeObjectModel.getNamespaceURIMismatchErrors(refDOMNodeObjectModel, other)); } //Section 6.2 st2067-2:2016 imfErrorLogger.addAllErrors(refDOMNodeObjectModel.getErrors()); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("This Composition represented by the ID %s is invalid since the VirtualTrack represented by ID %s is not homogeneous based on a comparison of the EssenceDescriptors referenced by its resources in the Essence Descriptor List, " + "the EssenceDescriptors corresponding to this VirtualTrack in the EssenceDescriptorList are as follows %n%n%s", compositionPlaylistType.getId().toString(), virtualTrack.getTrackID().toString(), Utilities.serializeObjectCollectionToString(modelsIgnoreSet))); } } } } //TODO : Add a check to ensure that all the VirtualTracks have the same duration. //Section 6.3.1 st2067-2:2016 and Section 6.9.3 st2067-3:2016 if(!foundMainImageEssence){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("The Composition represented by Id %s does not contain a single image essence in its first segment, exactly one is required", compositionPlaylistType.getId().toString())); } else{ if(numberOfMainImageEssences > 1){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("The Composition represented by Id %s seems to contain %d image essences in its first segment, exactly one is required", compositionPlaylistType.getId().toString(), numberOfMainImageEssences)); } } //Section 6.3.2 st2067-2:2016 and Section 6.9.3 st2067-3:2016 if(!foundMainAudioEssence){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("The Composition represented by Id %s does not contain a single audio essence in its first segment, one or more is required", compositionPlaylistType.getId().toString())); } return imfErrorLogger.getErrors(); } public static void checkSegments(IMFCompositionPlaylistType compositionPlaylistType, Map<UUID, Composition.VirtualTrack> virtualTrackMap, @Nullable IMFErrorLogger imfErrorLogger) { for (IMFSegmentType segment : compositionPlaylistType.getSegmentList()) { Set<UUID> trackIDs = new HashSet<>(); /* TODO: Add check for Marker sequence */ Set<Long> sequencesDurationSet = new HashSet<>(); double compositionEditRate = (double)compositionPlaylistType.getEditRate().getNumerator()/compositionPlaylistType.getEditRate().getDenominator(); for (IMFSequenceType sequence : segment.getSequenceList()) { UUID uuid = UUIDHelper.fromUUIDAsURNStringToUUID(sequence.getTrackId()); trackIDs.add(uuid); if (virtualTrackMap.get(uuid) == null) { //Section 6.9.3 st2067-3:2016 String message = String.format( "Segment represented by the ID %s in the Composition represented by ID %s contains virtual track represented by ID %s, which does not appear in all the segments of the Composition, this is invalid", segment.getId(), compositionPlaylistType.getId().toString(), uuid); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, message); } List<? extends IMFBaseResourceType> resources = sequence.getResourceList(); Long sequenceDurationInCompositionEditUnits = 0L; Long sequenceDuration = 0L; //Based on Section 6.2 and 6.3 in st2067-2:2016 All resources of either an Image Sequence or an Audio Sequence have to be of the same EditRate, hence we can sum the source durations of all the resources //of a virtual track to get its duration in resource edit units. for(IMFBaseResourceType imfBaseResourceType : resources){ sequenceDuration += imfBaseResourceType.getDuration(); } //Section 7.3 st2067-3:2016 long compositionEditRateNumerator = compositionPlaylistType.getEditRate().getNumerator(); long compositionEditRateDenominator = compositionPlaylistType.getEditRate().getDenominator(); long resourceEditRateNumerator = resources.get(0).getEditRate().getNumerator(); long resourceEditRateDenominator = resources.get(0).getEditRate().getDenominator(); long sequenceDurationInCompositionEditRateReminder = (sequenceDuration * compositionEditRateNumerator * resourceEditRateDenominator) % (compositionEditRateDenominator * resourceEditRateNumerator); Double sequenceDurationDoubleValue = ((double)sequenceDuration * compositionEditRateNumerator * resourceEditRateDenominator) / (compositionEditRateDenominator * resourceEditRateNumerator); //Section 7.3 st2067-3:2016 if(sequenceDurationInCompositionEditRateReminder != 0){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Segment represented by the Id %s in the Composition represented by ID %s has a sequence represented by ID %s, whose duration represented in Composition Edit Units is (%f) is not an integer" , segment.getId(), compositionPlaylistType.getId().toString(), sequence.getId(), sequenceDurationDoubleValue)); } sequenceDurationInCompositionEditUnits = Math.round(sequenceDurationDoubleValue); sequencesDurationSet.add(sequenceDurationInCompositionEditUnits); } //Section 7.2 st2067-3:2016 if(sequencesDurationSet.size() > 1){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Segment represented by the Id %s seems to have sequences that are not of the same duration, following sequence durations were computed based on the information in the Sequence List for this Segment, %s represented in Composition Edit Units", segment.getId(), Utilities.serializeObjectCollectionToString(sequencesDurationSet))); } //Section 6.9.3 st2067-3:2016 if (trackIDs.size() != virtualTrackMap.size()) { String message = String.format( "Number of distinct virtual trackIDs in a segment = %s, different from first segment %d", trackIDs.size(), virtualTrackMap.size()); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, message); } } } public static List checkVirtualTrackResourceList(UUID trackID, List<? extends IMFBaseResourceType> virtualBaseResourceList){ IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); //Section 6.9.3 st2067-3:2016 if(virtualBaseResourceList == null || virtualBaseResourceList.size() == 0){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("VirtualTrack with ID %s does not have any associated resources this is invalid", trackID.toString())); return imfErrorLogger.getErrors(); } Set<Composition.EditRate> editRates = new HashSet<>(); Composition.EditRate baseResourceEditRate = null; for(IMFBaseResourceType baseResource : virtualBaseResourceList){ long compositionPlaylistResourceIntrinsicDuration = baseResource.getIntrinsicDuration().longValue(); long compositionPlaylistResourceEntryPoint = (baseResource.getEntryPoint() == null) ? 0L : baseResource.getEntryPoint().longValue(); //Check to see if the Resource's source duration value is in the valid range as specified in st2067-3:2013 section 6.11.6 if(baseResource.getSourceDuration() != null){ if(baseResource.getSourceDuration().longValue() < 0 || baseResource.getSourceDuration().longValue() > (compositionPlaylistResourceIntrinsicDuration - compositionPlaylistResourceEntryPoint)){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("VirtualTrack with ID %s has a resource with ID %s, that has an invalid source duration value %d, should be in the range [0,%d]", trackID.toString(), baseResource.getId(), baseResource.getSourceDuration().longValue(), (compositionPlaylistResourceIntrinsicDuration - compositionPlaylistResourceEntryPoint))); } } //Check to see if the Marker Resource's intrinsic duration value is in the valid range as specified in st2067-3:2013 section 6.13 if (baseResource instanceof IMFMarkerResourceType) { IMFMarkerResourceType markerResource = IMFMarkerResourceType.class.cast(baseResource); List<IMFMarkerType> markerList = markerResource.getMarkerList(); for (IMFMarkerType marker : markerList) { if (marker.getOffset().longValue() >= markerResource.getIntrinsicDuration().longValue()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger .IMFErrors.ErrorLevels.FATAL, String.format("VirtualTrack with ID %s has a " + "resource with ID %s, that has a marker %s, that has an invalid offset " + "value %d, should be in the range [0,%d] ", trackID.toString(), markerResource.getId(), marker.getLabel().getValue(), marker .getOffset().longValue(), markerResource.getIntrinsicDuration().longValue()-1)); } } } baseResourceEditRate = baseResource.getEditRate(); if(baseResourceEditRate != null){ editRates.add(baseResourceEditRate); } } //Section 6.2, 6.3.1 and 6.3.2 st2067-2:2016 if(editRates.size() > 1){ StringBuilder editRatesString = new StringBuilder(); Iterator iterator = editRates.iterator(); while(iterator.hasNext()){ editRatesString.append(iterator.next().toString()); editRatesString.append(String.format("%n")); } imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("VirtualTrack with ID %s has resources with inconsistent editRates %s", trackID.toString(), editRatesString.toString())); } return imfErrorLogger.getErrors(); } }
src/main/java/com/netflix/imflibrary/st2067_2/IMFCoreConstraintsChecker.java
package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.st0377.header.GenericPictureEssenceDescriptor; import com.netflix.imflibrary.utils.DOMNodeObjectModel; import com.netflix.imflibrary.utils.RegXMLLibDictionary; import com.netflix.imflibrary.utils.UUIDHelper; import com.netflix.imflibrary.utils.Utilities; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; /** * A class that performs CoreConstraints st2067-2 related checks on the elements of a Composition Playlist such as VirtualTracks, Segments, Sequences and Resources. */ final class IMFCoreConstraintsChecker { private static final Set<String> VirtualTrackHomogeneityIgnoreSet = new HashSet<String>(){{ add("InstanceUID"); add("InstanceID"); add("EssenceLength"); add("AlternativeCenterCuts"); add("MCALinkID"); add("LinkedTrackID"); add("SoundfieldGroupLinkID"); add("MCAChannelID"); add("LinkedGenerationID"); add("MCATitle"); add("MCATitleVersion"); }}; //To prevent instantiation private IMFCoreConstraintsChecker(){ } public static List checkVirtualTracks(IMFCompositionPlaylistType compositionPlaylistType, Map<UUID, ? extends Composition.VirtualTrack> virtualTrackMap, Map<UUID, DOMNodeObjectModel> essenceDescriptorListMap) { RegXMLLibDictionary regXMLLibDictionary = new RegXMLLibDictionary(); return checkVirtualTracks(compositionPlaylistType, virtualTrackMap, essenceDescriptorListMap, regXMLLibDictionary); } public static List checkVirtualTracks(IMFCompositionPlaylistType compositionPlaylistType, Map<UUID, ? extends Composition.VirtualTrack> virtualTrackMap, Map<UUID, DOMNodeObjectModel> essenceDescriptorListMap, RegXMLLibDictionary regXMLLibDictionary){ boolean foundMainImageEssence = false; int numberOfMainImageEssences = 0; boolean foundMainAudioEssence = false; int numberOfMarkerSequences = 0; IMFErrorLogger imfErrorLogger =new IMFErrorLoggerImpl(); Iterator iterator = virtualTrackMap.entrySet().iterator(); while(iterator.hasNext()) { Composition.VirtualTrack virtualTrack = ((Map.Entry<UUID, ? extends Composition.VirtualTrack>) iterator.next()).getValue(); List<? extends IMFBaseResourceType> virtualTrackResourceList = virtualTrack.getResourceList(); imfErrorLogger.addAllErrors(checkVirtualTrackResourceList(virtualTrack.getTrackID(), virtualTrackResourceList)); if (!(virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainImageSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainAudioSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MarkerSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.SubtitlesSequence))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING, String.format("CPL has a Sequence of type %s which is not fully supported sequence type in Photon", virtualTrack.getSequenceTypeEnum().toString())); continue; } if (virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainImageSequence)) { foundMainImageEssence = true; numberOfMainImageEssences++; Composition.EditRate compositionEditRate = compositionPlaylistType.getEditRate(); for (IMFBaseResourceType baseResourceType : virtualTrackResourceList) { Composition.EditRate trackResourceEditRate = baseResourceType.getEditRate(); //Section 6.4 st2067-2:2016 if (trackResourceEditRate != null && !trackResourceEditRate.equals(compositionEditRate)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("This Composition is invalid since the CompositionEditRate %s is not the same as atleast one of the MainImageSequence's Resource EditRate %s. Please refer to st2067-2:2013 Section 6.4", compositionEditRate.toString(), trackResourceEditRate.toString())); } } } else if(virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainAudioSequence)){ foundMainAudioEssence = true; } if((virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainImageSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainAudioSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.SubtitlesSequence)) && compositionPlaylistType.getEssenceDescriptorList() != null && compositionPlaylistType.getEssenceDescriptorList().size() > 0) { List<DOMNodeObjectModel> virtualTrackEssenceDescriptors = new ArrayList<>(); String refSourceEncodingElement = ""; String essenceDescriptorField = ""; String otherEssenceDescriptorField = ""; Composition.EditRate essenceEditRate = null; for(IMFBaseResourceType imfBaseResourceType : virtualTrackResourceList){ IMFTrackFileResourceType imfTrackFileResourceType = IMFTrackFileResourceType.class.cast(imfBaseResourceType); DOMNodeObjectModel domNodeObjectModel = essenceDescriptorListMap.get(UUIDHelper.fromUUIDAsURNStringToUUID(imfTrackFileResourceType.getSourceEncoding())); //Section 6.8 st2067-2:2016 if(domNodeObjectModel == null){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("EssenceDescriptor ID %s referenced by a " + "VirtualTrack Resource does not have a corresponding EssenceDescriptor in the EssenceDescriptorList in the CPL", imfTrackFileResourceType.getSourceEncoding())); } else { if (!refSourceEncodingElement.equals(imfTrackFileResourceType.getSourceEncoding())) { refSourceEncodingElement = imfTrackFileResourceType.getSourceEncoding(); //Section 6.3.1 and 6.3.2 st2067-2:2016 Edit Rate check if (virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainImageSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.SubtitlesSequence)) { essenceDescriptorField = "SampleRate"; } else if (virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainAudioSequence)) { essenceDescriptorField = "SampleRate"; otherEssenceDescriptorField = "AudioSampleRate"; } String sampleRate = domNodeObjectModel.getFieldAsString(essenceDescriptorField); if(sampleRate == null && !otherEssenceDescriptorField.isEmpty()) { sampleRate = domNodeObjectModel.getFieldAsString(otherEssenceDescriptorField); } if (sampleRate != null) { Long numerator = 0L; Long denominator = 0L; String[] sampleRateElements = (sampleRate.contains(" ")) ? sampleRate.split(" ") : sampleRate.contains("/") ? sampleRate.split("/") : new String[2]; if (sampleRateElements.length == 2) { numerator = Long.valueOf(sampleRateElements[0]); denominator = Long.valueOf(sampleRateElements[1]); } else if (sampleRateElements.length == 1) { numerator = Long.valueOf(sampleRateElements[0]); denominator = 1L; } List<Long> editRate = new ArrayList<>(); Integer sampleRateToEditRateScale = 1; if(virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainImageSequence)) { CompositionImageEssenceDescriptorModel imageEssenceDescriptorModel = new CompositionImageEssenceDescriptorModel(UUIDHelper.fromUUIDAsURNStringToUUID (imfTrackFileResourceType.getSourceEncoding()), domNodeObjectModel, regXMLLibDictionary); sampleRateToEditRateScale = imageEssenceDescriptorModel.getFrameLayoutType().equals(GenericPictureEssenceDescriptor.FrameLayoutType.SeparateFields) ? 2 : 1; } editRate.add(numerator / sampleRateToEditRateScale); editRate.add(denominator); essenceEditRate = new Composition.EditRate(editRate); } } if (essenceEditRate == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("This Composition represented by the ID %s is invalid since the VirtualTrack represented by ID %s has a Resource represented by ID %s that seems to refer to a EssenceDescriptor in the CPL's EssenceDescriptorList represented by the ID %s " + "which does not have a value set for the field %s, however the Resource Edit Rate is %s" , compositionPlaylistType.getId().toString(), virtualTrack.getTrackID().toString(), imfBaseResourceType.getId(), imfTrackFileResourceType.getSourceEncoding(), essenceDescriptorField, imfBaseResourceType.getEditRate().toString())); } else if (!essenceEditRate.equals(imfBaseResourceType.getEditRate())) { //Section 6.3.1 and 6.3.2 st2067-2:2016 imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("This Composition represented by the ID %s is invalid since the VirtualTrack represented by ID %s has a Resource represented by ID %s that refers to a EssenceDescriptor in the CPL's EssenceDescriptorList represented by the ID %s " + "whose indicated %s value is %s, however the Resource Edit Rate is %s" , compositionPlaylistType.getId().toString(), virtualTrack.getTrackID().toString(), imfBaseResourceType.getId(), imfTrackFileResourceType.getSourceEncoding(), essenceDescriptorField, essenceEditRate.toString(), imfBaseResourceType.getEditRate().toString())); } virtualTrackEssenceDescriptors.add(domNodeObjectModel); } } //Section 6.8 st2067-2:2016 if(!(virtualTrackEssenceDescriptors.size() > 0)){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("This Composition represented by the ID %s is invalid since the resources comprising the VirtualTrack represented by ID %s seem to refer to EssenceDescriptor/s in the CPL's EssenceDescriptorList that are absent", compositionPlaylistType.getId().toString(), virtualTrack.getTrackID().toString())); } else if( virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainImageSequence) || virtualTrack.getSequenceTypeEnum().equals(Composition.SequenceTypeEnum.MainAudioSequence)){ boolean isVirtualTrackHomogeneous = true; DOMNodeObjectModel refDOMNodeObjectModel = virtualTrackEssenceDescriptors.get(0).createDOMNodeObjectModelIgnoreSet(virtualTrackEssenceDescriptors.get(0), IMFCoreConstraintsChecker.VirtualTrackHomogeneityIgnoreSet); for (int i = 1; i < virtualTrackEssenceDescriptors.size(); i++) { isVirtualTrackHomogeneous &= refDOMNodeObjectModel.equals(virtualTrackEssenceDescriptors.get(i).createDOMNodeObjectModelIgnoreSet(virtualTrackEssenceDescriptors.get(i), IMFCoreConstraintsChecker.VirtualTrackHomogeneityIgnoreSet)); } List<DOMNodeObjectModel> modelsIgnoreSet = new ArrayList<>(); if (!isVirtualTrackHomogeneous) { for(int i = 1; i< virtualTrackEssenceDescriptors.size(); i++){ DOMNodeObjectModel other = virtualTrackEssenceDescriptors.get(i).createDOMNodeObjectModelIgnoreSet(virtualTrackEssenceDescriptors.get(i), IMFCoreConstraintsChecker.VirtualTrackHomogeneityIgnoreSet); modelsIgnoreSet.add(other); imfErrorLogger.addAllErrors(DOMNodeObjectModel.getNamespaceURIMismatchErrors(refDOMNodeObjectModel, other)); } //Section 6.2 st2067-2:2016 imfErrorLogger.addAllErrors(refDOMNodeObjectModel.getErrors()); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("This Composition represented by the ID %s is invalid since the VirtualTrack represented by ID %s is not homogeneous based on a comparison of the EssenceDescriptors referenced by its resources in the Essence Descriptor List, " + "the EssenceDescriptors corresponding to this VirtualTrack in the EssenceDescriptorList are as follows %n%n%s", compositionPlaylistType.getId().toString(), virtualTrack.getTrackID().toString(), Utilities.serializeObjectCollectionToString(modelsIgnoreSet))); } } } } //TODO : Add a check to ensure that all the VirtualTracks have the same duration. //Section 6.3.1 st2067-2:2016 and Section 6.9.3 st2067-3:2016 if(!foundMainImageEssence){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("The Composition represented by Id %s does not contain a single image essence in its first segment, exactly one is required", compositionPlaylistType.getId().toString())); } else{ if(numberOfMainImageEssences > 1){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("The Composition represented by Id %s seems to contain %d image essences in its first segment, exactly one is required", compositionPlaylistType.getId().toString(), numberOfMainImageEssences)); } } //Section 6.3.2 st2067-2:2016 and Section 6.9.3 st2067-3:2016 if(!foundMainAudioEssence){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("The Composition represented by Id %s does not contain a single audio essence in its first segment, one or more is required", compositionPlaylistType.getId().toString())); } return imfErrorLogger.getErrors(); } public static void checkSegments(IMFCompositionPlaylistType compositionPlaylistType, Map<UUID, Composition.VirtualTrack> virtualTrackMap, @Nullable IMFErrorLogger imfErrorLogger) { for (IMFSegmentType segment : compositionPlaylistType.getSegmentList()) { Set<UUID> trackIDs = new HashSet<>(); /* TODO: Add check for Marker sequence */ Set<Long> sequencesDurationSet = new HashSet<>(); double compositionEditRate = (double)compositionPlaylistType.getEditRate().getNumerator()/compositionPlaylistType.getEditRate().getDenominator(); for (IMFSequenceType sequence : segment.getSequenceList()) { UUID uuid = UUIDHelper.fromUUIDAsURNStringToUUID(sequence.getTrackId()); trackIDs.add(uuid); if (virtualTrackMap.get(uuid) == null) { //Section 6.9.3 st2067-3:2016 String message = String.format( "Segment represented by the ID %s in the Composition represented by ID %s contains virtual track represented by ID %s, which does not appear in all the segments of the Composition, this is invalid", segment.getId(), compositionPlaylistType.getId().toString(), uuid); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, message); } List<? extends IMFBaseResourceType> resources = sequence.getResourceList(); Long sequenceDurationInCompositionEditUnits = 0L; Long sequenceDuration = 0L; //Based on Section 6.2 and 6.3 in st2067-2:2016 All resources of either an Image Sequence or an Audio Sequence have to be of the same EditRate, hence we can sum the source durations of all the resources //of a virtual track to get its duration in resource edit units. for(IMFBaseResourceType imfBaseResourceType : resources){ sequenceDuration += imfBaseResourceType.getDuration(); } //Section 7.3 st2067-3:2016 long compositionEditRateNumerator = compositionPlaylistType.getEditRate().getNumerator(); long compositionEditRateDenominator = compositionPlaylistType.getEditRate().getDenominator(); long resourceEditRateNumerator = resources.get(0).getEditRate().getNumerator(); long resourceEditRateDenominator = resources.get(0).getEditRate().getDenominator(); long sequenceDurationInCompositionEditRateReminder = (sequenceDuration * compositionEditRateNumerator * resourceEditRateDenominator) % (compositionEditRateDenominator * resourceEditRateNumerator); Double sequenceDurationDoubleValue = ((double)sequenceDuration * compositionEditRateNumerator * resourceEditRateDenominator) / (compositionEditRateDenominator * resourceEditRateNumerator); //Section 7.3 st2067-3:2016 if(sequenceDurationInCompositionEditRateReminder != 0){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Segment represented by the Id %s in the Composition represented by ID %s has a sequence represented by ID %s, whose duration represented in Composition Edit Units is (%f) is not an integer" , segment.getId(), compositionPlaylistType.getId().toString(), sequence.getId(), sequenceDurationDoubleValue)); } sequenceDurationInCompositionEditUnits = Math.round(sequenceDurationDoubleValue); sequencesDurationSet.add(sequenceDurationInCompositionEditUnits); } //Section 7.2 st2067-3:2016 if(sequencesDurationSet.size() > 1){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Segment represented by the Id %s seems to have sequences that are not of the same duration, following sequence durations were computed based on the information in the Sequence List for this Segment, %s represented in Composition Edit Units", segment.getId(), Utilities.serializeObjectCollectionToString(sequencesDurationSet))); } //Section 6.9.3 st2067-3:2016 if (trackIDs.size() != virtualTrackMap.size()) { String message = String.format( "Number of distinct virtual trackIDs in a segment = %s, different from first segment %d", trackIDs.size(), virtualTrackMap.size()); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, message); } } } public static List checkVirtualTrackResourceList(UUID trackID, List<? extends IMFBaseResourceType> virtualBaseResourceList){ IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); //Section 6.9.3 st2067-3:2016 if(virtualBaseResourceList == null || virtualBaseResourceList.size() == 0){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("VirtualTrack with ID %s does not have any associated resources this is invalid", trackID.toString())); return imfErrorLogger.getErrors(); } Set<Composition.EditRate> editRates = new HashSet<>(); Composition.EditRate baseResourceEditRate = null; for(IMFBaseResourceType baseResource : virtualBaseResourceList){ long compositionPlaylistResourceIntrinsicDuration = baseResource.getIntrinsicDuration().longValue(); long compositionPlaylistResourceEntryPoint = (baseResource.getEntryPoint() == null) ? 0L : baseResource.getEntryPoint().longValue(); //Check to see if the Resource's source duration value is in the valid range as specified in st2067-3:2013 section 6.11.6 if(baseResource.getSourceDuration() != null){ if(baseResource.getSourceDuration().longValue() < 0 || baseResource.getSourceDuration().longValue() > (compositionPlaylistResourceIntrinsicDuration - compositionPlaylistResourceEntryPoint)){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("VirtualTrack with ID %s has a resource with ID %s, that has an invalid source duration value %d, should be in the range [0,%d]", trackID.toString(), baseResource.getId(), baseResource.getSourceDuration().longValue(), (compositionPlaylistResourceIntrinsicDuration - compositionPlaylistResourceEntryPoint))); } } //Check to see if the Marker Resource's intrinsic duration value is in the valid range as specified in st2067-3:2013 section 6.13 if (baseResource instanceof IMFMarkerResourceType) { IMFMarkerResourceType markerResource = IMFMarkerResourceType.class.cast(baseResource); List<IMFMarkerType> markerList = markerResource.getMarkerList(); for (IMFMarkerType marker : markerList) { if (marker.getOffset().longValue() >= markerResource.getIntrinsicDuration().longValue()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CPL_ERROR, IMFErrorLogger .IMFErrors.ErrorLevels.FATAL, String.format("VirtualTrack with ID %s has a " + "resource with ID %s, that has a marker %s, that has an invalid offset " + "value %d, should be in the range [0,%d] ", trackID.toString(), markerResource.getId(), marker.getLabel().getValue(), marker .getOffset().longValue(), markerResource.getIntrinsicDuration().longValue()-1)); } } } baseResourceEditRate = baseResource.getEditRate(); if(baseResourceEditRate != null){ editRates.add(baseResourceEditRate); } } //Section 6.2, 6.3.1 and 6.3.2 st2067-2:2016 if(editRates.size() > 1){ StringBuilder editRatesString = new StringBuilder(); Iterator iterator = editRates.iterator(); while(iterator.hasNext()){ editRatesString.append(iterator.next().toString()); editRatesString.append(String.format("%n")); } imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, String.format("VirtualTrack with ID %s has resources with inconsistent editRates %s", trackID.toString(), editRatesString.toString())); } return imfErrorLogger.getErrors(); } }
Add some more ignore fields for image essence homogeneity check
src/main/java/com/netflix/imflibrary/st2067_2/IMFCoreConstraintsChecker.java
Add some more ignore fields for image essence homogeneity check
<ide><path>rc/main/java/com/netflix/imflibrary/st2067_2/IMFCoreConstraintsChecker.java <ide> add("LinkedGenerationID"); <ide> add("MCATitle"); <ide> add("MCATitleVersion"); <add> add("PixelLayout"); <add> add("VideoLineMap"); <add> add("CodingStyleDefault"); <add> add("PictureComponentSizing"); <add> add("QuantizationDefault"); <add> add("Rsiz"); <add> add("Xsiz"); <add> add("Ysiz"); <add> add("XOsiz"); <add> add("YOsiz"); <add> add("XTsiz"); <add> add("YTsiz"); <add> add("XTOsiz"); <add> add("YTOsiz"); <add> add("Csiz"); <ide> }}; <ide> <ide> //To prevent instantiation
JavaScript
mit
dd3b01b6a48a19419a830a03d5aabc9d01c6e2ee
0
jfroom/portfolio-web,jfroom/portfolio-web
// An example configuration file. exports.config = { directConnect: true, //seleniumAddress: 'http://localhost:4444/wd/hub', # travis needs this? // Capabilities to be passed to the webdriver instance. capabilities: { 'browserName': 'chrome' // travis needs 'firefox'? }, // Framework to use. Jasmine is recommended. framework: 'jasmine', // Spec patterns are relative to the current working directory when // protractor is called. suites: { app: [ './e2e/app/app.spec.coffee', './e2e/app/app.nav.spec.coffee' ], work: [ './e2e/app/work/work.spec.coffee', './e2e/app/work/work.nav.spec.coffee', './e2e/app/work/work.projects.spec.coffee' ] }, // Options to be passed to Jasmine. jasmineNodeOpts: { defaultTimeoutInterval: 30000 } };
test/protractor-e2e.conf.js
// An example configuration file. exports.config = { //directConnect: true, seleniumAddress: 'http://localhost:4444/wd/hub', // Capabilities to be passed to the webdriver instance. capabilities: { 'browserName': 'firefox' }, // Framework to use. Jasmine is recommended. framework: 'jasmine', // Spec patterns are relative to the current working directory when // protractor is called. suites: { app: [ './e2e/app/app.spec.coffee', './e2e/app/app.nav.spec.coffee' ], work: [ './e2e/app/work/work.spec.coffee', './e2e/app/work/work.nav.spec.coffee', './e2e/app/work/work.projects.spec.coffee' ] }, // Options to be passed to Jasmine. jasmineNodeOpts: { defaultTimeoutInterval: 30000 } };
Test: protractor, go back to using chrome and directConnect
test/protractor-e2e.conf.js
Test: protractor, go back to using chrome and directConnect
<ide><path>est/protractor-e2e.conf.js <ide> // An example configuration file. <ide> exports.config = { <del> //directConnect: true, <del> seleniumAddress: 'http://localhost:4444/wd/hub', <add> directConnect: true, <add> //seleniumAddress: 'http://localhost:4444/wd/hub', # travis needs this? <ide> <ide> // Capabilities to be passed to the webdriver instance. <ide> capabilities: { <del> 'browserName': 'firefox' <add> 'browserName': 'chrome' // travis needs 'firefox'? <ide> }, <ide> <ide> // Framework to use. Jasmine is recommended.
Java
apache-2.0
7fae743fbdb2bf57e7bafe20646336ab17df2224
0
Medium/closure-templates,Medium/closure-templates,Medium/closure-templates,Medium/closure-templates,google/closure-templates,yext/closure-templates,yext/closure-templates,google/closure-templates,google/closure-templates,google/closure-templates,yext/closure-templates,Medium/closure-templates,yext/closure-templates,google/closure-templates
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.template.soy.passes; import com.google.common.base.Preconditions; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import com.google.template.soy.base.SourceLocation; import com.google.template.soy.base.internal.SanitizedContentKind; import com.google.template.soy.basicfunctions.FloatFunction; import com.google.template.soy.error.ErrorReporter; import com.google.template.soy.error.SoyErrorKind; import com.google.template.soy.error.SoyErrorKind.StyleAllowance; import com.google.template.soy.exprtree.ExprNode; import com.google.template.soy.exprtree.ExprRootNode; import com.google.template.soy.exprtree.FunctionNode; import com.google.template.soy.passes.FindIndirectParamsVisitor.IndirectParamsInfo; import com.google.template.soy.soytree.AbstractSoyNodeVisitor; import com.google.template.soy.soytree.CallBasicNode; import com.google.template.soy.soytree.CallDelegateNode; import com.google.template.soy.soytree.CallNode; import com.google.template.soy.soytree.CallParamContentNode; import com.google.template.soy.soytree.CallParamNode; import com.google.template.soy.soytree.CallParamValueNode; import com.google.template.soy.soytree.SoyFileSetNode; import com.google.template.soy.soytree.SoyNode; import com.google.template.soy.soytree.SoyNode.ParentSoyNode; import com.google.template.soy.soytree.TemplateDelegateNode; import com.google.template.soy.soytree.TemplateNode; import com.google.template.soy.soytree.TemplateRegistry; import com.google.template.soy.soytree.defn.HeaderParam; import com.google.template.soy.soytree.defn.TemplateParam; import com.google.template.soy.soytree.defn.TemplateParam.DeclLoc; import com.google.template.soy.types.SoyType; import com.google.template.soy.types.SoyType.Kind; import com.google.template.soy.types.SoyTypes; import com.google.template.soy.types.aggregate.UnionType; import com.google.template.soy.types.primitive.FloatType; import com.google.template.soy.types.primitive.SanitizedType; import com.google.template.soy.types.primitive.StringType; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; /** * This compiler pass runs several checks on {@code CallNode}s. * * <ul> * <li> Checks that calling arguments match the declared parameter types of the called template. * <li> Checks missing or duplicate parameters. * <li> Checks strict-html templates can only call other strict-html templates from an html * context. * </ul> * * <p>In addition to checking that static types match and flagging errors, this visitor also stores * a set of TemplateParam object in each {@code CallNode} for all the params that require runtime * checking. * * <p>Note: This pass requires that the ResolveExpressionTypesVisitor has already been run. */ final class CheckTemplateCallsPass extends CompilerFileSetPass { static final SoyErrorKind ARGUMENT_TYPE_MISMATCH = SoyErrorKind.of( "Type mismatch on param {0}: expected: {1}, actual: {2}", StyleAllowance.NO_PUNCTUATION); private static final SoyErrorKind DUPLICATE_PARAM = SoyErrorKind.of("Duplicate param ''{0}''."); private static final SoyErrorKind MISSING_PARAM = SoyErrorKind.of("Call missing required {0}."); private static final SoyErrorKind PASSING_PROTOBUF_FROM_STRICT_TO_NON_STRICT = SoyErrorKind.of("Passing protobuf {0} of type {1} to an untyped template is not allowed."); private static final SoyErrorKind STRICT_HTML = SoyErrorKind.of( "Found call to non stricthtml template. Strict HTML template " + "can only call other strict HTML templates from an HTML context."); /** The error reporter that is used in this compiler pass. */ private final ErrorReporter errorReporter; CheckTemplateCallsPass(ErrorReporter errorReporter) { this.errorReporter = errorReporter; } @Override public void run(SoyFileSetNode fileSet, TemplateRegistry registry) { new CheckCallsVisitor(registry).exec(fileSet); } private final class CheckCallsVisitor extends AbstractSoyNodeVisitor<Void> { /** Registry of all templates in the Soy tree. */ private final TemplateRegistry templateRegistry; /** The current template being checked. */ private TemplateNode callerTemplate; /** Map of all template parameters, both explicit and implicit, organized by template. */ private final Map<TemplateNode, TemplateParamTypes> paramTypesMap = new HashMap<>(); CheckCallsVisitor(TemplateRegistry registry) { this.templateRegistry = registry; } @Override protected void visitCallBasicNode(CallBasicNode node) { TemplateNode callee = templateRegistry.getBasicTemplate(node.getCalleeName()); if (callee != null) { Set<TemplateParam> paramsToRuntimeCheck = checkCallParamTypes(node, callee); node.setParamsToRuntimeCheck(paramsToRuntimeCheck); checkCallParamNames(node, callee); } checkStrictHtml(node, callee); visitChildren(node); } @Override protected void visitCallDelegateNode(CallDelegateNode node) { ImmutableMap.Builder<TemplateDelegateNode, ImmutableList<TemplateParam>> paramsToCheckByTemplate = ImmutableMap.builder(); ImmutableList<TemplateDelegateNode> potentialCallees = templateRegistry .getDelTemplateSelector() .delTemplateNameToValues() .get(node.getDelCalleeName()); for (TemplateDelegateNode delTemplate : potentialCallees) { Set<TemplateParam> params = checkCallParamTypes(node, delTemplate); paramsToCheckByTemplate.put(delTemplate, ImmutableList.copyOf(params)); checkCallParamNames(node, delTemplate); } node.setParamsToRuntimeCheck(paramsToCheckByTemplate.build()); if (!potentialCallees.isEmpty()) { checkStrictHtml(node, potentialCallees.get(0)); } visitChildren(node); } @Override protected void visitSoyNode(SoyNode node) { if (node instanceof ParentSoyNode<?>) { visitChildren((ParentSoyNode<?>) node); } } @Override protected void visitTemplateNode(TemplateNode node) { callerTemplate = node; visitChildren(node); callerTemplate = null; } /** * Returns the subset of {@link TemplateNode#getParams() callee params} that require runtime * type checking. */ private Set<TemplateParam> checkCallParamTypes(CallNode call, TemplateNode callee) { TemplateParamTypes calleeParamTypes = getTemplateParamTypes(callee); // Explicit params being passed by the CallNode Set<String> explicitParams = new HashSet<>(); // The set of params that need runtime type checking at template call time. We start this with // all the params of the callee and remove each param that is statically verified. Set<String> paramNamesToRuntimeCheck = new HashSet<>(calleeParamTypes.params.keySet()); // indirect params should be checked at their callsites, not this one. paramNamesToRuntimeCheck.removeAll(calleeParamTypes.indirectParamNames); // First check all the {param} blocks of the caller to make sure that the types match. for (CallParamNode callerParam : call.getChildren()) { String paramName = callerParam.getKey().identifier(); // The types of the parameters. If this is an explicitly declared parameter, // then this collection will have only one member; If it's an implicit // parameter then this may contain multiple types. Note we don't use // a union here because the rules are a bit different than the normal rules // for assigning union types. // It's possible that the set may be empty, because all of the callees // are external. In that case there's nothing we can do, so we don't // report anything. Collection<SoyType> declaredParamTypes = calleeParamTypes.params.get(paramName); // Type of the param value. May be null if the param is a v1 expression. SoyType argType = null; if (callerParam.getKind() == SoyNode.Kind.CALL_PARAM_VALUE_NODE) { CallParamValueNode node = (CallParamValueNode) callerParam; ExprNode expr = node.getExpr(); if (expr != null) { argType = maybeCoerceType(node, expr.getType(), declaredParamTypes); } } else if (callerParam.getKind() == SoyNode.Kind.CALL_PARAM_CONTENT_NODE) { SanitizedContentKind contentKind = ((CallParamContentNode) callerParam).getContentKind(); argType = contentKind == null ? StringType.getInstance() : SanitizedType.getTypeForContentKind(contentKind); } else { throw new AssertionError(); // CallParamNode shouldn't have any other kind of child } // If the param is a v1 expression (so argType == null) we can't check anything, or if the // calculated type is an error type (because we already reported a type error for this // expression) don't check whether it matches the formal param. if (argType != null && argType.getKind() != SoyType.Kind.ERROR) { boolean staticTypeSafe = true; for (SoyType formalType : declaredParamTypes) { staticTypeSafe &= checkArgumentAgainstParamType( callerParam.getSourceLocation(), paramName, argType, formalType, calleeParamTypes); } if (staticTypeSafe) { paramNamesToRuntimeCheck.remove(paramName); } } explicitParams.add(paramName); } // If the caller is passing data via data="all" then we look for matching static param // declarations in the callers template and see if there are type errors there. if (call.isPassingData()) { if (call.isPassingAllData()) { // Check indirect params that are passed via data="all". // We only need to check explicit params of calling template here. for (TemplateParam callerParam : callerTemplate.getParams()) { if (!(callerParam instanceof HeaderParam)) { continue; } String paramName = callerParam.name(); // The parameter is explicitly overridden with another value, which we // already checked. if (explicitParams.contains(paramName)) { continue; } Collection<SoyType> declaredParamTypes = calleeParamTypes.params.get(paramName); boolean staticTypeSafe = true; for (SoyType formalType : declaredParamTypes) { staticTypeSafe &= checkArgumentAgainstParamType( call.getSourceLocation(), paramName, callerParam.type(), formalType, calleeParamTypes); } if (staticTypeSafe) { paramNamesToRuntimeCheck.remove(paramName); } } } else { // TODO: Check if the fields of the type of data arg can be assigned to the params. // This is possible for some types, and never allowed for other types. } } /** * We track the set as names above and transform to TemplateParams here because the above * loops are over the {param}s of the caller and TemplateParams of the callers template, so * all we have are the names of the parameters. To convert them to a TemplateParam of the * callee we need to match the names and it is easier to do that as one pass at the end * instead of iteratively throughout. */ Set<TemplateParam> paramsToRuntimeCheck = new HashSet<>(); for (TemplateParam param : callee.getParams()) { if (paramNamesToRuntimeCheck.remove(param.name())) { paramsToRuntimeCheck.add(param); } } // sanity check Preconditions.checkState( paramNamesToRuntimeCheck.isEmpty(), "Unexpected callee params %s", paramNamesToRuntimeCheck); return paramsToRuntimeCheck; } /** * For int values passed into template param float, perform automatic type coercion from the * call param value to the template param type. * * <p>Supported coercions: * * <ul> * <li>int -> float * <li>int -> float|null * </ul> * * @param paramNode Node containing the call param value * @param argType Type of the call param value * @param declaredTypes Types accepted by the template param * @return the new coerced type */ @CheckReturnValue private SoyType maybeCoerceType( CallParamValueNode paramNode, SoyType argType, Collection<SoyType> declaredTypes) { if (argType.getKind() == Kind.INT && (declaredTypes.contains(FloatType.getInstance()) || declaredTypes.contains(SoyTypes.makeNullable(FloatType.getInstance())))) { for (SoyType formalType : declaredTypes) { if (formalType.isAssignableFrom(argType)) { return argType; // template already accepts int, no need to coerce } } ExprRootNode root = paramNode.getExpr(); // create a node to wrap param in float coercion FunctionNode newParam = new FunctionNode(FloatFunction.INSTANCE, root.getRoot().getSourceLocation()); newParam.setType(FloatType.getInstance()); newParam.addChild(root.getRoot()); root.addChild(newParam); return FloatType.getInstance(); } return argType; } /** * Check that the argument passed to the template is compatible with the template parameter * type. * * @param location The location to report a type check error. * @param paramName the name of the parameter. * @param argType The type of the value being passed. * @param formalType The type of the parameter. * @param calleeParams metadata about the callee parameters * @return true if runtime type checks can be elided for this param */ private boolean checkArgumentAgainstParamType( SourceLocation location, String paramName, SoyType argType, SoyType formalType, TemplateParamTypes calleeParams) { if ((!calleeParams.isStrictlyTyped && formalType.getKind() == SoyType.Kind.UNKNOWN) || formalType.getKind() == SoyType.Kind.ANY) { // Special rules for unknown / any if (argType.getKind() == SoyType.Kind.PROTO) { errorReporter.report( location, PASSING_PROTOBUF_FROM_STRICT_TO_NON_STRICT, paramName, argType); } } else if (argType.getKind() == SoyType.Kind.UNKNOWN) { // Special rules for unknown / any // // This check disabled: We now allow maps created from protos to be passed // to a function accepting a proto, this makes migration easier. // (See GenJsCodeVisitor.genParamTypeChecks). // TODO(user): Re-enable at some future date? // if (formalType.getKind() == SoyType.Kind.PROTO || SoyType.Kind.PROTO_ENUM) { // reportProtoArgumentTypeMismatch(call, paramName, formalType, argType); // } } else { if (!formalType.isAssignableFrom(argType)) { if (calleeParams.isIndirect(paramName) && argType.getKind() == SoyType.Kind.UNION && ((UnionType) argType).isNullable() && SoyTypes.makeNullable(formalType).isAssignableFrom(argType)) { // Special case for indirect params: Allow a nullable type to be assigned // to a non-nullable type if the non-nullable type is an indirect parameter type. // The reason is because without flow analysis, we can't know whether or not // there are if-statements preventing null from being passed as an indirect // param, so we assume all indirect params are optional. return false; } errorReporter.report(location, ARGUMENT_TYPE_MISMATCH, paramName, formalType, argType); } } return true; } /** * Get the parameter types for a callee. * * @param node The template being called. * @return The set of template parameters, both explicit and implicit. */ private TemplateParamTypes getTemplateParamTypes(TemplateNode node) { TemplateParamTypes paramTypes = paramTypesMap.get(node); if (paramTypes == null) { paramTypes = new TemplateParamTypes(); // Store all of the explicitly declared param types for (TemplateParam param : node.getParams()) { if (param.declLoc() == DeclLoc.SOY_DOC) { paramTypes.isStrictlyTyped = false; } Preconditions.checkNotNull(param.type()); paramTypes.params.put(param.name(), param.type()); } // Store indirect params where there's no conflict with explicit params. // Note that we don't check here whether the explicit type and the implicit // types are in agreement - that will be done when it's this template's // turn to be analyzed as a caller. IndirectParamsInfo ipi = new FindIndirectParamsVisitor(templateRegistry).exec(node); for (String indirectParamName : ipi.indirectParamTypes.keySet()) { if (paramTypes.params.containsKey(indirectParamName)) { continue; } paramTypes.params.putAll( indirectParamName, ipi.indirectParamTypes.get(indirectParamName)); paramTypes.indirectParamNames.add(indirectParamName); } // Save the param types map paramTypesMap.put(node, paramTypes); } return paramTypes; } /** * Helper method that reports an error if a strict html template calls a non-strict html * template from HTML context. */ private void checkStrictHtml(CallNode caller, @Nullable TemplateNode callee) { // We should only check strict html if 1) the current template // sets stricthtml to true, and 2) the current call node is in HTML context. // Then we report an error if the callee is HTML but is not a strict HTML template. if (callerTemplate.isStrictHtml() && caller.getIsPcData() && callee != null && callee.getContentKind() == SanitizedContentKind.HTML && !callee.isStrictHtml()) { errorReporter.report(caller.getSourceLocation(), STRICT_HTML); } } /** * Helper method that reports an error if: * * <ul> * <li> There are duplicate params for the caller. * <li> Required parameters in callee template are not presented in the caller. * </ul> */ private void checkCallParamNames(CallNode caller, TemplateNode callee) { if (callee != null) { // Get param keys passed by caller. Set<String> callerParamKeys = Sets.newHashSet(); for (CallParamNode callerParam : caller.getChildren()) { boolean isUnique = callerParamKeys.add(callerParam.getKey().identifier()); if (!isUnique) { // Found a duplicate param. errorReporter.report( callerParam.getKey().location(), DUPLICATE_PARAM, callerParam.getKey().identifier()); } } // If all the data keys being passed are listed using 'param' commands, then check that all // required params of the callee are included. if (!caller.isPassingData()) { // Check param keys required by callee. List<String> missingParamKeys = Lists.newArrayListWithCapacity(2); for (TemplateParam calleeParam : callee.getParams()) { if (calleeParam.isRequired() && !callerParamKeys.contains(calleeParam.name())) { missingParamKeys.add(calleeParam.name()); } } // Report errors. if (!missingParamKeys.isEmpty()) { String errorMsgEnd = (missingParamKeys.size() == 1) ? "param '" + missingParamKeys.get(0) + "'" : "params " + missingParamKeys; errorReporter.report(caller.getSourceLocation(), MISSING_PARAM, errorMsgEnd); } } } } private class TemplateParamTypes { public boolean isStrictlyTyped = true; public final Multimap<String, SoyType> params = HashMultimap.create(); public final Set<String> indirectParamNames = new HashSet<>(); public boolean isIndirect(String paramName) { return indirectParamNames.contains(paramName); } } } }
java/src/com/google/template/soy/passes/CheckTemplateCallsPass.java
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.template.soy.passes; import com.google.common.base.Preconditions; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import com.google.template.soy.base.SourceLocation; import com.google.template.soy.base.internal.SanitizedContentKind; import com.google.template.soy.basicfunctions.FloatFunction; import com.google.template.soy.error.ErrorReporter; import com.google.template.soy.error.SoyErrorKind; import com.google.template.soy.error.SoyErrorKind.StyleAllowance; import com.google.template.soy.exprtree.ExprNode; import com.google.template.soy.exprtree.ExprRootNode; import com.google.template.soy.exprtree.FunctionNode; import com.google.template.soy.passes.FindIndirectParamsVisitor.IndirectParamsInfo; import com.google.template.soy.soytree.AbstractSoyNodeVisitor; import com.google.template.soy.soytree.CallBasicNode; import com.google.template.soy.soytree.CallDelegateNode; import com.google.template.soy.soytree.CallNode; import com.google.template.soy.soytree.CallParamContentNode; import com.google.template.soy.soytree.CallParamNode; import com.google.template.soy.soytree.CallParamValueNode; import com.google.template.soy.soytree.SoyFileSetNode; import com.google.template.soy.soytree.SoyNode; import com.google.template.soy.soytree.SoyNode.ParentSoyNode; import com.google.template.soy.soytree.TemplateDelegateNode; import com.google.template.soy.soytree.TemplateNode; import com.google.template.soy.soytree.TemplateRegistry; import com.google.template.soy.soytree.defn.HeaderParam; import com.google.template.soy.soytree.defn.TemplateParam; import com.google.template.soy.soytree.defn.TemplateParam.DeclLoc; import com.google.template.soy.types.SoyType; import com.google.template.soy.types.SoyType.Kind; import com.google.template.soy.types.SoyTypes; import com.google.template.soy.types.aggregate.UnionType; import com.google.template.soy.types.primitive.FloatType; import com.google.template.soy.types.primitive.SanitizedType; import com.google.template.soy.types.primitive.StringType; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; /** * This compiler pass runs several checks on {@code CallNode}s. * * <ul> * <li> Checks that calling arguments match the declared parameter types of the called template. * <li> Checks missing or duplicate parameters. * <li> Checks strict-html templates can only call other strict-html templates from an html * context. * </ul> * * <p>In addition to checking that static types match and flagging errors, this visitor also stores * a set of TemplateParam object in each {@code CallNode} for all the params that require runtime * checking. * * <p>Note: This pass requires that the ResolveExpressionTypesVisitor has already been run. */ final class CheckTemplateCallsPass extends CompilerFileSetPass { static final SoyErrorKind ARGUMENT_TYPE_MISMATCH = SoyErrorKind.of( "Type mismatch on param {0}: expected: {1}, actual: {2}", StyleAllowance.NO_PUNCTUATION); private static final SoyErrorKind DUPLICATE_PARAM = SoyErrorKind.of("Duplicate param ''{0}''."); private static final SoyErrorKind MISSING_PARAM = SoyErrorKind.of("Call missing required {0}."); private static final SoyErrorKind PASSING_PROTOBUF_FROM_STRICT_TO_NON_STRICT = SoyErrorKind.of("Passing protobuf {0} of type {1} to an untyped template is not allowed."); private static final SoyErrorKind STRICT_HTML = SoyErrorKind.of( "Found call to non stricthtml template. Strict HTML template " + "can only call other strict HTML templates from an HTML context."); /** The error reporter that is used in this compiler pass. */ private final ErrorReporter errorReporter; CheckTemplateCallsPass(ErrorReporter errorReporter) { this.errorReporter = errorReporter; } @Override public void run(SoyFileSetNode fileSet, TemplateRegistry registry) { new CheckCallsVisitor(registry).exec(fileSet); } private final class CheckCallsVisitor extends AbstractSoyNodeVisitor<Void> { /** Registry of all templates in the Soy tree. */ private final TemplateRegistry templateRegistry; /** The current template being checked. */ private TemplateNode callerTemplate; /** Map of all template parameters, both explicit and implicit, organized by template. */ private final Map<TemplateNode, TemplateParamTypes> paramTypesMap = new HashMap<>(); CheckCallsVisitor(TemplateRegistry registry) { this.templateRegistry = registry; } @Override protected void visitCallBasicNode(CallBasicNode node) { TemplateNode callee = templateRegistry.getBasicTemplate(node.getCalleeName()); if (callee != null) { Set<TemplateParam> paramsToRuntimeCheck = checkCallParamTypes(node, callee); node.setParamsToRuntimeCheck(paramsToRuntimeCheck); checkCallParamNames(node, callee); } checkStrictHtml(node, callee); visitChildren(node); } @Override protected void visitCallDelegateNode(CallDelegateNode node) { ImmutableMap.Builder<TemplateDelegateNode, ImmutableList<TemplateParam>> paramsToCheckByTemplate = ImmutableMap.builder(); ImmutableList<TemplateDelegateNode> potentialCallees = templateRegistry .getDelTemplateSelector() .delTemplateNameToValues() .get(node.getDelCalleeName()); for (TemplateDelegateNode delTemplate : potentialCallees) { Set<TemplateParam> params = checkCallParamTypes(node, delTemplate); paramsToCheckByTemplate.put(delTemplate, ImmutableList.copyOf(params)); checkCallParamNames(node, delTemplate); } node.setParamsToRuntimeCheck(paramsToCheckByTemplate.build()); if (!potentialCallees.isEmpty()) { checkStrictHtml(node, potentialCallees.get(0)); } visitChildren(node); } @Override protected void visitSoyNode(SoyNode node) { if (node instanceof ParentSoyNode<?>) { visitChildren((ParentSoyNode<?>) node); } } @Override protected void visitTemplateNode(TemplateNode node) { callerTemplate = node; visitChildren(node); callerTemplate = null; } /** * Returns the subset of {@link TemplateNode#getParams() callee params} that require runtime * type checking. */ private Set<TemplateParam> checkCallParamTypes(CallNode call, TemplateNode callee) { TemplateParamTypes calleeParamTypes = getTemplateParamTypes(callee); // Explicit params being passed by the CallNode Set<String> explicitParams = new HashSet<>(); // The set of params that need runtime type checking at template call time. We start this with // all the params of the callee and remove each param that is statically verified. Set<String> paramNamesToRuntimeCheck = new HashSet<>(calleeParamTypes.params.keySet()); // indirect params should be checked at their callsites, not this one. paramNamesToRuntimeCheck.removeAll(calleeParamTypes.indirectParamNames); // First check all the {param} blocks of the caller to make sure that the types match. for (CallParamNode callerParam : call.getChildren()) { String paramName = callerParam.getKey().identifier(); // The types of the parameters. If this is an explicitly declared parameter, // then this collection will have only one member; If it's an implicit // parameter then this may contain multiple types. Note we don't use // a union here because the rules are a bit different than the normal rules // for assigning union types. // It's possible that the set may be empty, because all of the callees // are external. In that case there's nothing we can do, so we don't // report anything. Collection<SoyType> declaredParamTypes = calleeParamTypes.params.get(paramName); // Type of the param value. May be null if the param is a v1 expression. SoyType argType = null; if (callerParam.getKind() == SoyNode.Kind.CALL_PARAM_VALUE_NODE) { CallParamValueNode node = (CallParamValueNode) callerParam; ExprNode expr = node.getExpr(); if (expr != null) { argType = maybeCoerceType(node, expr.getType(), declaredParamTypes); } } else if (callerParam.getKind() == SoyNode.Kind.CALL_PARAM_CONTENT_NODE) { SanitizedContentKind contentKind = ((CallParamContentNode) callerParam).getContentKind(); argType = contentKind == null ? StringType.getInstance() : SanitizedType.getTypeForContentKind(contentKind); } else { throw new AssertionError(); // CallParamNode shouldn't have any other kind of child } // If the param is a v1 expression (so argType == null) we can't check anything, or if the // calculated type is an error type (because we already reported a type error for this // expression) don't check whether it matches the formal param. if (argType != null && argType.getKind() != SoyType.Kind.ERROR) { boolean staticTypeSafe = true; for (SoyType formalType : declaredParamTypes) { staticTypeSafe &= checkArgumentAgainstParamType( callerParam.getSourceLocation(), paramName, argType, formalType, calleeParamTypes); } if (staticTypeSafe) { paramNamesToRuntimeCheck.remove(paramName); } } explicitParams.add(paramName); } // If the caller is passing data via data="all" then we look for matching static param // declarations in the callers template and see if there are type errors there. if (call.isPassingData()) { if (call.isPassingAllData()) { // Check indirect params that are passed via data="all". // We only need to check explicit params of calling template here. for (TemplateParam callerParam : callerTemplate.getParams()) { if (!(callerParam instanceof HeaderParam)) { continue; } String paramName = callerParam.name(); // The parameter is explicitly overridden with another value, which we // already checked. if (explicitParams.contains(paramName)) { continue; } Collection<SoyType> declaredParamTypes = calleeParamTypes.params.get(paramName); boolean staticTypeSafe = true; for (SoyType formalType : declaredParamTypes) { staticTypeSafe &= checkArgumentAgainstParamType( call.getSourceLocation(), paramName, callerParam.type(), formalType, calleeParamTypes); } if (staticTypeSafe) { paramNamesToRuntimeCheck.remove(paramName); } } } else { // TODO: Check if the fields of the type of data arg can be assigned to the params. // This is possible for some types, and never allowed for other types. } } /** * We track the set as names above and transform to TemplateParams here because the above * loops are over the {param}s of the caller and TemplateParams of the callers template, so * all we have are the names of the parameters. To convert them to a TemplateParam of the * callee we need to match the names and it is easier to do that as one pass at the end * instead of iteratively throughout. */ Set<TemplateParam> paramsToRuntimeCheck = new HashSet<>(); for (TemplateParam param : callee.getParams()) { if (paramNamesToRuntimeCheck.remove(param.name())) { paramsToRuntimeCheck.add(param); } } // sanity check Preconditions.checkState( paramNamesToRuntimeCheck.isEmpty(), "Unexpected callee params %s", paramNamesToRuntimeCheck); return paramsToRuntimeCheck; } /** * For int values passed into template param float, perform automatic type coercion from the * call param value to the template param type. * * <p>Supported coercions: * * <ul> * <li>int -> float * <li>int -> float|null * </ul> * * @param paramNode Node containing the call param value * @param argType Type of the call param value * @param declaredTypes Types accepted by the template param * @return the new coerced type */ @CheckReturnValue private SoyType maybeCoerceType( CallParamValueNode paramNode, SoyType argType, Collection<SoyType> declaredTypes) { if (argType.getKind() == Kind.INT && (declaredTypes.contains(FloatType.getInstance()) || declaredTypes.contains(SoyTypes.makeNullable(FloatType.getInstance())))) { for (SoyType formalType : declaredTypes) { if (formalType.isAssignableFrom(argType)) { return argType; // template already accepts int, no need to coerce } } ExprRootNode root = paramNode.getExpr(); // create a node to wrap param in float coercion FunctionNode newParam = new FunctionNode(FloatFunction.INSTANCE, root.getRoot().getSourceLocation()); newParam.setType(FloatType.getInstance()); newParam.addChild(root.getRoot()); root.addChild(newParam); return FloatType.getInstance(); } return argType; } /** * Check that the argument passed to the template is compatible with the template parameter * type. * * @param location The location to report a type check error. * @param paramName the name of the parameter. * @param argType The type of the value being passed. * @param formalType The type of the parameter. * @param calleeParams metadata about the callee parameters * @return true if runtime type checks can be elided for this param */ private boolean checkArgumentAgainstParamType( SourceLocation location, String paramName, SoyType argType, SoyType formalType, TemplateParamTypes calleeParams) { if ((!calleeParams.isStrictlyTyped && formalType.getKind() == SoyType.Kind.UNKNOWN) || formalType.getKind() == SoyType.Kind.ANY) { // Special rules for unknown / any if (argType.getKind() == SoyType.Kind.PROTO) { errorReporter.report( location, PASSING_PROTOBUF_FROM_STRICT_TO_NON_STRICT, paramName, argType); } } else if (argType.getKind() == SoyType.Kind.UNKNOWN) { // Special rules for unknown / any // // This check disabled: We now allow maps created from protos to be passed // to a function accepting a proto, this makes migration easier. // (See GenJsCodeVisitor.genParamTypeChecks). // TODO(user): Re-enable at some future date? // if (formalType.getKind() == SoyType.Kind.PROTO || SoyType.Kind.PROTO_ENUM) { // reportProtoArgumentTypeMismatch(call, paramName, formalType, argType); // } } else { if (!formalType.isAssignableFrom(argType)) { if (calleeParams.isIndirect(paramName) && argType.getKind() == SoyType.Kind.UNION && ((UnionType) argType).isNullable() && SoyTypes.makeNullable(formalType).isAssignableFrom(argType)) { // Special case for indirect params: Allow a nullable type to be assigned // to a non-nullable type if the non-nullable type is an indirect parameter type. // The reason is because without flow analysis, we can't know whether or not // there are if-statements preventing null from being passed as an indirect // param, so we assume all indirect params are optional. return false; } errorReporter.report(location, ARGUMENT_TYPE_MISMATCH, paramName, formalType, argType); } } return true; } /** * Get the parameter types for a callee. * * @param node The template being called. * @return The set of template parameters, both explicit and implicit. */ private TemplateParamTypes getTemplateParamTypes(TemplateNode node) { TemplateParamTypes paramTypes = paramTypesMap.get(node); if (paramTypes == null) { paramTypes = new TemplateParamTypes(); // Store all of the explicitly declared param types for (TemplateParam param : node.getParams()) { if (param.declLoc() == DeclLoc.SOY_DOC) { paramTypes.isStrictlyTyped = false; } Preconditions.checkNotNull(param.type()); paramTypes.params.put(param.name(), param.type()); } // Store indirect params where there's no conflict with explicit params. // Note that we don't check here whether the explicit type and the implicit // types are in agreement - that will be done when it's this template's // turn to be analyzed as a caller. IndirectParamsInfo ipi = new FindIndirectParamsVisitor(templateRegistry).exec(node); for (String indirectParamName : ipi.indirectParamTypes.keySet()) { if (paramTypes.params.containsKey(indirectParamName)) { continue; } paramTypes.params.putAll( indirectParamName, ipi.indirectParamTypes.get(indirectParamName)); paramTypes.indirectParamNames.add(indirectParamName); } // Save the param types map paramTypesMap.put(node, paramTypes); } return paramTypes; } /** * Helper method that reports an error if a strict html template calls a non-strict html * template from HTML context. */ private void checkStrictHtml(CallNode caller, @Nullable TemplateNode callee) { // We should only check strict html if 1) the current template // sets stricthtml to true, and 2) the current call node is in HTML context. // Then we report an error if the callee is HTML but is not a strict HTML template. if (callerTemplate.isStrictHtml() && caller.getIsPcData() && callee != null && callee.getContentKind() == SanitizedContentKind.HTML && !callee.isStrictHtml()) { errorReporter.report(caller.getSourceLocation(), STRICT_HTML); } } /** * Helper method that reports an error if: * * <ul> * <li> There are duplicate params for the caller. * <li> Required parameters in callee template are not presented in the caller. * </ul> */ private void checkCallParamNames(CallNode caller, TemplateNode callee) { // If all the data keys being passed are listed using 'param' commands, then check that all // required params of the callee are included. if (!caller.isPassingData()) { if (callee != null) { // Get param keys passed by caller. Set<String> callerParamKeys = Sets.newHashSet(); for (CallParamNode callerParam : caller.getChildren()) { boolean isUnique = callerParamKeys.add(callerParam.getKey().identifier()); if (!isUnique) { // Found a duplicate param. errorReporter.report( callerParam.getKey().location(), DUPLICATE_PARAM, callerParam.getKey().identifier()); } } // Check param keys required by callee. List<String> missingParamKeys = Lists.newArrayListWithCapacity(2); for (TemplateParam calleeParam : callee.getParams()) { if (calleeParam.isRequired() && !callerParamKeys.contains(calleeParam.name())) { missingParamKeys.add(calleeParam.name()); } } // Report errors. if (!missingParamKeys.isEmpty()) { String errorMsgEnd = (missingParamKeys.size() == 1) ? "param '" + missingParamKeys.get(0) + "'" : "params " + missingParamKeys; errorReporter.report(caller.getSourceLocation(), MISSING_PARAM, errorMsgEnd); } } } } private class TemplateParamTypes { public boolean isStrictlyTyped = true; public final Multimap<String, SoyType> params = HashMultimap.create(); public final Set<String> indirectParamNames = new HashSet<>(); public boolean isIndirect(String paramName) { return indirectParamNames.contains(paramName); } } } }
Check for duplicate {param} even with data="" in {call}. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=179174824
java/src/com/google/template/soy/passes/CheckTemplateCallsPass.java
Check for duplicate {param} even with data="" in {call}.
<ide><path>ava/src/com/google/template/soy/passes/CheckTemplateCallsPass.java <ide> * </ul> <ide> */ <ide> private void checkCallParamNames(CallNode caller, TemplateNode callee) { <del> // If all the data keys being passed are listed using 'param' commands, then check that all <del> // required params of the callee are included. <del> if (!caller.isPassingData()) { <del> if (callee != null) { <del> // Get param keys passed by caller. <del> Set<String> callerParamKeys = Sets.newHashSet(); <del> for (CallParamNode callerParam : caller.getChildren()) { <del> boolean isUnique = callerParamKeys.add(callerParam.getKey().identifier()); <del> if (!isUnique) { <del> // Found a duplicate param. <del> errorReporter.report( <del> callerParam.getKey().location(), <del> DUPLICATE_PARAM, <del> callerParam.getKey().identifier()); <del> } <del> } <add> if (callee != null) { <add> // Get param keys passed by caller. <add> Set<String> callerParamKeys = Sets.newHashSet(); <add> for (CallParamNode callerParam : caller.getChildren()) { <add> boolean isUnique = callerParamKeys.add(callerParam.getKey().identifier()); <add> if (!isUnique) { <add> // Found a duplicate param. <add> errorReporter.report( <add> callerParam.getKey().location(), <add> DUPLICATE_PARAM, <add> callerParam.getKey().identifier()); <add> } <add> } <add> // If all the data keys being passed are listed using 'param' commands, then check that all <add> // required params of the callee are included. <add> if (!caller.isPassingData()) { <ide> // Check param keys required by callee. <ide> List<String> missingParamKeys = Lists.newArrayListWithCapacity(2); <ide> for (TemplateParam calleeParam : callee.getParams()) {
Java
mit
a4386806271e2b97325184e7965ce2f1d9ffdf16
0
angelozerr/eclipse-wtp-json,angelozerr/eclipse-wtp-json,angelozerr/eclipse-wtp-json
package org.eclipse.wst.json.ui.internal.projection; import org.eclipse.jface.text.Position; import org.eclipse.wst.json.core.document.IJSONArray; import org.eclipse.wst.json.core.document.IJSONNode; import org.eclipse.wst.json.core.document.IJSONObject; import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion; import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; import org.eclipse.wst.sse.ui.internal.projection.AbstractStructuredFoldingStrategy; /** * A folding strategy for JSON type structured documents. * See AbstractStructuredFoldingStrategy for more details. */ public class JSONFoldingStrategy extends AbstractStructuredFoldingStrategy { /** * Create an instance of the folding strategy. * Be sure to set the viewer and document after creation. */ public JSONFoldingStrategy() { super(); } /** * @see org.eclipse.wst.sse.ui.internal.projection.AbstractFoldingStrategy#calcNewFoldPosition(org.eclipse.wst.sse.core.internal.provisional.IndexedRegion) */ protected Position calcNewFoldPosition(IndexedRegion indexedRegion) { Position retPos = null; //only want to fold regions of the valid type and with a valid range if(indexedRegion.getStartOffset() >= 0 && indexedRegion.getLength() >= 0) { IJSONNode node = (IJSONNode)indexedRegion; IStructuredDocumentRegion startRegion = node.getStartStructuredDocumentRegion(); IStructuredDocumentRegion endRegion = node.getEndStructuredDocumentRegion(); //if the node has an endRegion (end tag) then folding region is // between the start and end tag //else if the region is a comment //else if the region is only an open tag or an open/close tag then don't fold it if(startRegion != null && endRegion != null) { if (endRegion.getEndOffset() >= startRegion.getStartOffset()) retPos = new JSONObjectFoldingPosition(startRegion, endRegion); } // else if(startRegion != null && indexedRegion instanceof CommentImpl) { // retPos = new JSONCommentFoldingPosition(startRegion); // } } return retPos; } @Override protected boolean indexedRegionValidType(IndexedRegion indexedRegion) { return (indexedRegion instanceof IJSONObject || indexedRegion instanceof IJSONArray); } }
core/org.eclipse.wst.json.ui/src/org/eclipse/wst/json/ui/internal/projection/JSONFoldingStrategy.java
package org.eclipse.wst.json.ui.internal.projection; import org.eclipse.jface.text.Position; import org.eclipse.wst.json.core.document.IJSONNode; import org.eclipse.wst.json.core.document.IJSONObject; import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion; import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; import org.eclipse.wst.sse.ui.internal.projection.AbstractStructuredFoldingStrategy; /** * A folding strategy for JSON type structured documents. * See AbstractStructuredFoldingStrategy for more details. */ public class JSONFoldingStrategy extends AbstractStructuredFoldingStrategy { /** * Create an instance of the folding strategy. * Be sure to set the viewer and document after creation. */ public JSONFoldingStrategy() { super(); } /** * @see org.eclipse.wst.sse.ui.internal.projection.AbstractFoldingStrategy#calcNewFoldPosition(org.eclipse.wst.sse.core.internal.provisional.IndexedRegion) */ protected Position calcNewFoldPosition(IndexedRegion indexedRegion) { Position retPos = null; //only want to fold regions of the valid type and with a valid range if(indexedRegion.getStartOffset() >= 0 && indexedRegion.getLength() >= 0) { IJSONNode node = (IJSONNode)indexedRegion; IStructuredDocumentRegion startRegion = node.getStartStructuredDocumentRegion(); IStructuredDocumentRegion endRegion = node.getEndStructuredDocumentRegion(); //if the node has an endRegion (end tag) then folding region is // between the start and end tag //else if the region is a comment //else if the region is only an open tag or an open/close tag then don't fold it if(startRegion != null && endRegion != null) { if (endRegion.getEndOffset() >= startRegion.getStartOffset()) retPos = new JSONObjectFoldingPosition(startRegion, endRegion); } // else if(startRegion != null && indexedRegion instanceof CommentImpl) { // retPos = new JSONCommentFoldingPosition(startRegion); // } } return retPos; } @Override protected boolean indexedRegionValidType(IndexedRegion indexedRegion) { return (indexedRegion instanceof IJSONObject); } }
Fold array.
core/org.eclipse.wst.json.ui/src/org/eclipse/wst/json/ui/internal/projection/JSONFoldingStrategy.java
Fold array.
<ide><path>ore/org.eclipse.wst.json.ui/src/org/eclipse/wst/json/ui/internal/projection/JSONFoldingStrategy.java <ide> package org.eclipse.wst.json.ui.internal.projection; <ide> <ide> import org.eclipse.jface.text.Position; <add>import org.eclipse.wst.json.core.document.IJSONArray; <ide> import org.eclipse.wst.json.core.document.IJSONNode; <ide> import org.eclipse.wst.json.core.document.IJSONObject; <ide> import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion; <ide> <ide> @Override <ide> protected boolean indexedRegionValidType(IndexedRegion indexedRegion) { <del> return (indexedRegion instanceof IJSONObject); <add> return (indexedRegion instanceof IJSONObject || indexedRegion instanceof IJSONArray); <ide> } <ide> }
JavaScript
bsd-3-clause
3cc4f97f0449ed922868c8d7532df9d3cad14c30
0
martinbigio/react-native,dikaiosune/react-native,tgoldenberg/react-native,Purii/react-native,corbt/react-native,hayeah/react-native,satya164/react-native,nathanajah/react-native,DerayGa/react-native,Andreyco/react-native,frantic/react-native,browniefed/react-native,lprhodes/react-native,salanki/react-native,callstack-io/react-native,rickbeerendonk/react-native,pandiaraj44/react-native,DerayGa/react-native,eduardinni/react-native,cosmith/react-native,javache/react-native,DerayGa/react-native,imjerrybao/react-native,xiayz/react-native,exponentjs/react-native,iodine/react-native,shrutic123/react-native,pglotov/react-native,hammerandchisel/react-native,esauter5/react-native,brentvatne/react-native,alin23/react-native,hammerandchisel/react-native,Ehesp/react-native,myntra/react-native,corbt/react-native,shrutic/react-native,charlesvinette/react-native,ptmt/react-native-macos,shrutic123/react-native,happypancake/react-native,philikon/react-native,lprhodes/react-native,aaron-goshine/react-native,skatpgusskat/react-native,wenpkpk/react-native,iodine/react-native,imDangerous/react-native,vjeux/react-native,imDangerous/react-native,satya164/react-native,ndejesus1227/react-native,hoangpham95/react-native,facebook/react-native,machard/react-native,ndejesus1227/react-native,Tredsite/react-native,exponent/react-native,pandiaraj44/react-native,makadaw/react-native,luqin/react-native,Andreyco/react-native,facebook/react-native,miracle2k/react-native,foghina/react-native,nickhudkins/react-native,miracle2k/react-native,skatpgusskat/react-native,jevakallio/react-native,forcedotcom/react-native,ndejesus1227/react-native,wenpkpk/react-native,dikaiosune/react-native,urvashi01/react-native,jeffchienzabinet/react-native,mironiasty/react-native,farazs/react-native,forcedotcom/react-native,arbesfeld/react-native,imDangerous/react-native,csatf/react-native,philikon/react-native,DerayGa/react-native,rickbeerendonk/react-native,cdlewis/react-native,CntChen/react-native,xiayz/react-native,machard/react-native,exponentjs/react-native,adamjmcgrath/react-native,facebook/react-native,wenpkpk/react-native,browniefed/react-native,callstack-io/react-native,makadaw/react-native,Livyli/react-native,rickbeerendonk/react-native,InterfaceInc/react-native,jevakallio/react-native,farazs/react-native,luqin/react-native,tadeuzagallo/react-native,ptmt/react-native-macos,cdlewis/react-native,peterp/react-native,farazs/react-native,rebeccahughes/react-native,Purii/react-native,kesha-antonov/react-native,cdlewis/react-native,salanki/react-native,eduardinni/react-native,tadeuzagallo/react-native,myntra/react-native,christopherdro/react-native,eduardinni/react-native,jevakallio/react-native,negativetwelve/react-native,tgoldenberg/react-native,naoufal/react-native,catalinmiron/react-native,jadbox/react-native,lelandrichardson/react-native,jhen0409/react-native,chnfeeeeeef/react-native,thotegowda/react-native,ultralame/react-native,cosmith/react-native,ptmt/react-native-macos,tgoldenberg/react-native,skevy/react-native,Maxwell2022/react-native,orenklein/react-native,lprhodes/react-native,janicduplessis/react-native,PlexChat/react-native,cpunion/react-native,jaggs6/react-native,tadeuzagallo/react-native,frantic/react-native,cosmith/react-native,clozr/react-native,facebook/react-native,BretJohnson/react-native,arbesfeld/react-native,tarkus/react-native-appletv,aljs/react-native,salanki/react-native,catalinmiron/react-native,corbt/react-native,CodeLinkIO/react-native,CodeLinkIO/react-native,pglotov/react-native,gre/react-native,mironiasty/react-native,wenpkpk/react-native,martinbigio/react-native,CodeLinkIO/react-native,tgoldenberg/react-native,doochik/react-native,jeffchienzabinet/react-native,Livyli/react-native,dikaiosune/react-native,formatlos/react-native,arthuralee/react-native,DanielMSchmidt/react-native,negativetwelve/react-native,Tredsite/react-native,cosmith/react-native,eduardinni/react-native,adamjmcgrath/react-native,cosmith/react-native,tarkus/react-native-appletv,DerayGa/react-native,miracle2k/react-native,javache/react-native,gilesvangruisen/react-native,happypancake/react-native,jasonnoahchoi/react-native,rickbeerendonk/react-native,lelandrichardson/react-native,csatf/react-native,cdlewis/react-native,wenpkpk/react-native,mrspeaker/react-native,DerayGa/react-native,CodeLinkIO/react-native,ankitsinghania94/react-native,facebook/react-native,hoangpham95/react-native,jaggs6/react-native,formatlos/react-native,urvashi01/react-native,browniefed/react-native,peterp/react-native,chnfeeeeeef/react-native,skatpgusskat/react-native,Ehesp/react-native,dikaiosune/react-native,makadaw/react-native,hammerandchisel/react-native,wenpkpk/react-native,luqin/react-native,nickhudkins/react-native,jeffchienzabinet/react-native,rebeccahughes/react-native,jaggs6/react-native,gitim/react-native,cpunion/react-native,DanielMSchmidt/react-native,imDangerous/react-native,ptomasroos/react-native,DannyvanderJagt/react-native,xiayz/react-native,Livyli/react-native,jasonnoahchoi/react-native,ptomasroos/react-native,martinbigio/react-native,Purii/react-native,hoastoolshop/react-native,philikon/react-native,cdlewis/react-native,jeffchienzabinet/react-native,Andreyco/react-native,cpunion/react-native,InterfaceInc/react-native,naoufal/react-native,kesha-antonov/react-native,wesley1001/react-native,lelandrichardson/react-native,formatlos/react-native,Swaagie/react-native,wesley1001/react-native,makadaw/react-native,corbt/react-native,callstack-io/react-native,hammerandchisel/react-native,Ehesp/react-native,tadeuzagallo/react-native,forcedotcom/react-native,xiayz/react-native,hoastoolshop/react-native,pglotov/react-native,DerayGa/react-native,farazs/react-native,corbt/react-native,tsjing/react-native,charlesvinette/react-native,jevakallio/react-native,DanielMSchmidt/react-native,cpunion/react-native,jasonnoahchoi/react-native,jhen0409/react-native,luqin/react-native,gitim/react-native,tarkus/react-native-appletv,orenklein/react-native,luqin/react-native,ptmt/react-native-macos,chnfeeeeeef/react-native,pglotov/react-native,CodeLinkIO/react-native,pglotov/react-native,jeffchienzabinet/react-native,mironiasty/react-native,thotegowda/react-native,jadbox/react-native,machard/react-native,mironiasty/react-native,rickbeerendonk/react-native,arthuralee/react-native,mironiasty/react-native,rickbeerendonk/react-native,satya164/react-native,aljs/react-native,salanki/react-native,ultralame/react-native,cpunion/react-native,CntChen/react-native,jevakallio/react-native,Guardiannw/react-native,jhen0409/react-native,dikaiosune/react-native,DanielMSchmidt/react-native,catalinmiron/react-native,jhen0409/react-native,javache/react-native,shrutic123/react-native,callstack-io/react-native,philikon/react-native,adamjmcgrath/react-native,Purii/react-native,Emilios1995/react-native,adamjmcgrath/react-native,miracle2k/react-native,makadaw/react-native,DanielMSchmidt/react-native,nathanajah/react-native,gilesvangruisen/react-native,htc2u/react-native,urvashi01/react-native,makadaw/react-native,htc2u/react-native,skatpgusskat/react-native,myntra/react-native,doochik/react-native,ultralame/react-native,xiayz/react-native,gre/react-native,gre/react-native,skevy/react-native,jeffchienzabinet/react-native,BretJohnson/react-native,aljs/react-native,csatf/react-native,hoastoolshop/react-native,pandiaraj44/react-native,Bhullnatik/react-native,ndejesus1227/react-native,browniefed/react-native,ndejesus1227/react-native,ndejesus1227/react-native,shrutic/react-native,tszajna0/react-native,forcedotcom/react-native,hayeah/react-native,InterfaceInc/react-native,DanielMSchmidt/react-native,corbt/react-native,martinbigio/react-native,esauter5/react-native,orenklein/react-native,forcedotcom/react-native,shrutic/react-native,chnfeeeeeef/react-native,philikon/react-native,mrspeaker/react-native,gilesvangruisen/react-native,forcedotcom/react-native,DanielMSchmidt/react-native,Andreyco/react-native,javache/react-native,cosmith/react-native,frantic/react-native,CntChen/react-native,hammerandchisel/react-native,Maxwell2022/react-native,shrutic123/react-native,imjerrybao/react-native,tadeuzagallo/react-native,luqin/react-native,pglotov/react-native,mrspeaker/react-native,eduardinni/react-native,ultralame/react-native,arbesfeld/react-native,esauter5/react-native,happypancake/react-native,Ehesp/react-native,jevakallio/react-native,salanki/react-native,lelandrichardson/react-native,lprhodes/react-native,negativetwelve/react-native,thotegowda/react-native,orenklein/react-native,brentvatne/react-native,cdlewis/react-native,nathanajah/react-native,arthuralee/react-native,Andreyco/react-native,skevy/react-native,Bhullnatik/react-native,janicduplessis/react-native,hoastoolshop/react-native,exponentjs/react-native,doochik/react-native,aaron-goshine/react-native,kesha-antonov/react-native,cpunion/react-native,thotegowda/react-native,DannyvanderJagt/react-native,lprhodes/react-native,eduardinni/react-native,InterfaceInc/react-native,ptomasroos/react-native,Ehesp/react-native,tszajna0/react-native,brentvatne/react-native,Guardiannw/react-native,tarkus/react-native-appletv,Bhullnatik/react-native,dubert/react-native,jeffchienzabinet/react-native,doochik/react-native,lprhodes/react-native,esauter5/react-native,imDangerous/react-native,formatlos/react-native,xiayz/react-native,exponentjs/react-native,myntra/react-native,facebook/react-native,miracle2k/react-native,urvashi01/react-native,BretJohnson/react-native,iodine/react-native,Guardiannw/react-native,Tredsite/react-native,Guardiannw/react-native,exponent/react-native,thotegowda/react-native,pglotov/react-native,imDangerous/react-native,BretJohnson/react-native,exponent/react-native,hoangpham95/react-native,alin23/react-native,hoangpham95/react-native,iodine/react-native,alin23/react-native,ptomasroos/react-native,Purii/react-native,farazs/react-native,doochik/react-native,aaron-goshine/react-native,jhen0409/react-native,Guardiannw/react-native,chnfeeeeeef/react-native,urvashi01/react-native,machard/react-native,Tredsite/react-native,PlexChat/react-native,imjerrybao/react-native,charlesvinette/react-native,brentvatne/react-native,aaron-goshine/react-native,CodeLinkIO/react-native,ptomasroos/react-native,exponent/react-native,tgoldenberg/react-native,farazs/react-native,negativetwelve/react-native,charlesvinette/react-native,iodine/react-native,negativetwelve/react-native,christopherdro/react-native,formatlos/react-native,esauter5/react-native,clozr/react-native,brentvatne/react-native,hayeah/react-native,ptmt/react-native-macos,mrspeaker/react-native,jevakallio/react-native,CntChen/react-native,tsjing/react-native,exponent/react-native,Swaagie/react-native,Swaagie/react-native,InterfaceInc/react-native,naoufal/react-native,alin23/react-native,jadbox/react-native,myntra/react-native,martinbigio/react-native,aaron-goshine/react-native,peterp/react-native,dubert/react-native,rickbeerendonk/react-native,miracle2k/react-native,shrutic/react-native,Tredsite/react-native,makadaw/react-native,nickhudkins/react-native,gitim/react-native,tadeuzagallo/react-native,nathanajah/react-native,hammerandchisel/react-native,skatpgusskat/react-native,DannyvanderJagt/react-native,dubert/react-native,rebeccahughes/react-native,Emilios1995/react-native,esauter5/react-native,exponentjs/react-native,jevakallio/react-native,browniefed/react-native,doochik/react-native,arbesfeld/react-native,tsjing/react-native,lelandrichardson/react-native,htc2u/react-native,hoastoolshop/react-native,clozr/react-native,shrutic123/react-native,esauter5/react-native,urvashi01/react-native,charlesvinette/react-native,martinbigio/react-native,facebook/react-native,pandiaraj44/react-native,xiayz/react-native,dubert/react-native,happypancake/react-native,adamjmcgrath/react-native,jevakallio/react-native,forcedotcom/react-native,gitim/react-native,Swaagie/react-native,alin23/react-native,shrutic123/react-native,tsjing/react-native,dikaiosune/react-native,compulim/react-native,gilesvangruisen/react-native,nickhudkins/react-native,kesha-antonov/react-native,peterp/react-native,janicduplessis/react-native,cdlewis/react-native,philikon/react-native,satya164/react-native,clozr/react-native,Purii/react-native,exponentjs/react-native,jadbox/react-native,htc2u/react-native,gre/react-native,ptomasroos/react-native,clozr/react-native,orenklein/react-native,tgoldenberg/react-native,DannyvanderJagt/react-native,chnfeeeeeef/react-native,Swaagie/react-native,Livyli/react-native,jaggs6/react-native,Bhullnatik/react-native,rebeccahughes/react-native,Purii/react-native,lelandrichardson/react-native,kesha-antonov/react-native,satya164/react-native,DannyvanderJagt/react-native,CodeLinkIO/react-native,wesley1001/react-native,martinbigio/react-native,tszajna0/react-native,dikaiosune/react-native,callstack-io/react-native,cpunion/react-native,ptomasroos/react-native,aaron-goshine/react-native,compulim/react-native,DannyvanderJagt/react-native,Livyli/react-native,BretJohnson/react-native,browniefed/react-native,Maxwell2022/react-native,nathanajah/react-native,skatpgusskat/react-native,tsjing/react-native,Maxwell2022/react-native,naoufal/react-native,pandiaraj44/react-native,aaron-goshine/react-native,naoufal/react-native,tgoldenberg/react-native,ptomasroos/react-native,aljs/react-native,Livyli/react-native,Bhullnatik/react-native,ptmt/react-native-macos,exponent/react-native,jaggs6/react-native,formatlos/react-native,javache/react-native,compulim/react-native,shrutic/react-native,BretJohnson/react-native,ankitsinghania94/react-native,CntChen/react-native,ptmt/react-native-macos,Ehesp/react-native,skevy/react-native,vjeux/react-native,thotegowda/react-native,skatpgusskat/react-native,Emilios1995/react-native,jhen0409/react-native,PlexChat/react-native,tgoldenberg/react-native,hoastoolshop/react-native,skevy/react-native,orenklein/react-native,htc2u/react-native,shrutic123/react-native,Emilios1995/react-native,skevy/react-native,myntra/react-native,gilesvangruisen/react-native,dikaiosune/react-native,brentvatne/react-native,eduardinni/react-native,ptmt/react-native-macos,jadbox/react-native,myntra/react-native,dubert/react-native,DanielMSchmidt/react-native,vjeux/react-native,hayeah/react-native,jasonnoahchoi/react-native,thotegowda/react-native,dubert/react-native,pandiaraj44/react-native,Andreyco/react-native,foghina/react-native,Purii/react-native,forcedotcom/react-native,tsjing/react-native,dubert/react-native,kesha-antonov/react-native,catalinmiron/react-native,hoangpham95/react-native,happypancake/react-native,pandiaraj44/react-native,lelandrichardson/react-native,tszajna0/react-native,gre/react-native,PlexChat/react-native,exponentjs/react-native,javache/react-native,javache/react-native,rickbeerendonk/react-native,Tredsite/react-native,facebook/react-native,tsjing/react-native,philikon/react-native,arthuralee/react-native,Guardiannw/react-native,negativetwelve/react-native,mironiasty/react-native,foghina/react-native,makadaw/react-native,catalinmiron/react-native,nickhudkins/react-native,peterp/react-native,adamjmcgrath/react-native,salanki/react-native,csatf/react-native,ankitsinghania94/react-native,Bhullnatik/react-native,lprhodes/react-native,shrutic/react-native,ndejesus1227/react-native,Emilios1995/react-native,ndejesus1227/react-native,vjeux/react-native,jasonnoahchoi/react-native,Emilios1995/react-native,ultralame/react-native,htc2u/react-native,gre/react-native,satya164/react-native,tsjing/react-native,InterfaceInc/react-native,tszajna0/react-native,farazs/react-native,aljs/react-native,javache/react-native,makadaw/react-native,janicduplessis/react-native,InterfaceInc/react-native,hoangpham95/react-native,miracle2k/react-native,nickhudkins/react-native,Ehesp/react-native,machard/react-native,arbesfeld/react-native,christopherdro/react-native,eduardinni/react-native,machard/react-native,naoufal/react-native,gre/react-native,hayeah/react-native,imDangerous/react-native,browniefed/react-native,formatlos/react-native,CntChen/react-native,jadbox/react-native,iodine/react-native,catalinmiron/react-native,DannyvanderJagt/react-native,nathanajah/react-native,gre/react-native,philikon/react-native,ankitsinghania94/react-native,DerayGa/react-native,Emilios1995/react-native,christopherdro/react-native,callstack-io/react-native,jadbox/react-native,nickhudkins/react-native,brentvatne/react-native,Tredsite/react-native,Swaagie/react-native,alin23/react-native,CodeLinkIO/react-native,wesley1001/react-native,lelandrichardson/react-native,hoastoolshop/react-native,xiayz/react-native,htc2u/react-native,gilesvangruisen/react-native,Maxwell2022/react-native,foghina/react-native,Swaagie/react-native,mironiasty/react-native,gitim/react-native,jaggs6/react-native,callstack-io/react-native,csatf/react-native,shrutic/react-native,csatf/react-native,ankitsinghania94/react-native,tarkus/react-native-appletv,tszajna0/react-native,facebook/react-native,frantic/react-native,christopherdro/react-native,PlexChat/react-native,wesley1001/react-native,aljs/react-native,imjerrybao/react-native,BretJohnson/react-native,urvashi01/react-native,mironiasty/react-native,aaron-goshine/react-native,arthuralee/react-native,adamjmcgrath/react-native,clozr/react-native,shrutic123/react-native,christopherdro/react-native,jadbox/react-native,htc2u/react-native,thotegowda/react-native,callstack-io/react-native,Maxwell2022/react-native,urvashi01/react-native,mrspeaker/react-native,tarkus/react-native-appletv,Andreyco/react-native,PlexChat/react-native,imjerrybao/react-native,imjerrybao/react-native,corbt/react-native,frantic/react-native,imDangerous/react-native,exponent/react-native,nathanajah/react-native,tarkus/react-native-appletv,charlesvinette/react-native,csatf/react-native,jasonnoahchoi/react-native,tadeuzagallo/react-native,gitim/react-native,Bhullnatik/react-native,foghina/react-native,miracle2k/react-native,salanki/react-native,satya164/react-native,hoastoolshop/react-native,christopherdro/react-native,farazs/react-native,catalinmiron/react-native,PlexChat/react-native,Swaagie/react-native,adamjmcgrath/react-native,tadeuzagallo/react-native,gilesvangruisen/react-native,salanki/react-native,orenklein/react-native,imjerrybao/react-native,chnfeeeeeef/react-native,foghina/react-native,peterp/react-native,iodine/react-native,Bhullnatik/react-native,cosmith/react-native,naoufal/react-native,Livyli/react-native,luqin/react-native,doochik/react-native,jasonnoahchoi/react-native,pglotov/react-native,cdlewis/react-native,myntra/react-native,rickbeerendonk/react-native,cosmith/react-native,mrspeaker/react-native,charlesvinette/react-native,martinbigio/react-native,wenpkpk/react-native,aljs/react-native,corbt/react-native,Andreyco/react-native,browniefed/react-native,dubert/react-native,ankitsinghania94/react-native,csatf/react-native,janicduplessis/react-native,kesha-antonov/react-native,negativetwelve/react-native,exponent/react-native,peterp/react-native,alin23/react-native,luqin/react-native,christopherdro/react-native,Maxwell2022/react-native,wenpkpk/react-native,janicduplessis/react-native,cpunion/react-native,nickhudkins/react-native,hoangpham95/react-native,farazs/react-native,aljs/react-native,javache/react-native,hammerandchisel/react-native,happypancake/react-native,machard/react-native,compulim/react-native,DannyvanderJagt/react-native,negativetwelve/react-native,rebeccahughes/react-native,tszajna0/react-native,vjeux/react-native,doochik/react-native,iodine/react-native,foghina/react-native,happypancake/react-native,mrspeaker/react-native,imjerrybao/react-native,nathanajah/react-native,janicduplessis/react-native,Ehesp/react-native,kesha-antonov/react-native,InterfaceInc/react-native,hoangpham95/react-native,orenklein/react-native,tszajna0/react-native,Maxwell2022/react-native,jeffchienzabinet/react-native,wesley1001/react-native,catalinmiron/react-native,Emilios1995/react-native,formatlos/react-native,naoufal/react-native,tarkus/react-native-appletv,machard/react-native,jaggs6/react-native,Guardiannw/react-native,peterp/react-native,doochik/react-native,Tredsite/react-native,arbesfeld/react-native,BretJohnson/react-native,arbesfeld/react-native,skevy/react-native,arbesfeld/react-native,janicduplessis/react-native,lprhodes/react-native,kesha-antonov/react-native,foghina/react-native,CntChen/react-native,jasonnoahchoi/react-native,ankitsinghania94/react-native,skatpgusskat/react-native,cdlewis/react-native,compulim/react-native,wesley1001/react-native,formatlos/react-native,shrutic/react-native,exponentjs/react-native,satya164/react-native,hammerandchisel/react-native,happypancake/react-native,Guardiannw/react-native,skevy/react-native,mironiasty/react-native,esauter5/react-native,pandiaraj44/react-native,ankitsinghania94/react-native,PlexChat/react-native,negativetwelve/react-native,mrspeaker/react-native,wesley1001/react-native,chnfeeeeeef/react-native,CntChen/react-native,myntra/react-native,clozr/react-native,Livyli/react-native,gitim/react-native,charlesvinette/react-native,clozr/react-native,alin23/react-native,jhen0409/react-native,jaggs6/react-native,brentvatne/react-native,jhen0409/react-native,brentvatne/react-native,gitim/react-native,gilesvangruisen/react-native
/** * The examples provided by Facebook are for non-commercial testing and * evaluation purposes only. * * Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @flow */ 'use strict'; const React = require('react-native'); const StyleSheet = require('StyleSheet'); const UIExplorerBlock = require('UIExplorerBlock'); const UIExplorerPage = require('UIExplorerPage'); const { Picker, Text, TouchableWithoutFeedback, } = React; const Item = Picker.Item; const PickerExample = React.createClass({ statics: { title: '<Picker>', description: 'Provides multiple options to choose from, using either a dropdown menu or a dialog.', }, getInitialState: function() { return { selected1: 'key1', selected2: 'key1', selected3: 'key1', color: 'red', mode: Picker.MODE_DIALOG, }; }, render: function() { return ( <UIExplorerPage title="<Picker>"> <UIExplorerBlock title="Basic Picker"> <Picker style={styles.picker} selectedValue={this.state.selected1} onValueChange={this.onValueChange.bind(this, 'selected1')}> <Item label="hello" value="key0" /> <Item label="world" value="key1" /> </Picker> </UIExplorerBlock> <UIExplorerBlock title="Disabled picker"> <Picker style={styles.picker} enabled={false} selectedValue={this.state.selected1}> <Item label="hello" value="key0" /> <Item label="world" value="key1" /> </Picker> </UIExplorerBlock> <UIExplorerBlock title="Dropdown Picker"> <Picker style={styles.picker} selectedValue={this.state.selected2} onValueChange={this.onValueChange.bind(this, 'selected2')} mode="dropdown"> <Item label="hello" value="key0" /> <Item label="world" value="key1" /> </Picker> </UIExplorerBlock> <UIExplorerBlock title="Picker with prompt message"> <Picker style={styles.picker} selectedValue={this.state.selected3} onValueChange={this.onValueChange.bind(this, 'selected3')} prompt="Pick one, just one"> <Item label="hello" value="key0" /> <Item label="world" value="key1" /> </Picker> </UIExplorerBlock> <UIExplorerBlock title="Picker with no listener"> <Picker style={styles.picker}> <Item label="hello" value="key0" /> <Item label="world" value="key1" /> </Picker> <Text> Cannot change the value of this picker because it doesn't update selectedValue. </Text> </UIExplorerBlock> <UIExplorerBlock title="Colorful pickers"> <Picker style={[styles.picker, {color: 'white', backgroundColor: '#333'}]} selectedValue={this.state.color} onValueChange={this.onValueChange.bind(this, 'color')} mode="dropdown"> <Item label="red" color="red" value="red" /> <Item label="green" color="green" value="green" /> <Item label="blue" color="blue" value="blue" /> </Picker> <Picker style={styles.picker} selectedValue={this.state.color} onValueChange={this.onValueChange.bind(this, 'color')} mode="dialog"> <Item label="red" color="red" value="red" /> <Item label="green" color="green" value="green" /> <Item label="blue" color="blue" value="blue" /> </Picker> </UIExplorerBlock> </UIExplorerPage> ); }, changeMode: function() { const newMode = this.state.mode === Picker.MODE_DIALOG ? Picker.MODE_DROPDOWN : Picker.MODE_DIALOG; this.setState({mode: newMode}); }, onValueChange: function(key: string, value: string) { const newState = {}; newState[key] = value; this.setState(newState); }, }); var styles = StyleSheet.create({ picker: { width: 100, }, }); module.exports = PickerExample;
Examples/UIExplorer/PickerAndroidExample.js
/** * The examples provided by Facebook are for non-commercial testing and * evaluation purposes only. * * Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @flow */ 'use strict'; const React = require('react-native'); const StyleSheet = require('StyleSheet'); const UIExplorerBlock = require('UIExplorerBlock'); const UIExplorerPage = require('UIExplorerPage'); const { Picker, Text, TouchableWithoutFeedback, } = React; const Item = Picker.Item; const PickerExample = React.createClass({ statics: { title: '<Picker>', description: 'Provides multiple options to choose from, using either a dropdown menu or a dialog.', }, getInitialState: function() { return { selected1: 'key1', selected2: 'key1', selected3: 'key1', color: 'red', mode: Picker.MODE_DIALOG, }; }, displayName: 'Android Picker', render: function() { return ( <UIExplorerPage title="<Picker>"> <UIExplorerBlock title="Basic Picker"> <Picker style={styles.picker} selectedValue={this.state.selected1} onValueChange={this.onValueChange.bind(this, 'selected1')}> <Item label="hello" value="key0" /> <Item label="world" value="key1" /> </Picker> </UIExplorerBlock> <UIExplorerBlock title="Disabled picker"> <Picker style={styles.picker} enabled={false} selectedValue={this.state.selected1}> <Item label="hello" value="key0" /> <Item label="world" value="key1" /> </Picker> </UIExplorerBlock> <UIExplorerBlock title="Dropdown Picker"> <Picker style={styles.picker} selectedValue={this.state.selected2} onValueChange={this.onValueChange.bind(this, 'selected2')} mode="dropdown"> <Item label="hello" value="key0" /> <Item label="world" value="key1" /> </Picker> </UIExplorerBlock> <UIExplorerBlock title="Picker with prompt message"> <Picker style={styles.picker} selectedValue={this.state.selected3} onValueChange={this.onValueChange.bind(this, 'selected3')} prompt="Pick one, just one"> <Item label="hello" value="key0" /> <Item label="world" value="key1" /> </Picker> </UIExplorerBlock> <UIExplorerBlock title="Picker with no listener"> <Picker style={styles.picker}> <Item label="hello" value="key0" /> <Item label="world" value="key1" /> </Picker> <Text> Cannot change the value of this picker because it doesn't update selectedValue. </Text> </UIExplorerBlock> <UIExplorerBlock title="Colorful pickers"> <Picker style={[styles.picker, {color: 'white', backgroundColor: '#333'}]} selectedValue={this.state.color} onValueChange={this.onValueChange.bind(this, 'color')} mode="dropdown"> <Item label="red" color="red" value="red" /> <Item label="green" color="green" value="green" /> <Item label="blue" color="blue" value="blue" /> </Picker> <Picker style={styles.picker} selectedValue={this.state.color} onValueChange={this.onValueChange.bind(this, 'color')} mode="dialog"> <Item label="red" color="red" value="red" /> <Item label="green" color="green" value="green" /> <Item label="blue" color="blue" value="blue" /> </Picker> </UIExplorerBlock> </UIExplorerPage> ); }, changeMode: function() { const newMode = this.state.mode === Picker.MODE_DIALOG ? Picker.MODE_DROPDOWN : Picker.MODE_DIALOG; this.setState({mode: newMode}); }, onValueChange: function(key: string, value: string) { const newState = {}; newState[key] = value; this.setState(newState); }, }); var styles = StyleSheet.create({ picker: { width: 100, }, }); module.exports = PickerExample;
Remove 'displayName' prop from 'PickerExample' component Summary:The value of the displayName was wrong (had space in it). Also the babel plugin for display name already adds display names. So we shouldn't need to do it manually. As a side effect, it breaks the UIExplorer app when HMR is enabled (that's how I found it). Closes https://github.com/facebook/react-native/pull/6193 Differential Revision: D2987160 fb-gh-sync-id: fd64112c26741fab1385454a0ce978ec1eaf2415 shipit-source-id: fd64112c26741fab1385454a0ce978ec1eaf2415
Examples/UIExplorer/PickerAndroidExample.js
Remove 'displayName' prop from 'PickerExample' component
<ide><path>xamples/UIExplorer/PickerAndroidExample.js <ide> mode: Picker.MODE_DIALOG, <ide> }; <ide> }, <del> <del> displayName: 'Android Picker', <ide> <ide> render: function() { <ide> return (
Java
agpl-3.0
4926b1219bece02c1adfd8d1ccef67c91882a196
0
printedheart/opennars,printedheart/opennars,printedheart/opennars,printedheart/opennars,printedheart/opennars,printedheart/opennars
/* * Here comes the text of your license * Each line should be prefixed with * */ package nars.logic; import nars.core.*; import nars.logic.entity.*; import reactor.event.Event; import reactor.function.Supplier; import java.util.ArrayDeque; import java.util.Deque; import java.util.List; /** * NAL Reasoner Process. Includes all reasoning process state and common utility methods that utilize it. * <p> * https://code.google.com/p/open-nars/wiki/SingleStepTestingCases * according to derived Task: if it contains a mental operator it is NAL9, if it contains a operation it is NAL8, if it contains temporal information it is NAL7, if it contains in/dependent vars it is NAL6, if it contains higher order copulas like &&, ==> or negation it is NAL5 * <p> * if it contains product or image it is NAL4, if it contains sets or set operations like &, -, | it is NAL3 * <p> * if it contains similarity or instances or properties it is NAL2 * and if it only contains inheritance */ public abstract class NAL extends Event implements Runnable, Supplier<Task> { public interface DerivationFilter extends Plugin { /** * returns null if allowed to derive, or a String containing a short rejection reason for logging */ public String reject(NAL nal, Task task, boolean revised, boolean single, Task parent, Sentence otherBelief, Sentence derivedCurrentBelief, Task derivedCurrentTask); @Override public default boolean setEnabled(NAR n, boolean enabled) { return true; } } public final Memory memory; protected final Task currentTask; protected Sentence currentBelief; protected final NALRuleEngine reasoner; /** * stores the tasks that this process generates, and adds to memory */ Deque<Task> newTasks = null; //lazily instantiated //TODO tasksDicarded public NAL(Memory mem, Task task) { this(mem, -1, task); } /** @param nalLevel the NAL level to limit processing of this reasoning context. set to -1 to use Memory's default value */ public NAL(Memory mem, int nalLevel, Task task) { super(null); //setKey(getClass()); setData(this); memory = mem; reasoner = memory.rules; if ((nalLevel!=-1) && (nalLevel!=mem.nal())) throw new RuntimeException("Different NAL level than Memory not supported yet"); currentTask = task; currentBelief = null; } @Override public void run() { onStart(); reason(); onFinished(); } protected void onStart() { /** implement if necessary in subclasses */ } protected void onFinished() { /** implement if necessary in subclasses */ } protected abstract void reason(); protected int newTasksCount() { if (newTasks == null) return 0; return newTasks.size(); } public void emit(final Class c, final Object... o) { memory.emit(c, o); } public int nal() { return memory.nal(); } /** * whether at least NAL level N is enabled */ public boolean nal(int n) { return nal() >= n; } public boolean deriveTask(final Task task, final boolean revised, final boolean single, Task parent, Sentence occurence2) { return deriveTask(task, revised, single, parent, occurence2, getCurrentBelief(), getCurrentTask()); } /** * iived task comes from the logic rules. * * @param task the derived task */ public boolean deriveTask(final Task task, final boolean revised, final boolean single, Task parent, Sentence occurence2, Sentence derivedCurrentBelief, Task derivedCurrentTask) { List<DerivationFilter> derivationFilters = reasoner.getDerivationFilters(); if (derivationFilters != null) { for (int i = 0; i < derivationFilters.size(); i++) { DerivationFilter d = derivationFilters.get(i); String rejectionReason = d.reject(this, task, revised, single, parent, occurence2, derivedCurrentBelief, derivedCurrentTask); if (rejectionReason != null) { memory.removeTask(task, rejectionReason); return false; } } } if (task.sentence.getOccurenceTime() > memory.time()) { memory.event.emit(Events.TaskDeriveFuture.class, task, this); } if (task.sentence.stamp.latency > 0) { memory.logic.DERIVATION_LATENCY.set((double) task.sentence.stamp.latency); } task.setParticipateInTemporalInduction(false); final Sentence occurence = parent != null ? parent.sentence : null; memory.event.emit(Events.TaskDerive.class, task, revised, single, occurence, occurence2, derivedCurrentTask); memory.logic.TASK_DERIVED.hit(); addNewTask(task, "Derived"); return true; } /* --------------- new task building --------------- */ /** * Shared final operations by all double-premise rules, called from the * rules except StructuralRules * * @param newTaskContent The content of the sentence in task * @param newTruth The truth value of the sentence in task * @param newBudget The budget value in task */ public boolean doublePremiseTask(CompoundTerm newTaskContent, final TruthValue newTruth, final BudgetValue newBudget, StampBuilder newStamp, boolean temporalAdd) { return doublePremiseTask(newTaskContent, newTruth, newBudget, newStamp, temporalAdd, getCurrentBelief(), getCurrentTask()); } public boolean doublePremiseTask(CompoundTerm newTaskContent, final TruthValue newTruth, final BudgetValue newBudget, StampBuilder stamp, final boolean temporalAdd, Sentence subbedBelief, Task subbedTask) { if (!newBudget.aboveThreshold()) { return false; } newTaskContent = Sentence.termOrNull(newTaskContent); if (newTaskContent == null) return false; final Stamp newStamp = stamp.build(); boolean derived = deriveTask(new Task( new Sentence(newTaskContent, subbedTask.sentence.punctuation, newTruth, newStamp), newBudget, subbedTask, subbedBelief), false, false, subbedTask, subbedBelief); //"Since in principle it is always valid to eternalize a tensed belief" if (temporalAdd && nal(7) && Parameters.IMMEDIATE_ETERNALIZATION) { //temporal induction generated ones get eternalized directly derived |= deriveTask( new Task( new Sentence(newTaskContent, subbedTask.sentence.punctuation, TruthFunctions.eternalize(newTruth), newStamp.cloneEternal()), newBudget, subbedTask, subbedBelief), false, false, null, null); } return derived; } /** * Shared final operations by all double-premise rules, called from the * rules except StructuralRules * * @param newContent The content of the sentence in task * @param newTruth The truth value of the sentence in task * @param newBudget The budget value in task * @param revisible Whether the sentence is revisible */ // public void doublePremiseTask(Term newContent, TruthValue newTruth, BudgetValue newBudget, boolean revisible) { // if (newContent != null) { // Sentence taskSentence = currentTask.getSentence(); // Sentence newSentence = new Sentence(newContent, taskSentence.getPunctuation(), newTruth, newStamp, revisible); // Task newTaskAt = new Task(newSentence, newBudget, currentTask, currentBelief); // derivedTask(newTaskAt, false, false); // } // } /** * Shared final operations by all single-premise rules, called in * StructuralRules * * @param newContent The content of the sentence in task * @param newTruth The truth value of the sentence in task * @param newBudget The budget value in task */ public boolean singlePremiseTask(CompoundTerm newContent, TruthValue newTruth, BudgetValue newBudget) { return singlePremiseTask(newContent, getCurrentTask().sentence.punctuation, newTruth, newBudget); } /** * Shared final operations by all single-premise rules, called in * StructuralRules * * @param newContent The content of the sentence in task * @param punctuation The punctuation of the sentence in task * @param newTruth The truth value of the sentence in task * @param newBudget The budget value in task */ public boolean singlePremiseTask(final CompoundTerm newContent, final char punctuation, final TruthValue newTruth, final BudgetValue newBudget) { if (!newBudget.aboveThreshold()) return false; Task parentTask = getCurrentTask().getParentTask(); if (parentTask != null) { if (parentTask.getTerm() == null) { return false; } if (newContent == null) { return false; } if (newContent.equals(parentTask.getTerm())) { return false; } } Sentence taskSentence = getCurrentTask().sentence; final Stamp stamp; if (taskSentence.isJudgment() || getCurrentBelief() == null) { stamp = new Stamp(taskSentence.stamp, time()); } else { // to answer a question with negation in NAL-5 --- move to activated task? stamp = new Stamp(getCurrentBelief().stamp, time()); } if (newContent.subjectOrPredicateIsIndependentVar()) { return false; } return deriveTask(new Task(new Sentence(newContent, punctuation, newTruth, stamp), newBudget, getCurrentTask(), null), false, true, null, null); } public boolean singlePremiseTask(Sentence newSentence, BudgetValue newBudget) { /*if (!newBudget.aboveThreshold()) { return false; }*/ Task newTask = new Task(newSentence, newBudget, getCurrentTask()); return deriveTask(newTask, false, true, null, null); } public long time() { return memory.time(); } /** * @return the currentTask */ public Task getCurrentTask() { return currentTask; } // // /** // * @return the newStamp // */ // public Stamp getTheNewStamp() { // if (newStamp == null) { // //if newStamp==null then newStampBuilder must be available. cache it's return value as newStamp // newStamp = newStampBuilder.build(); // newStampBuilder = null; // } // return newStamp; // } // public Stamp getTheNewStampForRevision() { // if (newStamp == null) { // if (newStampBuilder.overlapping()) { // newStamp = null; // } // else { // newStamp = newStampBuilder.build(); // } // newStampBuilder = null; // } // return newStamp; // } // // /** // * @param newStamp the newStamp to set // */ // public Stamp setNextNewStamp(Stamp newStamp) { // this.newStamp = newStamp; // this.newStampBuilder = null; // return newStamp; // } // // /** // * creates a lazy/deferred StampBuilder which only constructs the stamp if getTheNewStamp() is actually invoked // */ // public void setNextNewStamp(final Stamp first, final Stamp second, final long time) { // newStamp = null; // newStampBuilder = new NewStampBuilder(first, second, time); // } // interface StampBuilder { // // public Stamp build(); // // default public Stamp getFirst() { return null; } // default public Stamp getSecond(){ return null; } // // default public boolean overlapping() { // /*final int stampLength = stamp.baseLength; // for (int i = 0; i < stampLength; i++) { // final long baseI = stamp.evidentialBase[i]; // for (int j = 0; j < stampLength; j++) { // if ((i != j) && (baseI == stamp.evidentialBase[j])) { // throw new RuntimeException("Overlapping Revision Evidence: Should have been discovered earlier: " + Arrays.toString(stamp.evidentialBase)); // } // } // }*/ // // long[] a = getFirst().toSet(); // long[] b = getSecond().toSet(); // for (long ae : a) { // for (long be : b) { // if (ae == be) return true; // } // } // return false; // } // } /** * @return the currentBelief */ public Sentence getCurrentBelief() { return currentBelief; } /** * tasks added with this method will be buffered by this NAL instance; * at the end of the processing they can be reviewed and filtered * then they need to be added to memory with inputTask(t) */ protected void addNewTask(Task t, String reason) { t.setReason(reason); if (newTasks==null) newTasks = new ArrayDeque(4); newTasks.add(t); } /** called from consumers of the tasks that this context generates */ @Override public Task get() { if (newTasks == null || newTasks.isEmpty()) return null; return newTasks.removeFirst(); } /** * Activated task called in MatchingRules.trySolution and * Concept.processGoal * * @param budget The budget value of the new Task * @param sentence The content of the new Task * @param candidateBelief The belief to be used in future logic, for * forward/backward correspondence */ public void addSolution(final Task currentTask, final BudgetValue budget, final Sentence sentence, final Sentence candidateBelief) { addNewTask(new Task(sentence, budget, currentTask, sentence, candidateBelief), "Activated"); } public interface StampBuilder { public Stamp build(); } public static class LazyStampBuilder implements StampBuilder { public final Stamp a, b; public final long creationTime, occurrenceTime; protected Stamp stamp = null; public LazyStampBuilder(Stamp a, Stamp b, long creationTime, long occurrenceTime) { this.a = a; this.b = b; this.creationTime = creationTime; this.occurrenceTime = occurrenceTime; } @Override public Stamp build() { if (stamp == null) stamp = new Stamp(a, b, creationTime).setOccurrenceTime(occurrenceTime); return stamp; } } public StampBuilder newStamp(Sentence a, Sentence b, long at) { return new LazyStampBuilder(a.stamp, b.stamp, time(), at); } public StampBuilder newStamp(Sentence a, Sentence b) { /** eternal by default, it may be changed later */ return newStamp(a, b, Stamp.ETERNAL); } /** returns a new stamp if A and B do not have overlapping evidence; null otherwise */ public StampBuilder newStampIfNotOverlapping(Sentence A, Sentence B) { long[] a = A.stamp.toSet(); long[] b = B.stamp.toSet(); for (long ae : a) { for (long be : b) { if (ae == be) return null; } } return newStamp(A, B); } }
nars_java/src/main/java/nars/logic/NAL.java
/* * Here comes the text of your license * Each line should be prefixed with * */ package nars.logic; import nars.core.*; import nars.logic.entity.*; import reactor.event.Event; import reactor.function.Supplier; import java.util.ArrayDeque; import java.util.Deque; import java.util.List; /** * NAL Reasoner Process. Includes all reasoning process state and common utility methods that utilize it. * <p> * https://code.google.com/p/open-nars/wiki/SingleStepTestingCases * according to derived Task: if it contains a mental operator it is NAL9, if it contains a operation it is NAL8, if it contains temporal information it is NAL7, if it contains in/dependent vars it is NAL6, if it contains higher order copulas like &&, ==> or negation it is NAL5 * <p> * if it contains product or image it is NAL4, if it contains sets or set operations like &, -, | it is NAL3 * <p> * if it contains similarity or instances or properties it is NAL2 * and if it only contains inheritance */ public abstract class NAL extends Event implements Runnable, Supplier<Task> { public interface DerivationFilter extends Plugin { /** * returns null if allowed to derive, or a String containing a short rejection reason for logging */ public String reject(NAL nal, Task task, boolean revised, boolean single, Task parent, Sentence otherBelief, Sentence derivedCurrentBelief, Task derivedCurrentTask); @Override public default boolean setEnabled(NAR n, boolean enabled) { return true; } } public final Memory memory; protected final Task currentTask; protected Sentence currentBelief; protected final NALRuleEngine reasoner; /** * stores the tasks that this process generates, and adds to memory */ Deque<Task> newTasks = null; //lazily instantiated //TODO tasksDicarded public NAL(Memory mem, Task task) { this(mem, -1, task); } /** @param nalLevel the NAL level to limit processing of this reasoning context. set to -1 to use Memory's default value */ public NAL(Memory mem, int nalLevel, Task task) { super(null); //setKey(getClass()); setData(this); memory = mem; reasoner = memory.rules; if ((nalLevel!=-1) && (nalLevel!=mem.nal())) throw new RuntimeException("Different NAL level than Memory not supported yet"); currentTask = task; currentBelief = null; } @Override public void run() { onStart(); reason(); onFinished(); } protected void onStart() { /** implement if necessary in subclasses */ } protected void onFinished() { /** implement if necessary in subclasses */ } protected abstract void reason(); protected int newTasksCount() { if (newTasks == null) return 0; return newTasks.size(); } public void emit(final Class c, final Object... o) { memory.emit(c, o); } public int nal() { return memory.nal(); } /** * whether at least NAL level N is enabled */ public boolean nal(int n) { return nal() >= n; } public boolean deriveTask(final Task task, final boolean revised, final boolean single, Task parent, Sentence occurence2) { return deriveTask(task, revised, single, parent, occurence2, getCurrentBelief(), getCurrentTask()); } /** * iived task comes from the logic rules. * * @param task the derived task */ public boolean deriveTask(final Task task, final boolean revised, final boolean single, Task parent, Sentence occurence2, Sentence derivedCurrentBelief, Task derivedCurrentTask) { List<DerivationFilter> derivationFilters = reasoner.getDerivationFilters(); if (derivationFilters != null) { for (int i = 0; i < derivationFilters.size(); i++) { DerivationFilter d = derivationFilters.get(i); String rejectionReason = d.reject(this, task, revised, single, parent, occurence2, derivedCurrentBelief, derivedCurrentTask); if (rejectionReason != null) { memory.removeTask(task, rejectionReason); return false; } } } if (task.sentence.getOccurenceTime() > memory.time()) { memory.event.emit(Events.TaskDeriveFuture.class, task, this); } if (task.sentence.stamp.latency > 0) { memory.logic.DERIVATION_LATENCY.set((double) task.sentence.stamp.latency); } task.setParticipateInTemporalInduction(false); final Sentence occurence = parent != null ? parent.sentence : null; memory.event.emit(Events.TaskDerive.class, task, revised, single, occurence, occurence2, derivedCurrentTask); memory.logic.TASK_DERIVED.hit(); addNewTask(task, "Derived"); return true; } /* --------------- new task building --------------- */ /** * Shared final operations by all double-premise rules, called from the * rules except StructuralRules * * @param newTaskContent The content of the sentence in task * @param newTruth The truth value of the sentence in task * @param newBudget The budget value in task */ public boolean doublePremiseTask(CompoundTerm newTaskContent, final TruthValue newTruth, final BudgetValue newBudget, StampBuilder newStamp, boolean temporalAdd) { return doublePremiseTask(newTaskContent, newTruth, newBudget, newStamp, temporalAdd, getCurrentBelief(), getCurrentTask()); } public boolean doublePremiseTask(CompoundTerm newTaskContent, final TruthValue newTruth, final BudgetValue newBudget, StampBuilder stamp, final boolean temporalAdd, Sentence subbedBelief, Task subbedTask) { if (!newBudget.aboveThreshold()) { return false; } newTaskContent = Sentence.termOrNull(newTaskContent); if (newTaskContent == null) return false; final Stamp newStamp = stamp.build(); boolean derived = deriveTask(new Task( new Sentence(newTaskContent, subbedTask.sentence.punctuation, newTruth, newStamp), newBudget, subbedTask, subbedBelief), false, false, null, subbedTask.sentence); //"Since in principle it is always valid to eternalize a tensed belief" if (temporalAdd && nal(7) && Parameters.IMMEDIATE_ETERNALIZATION) { //temporal induction generated ones get eternalized directly derived |= deriveTask( new Task( new Sentence(newTaskContent, subbedTask.sentence.punctuation, TruthFunctions.eternalize(newTruth), newStamp.cloneEternal()), newBudget, subbedTask, subbedBelief), false, false, null, null); } return derived; } /** * Shared final operations by all double-premise rules, called from the * rules except StructuralRules * * @param newContent The content of the sentence in task * @param newTruth The truth value of the sentence in task * @param newBudget The budget value in task * @param revisible Whether the sentence is revisible */ // public void doublePremiseTask(Term newContent, TruthValue newTruth, BudgetValue newBudget, boolean revisible) { // if (newContent != null) { // Sentence taskSentence = currentTask.getSentence(); // Sentence newSentence = new Sentence(newContent, taskSentence.getPunctuation(), newTruth, newStamp, revisible); // Task newTaskAt = new Task(newSentence, newBudget, currentTask, currentBelief); // derivedTask(newTaskAt, false, false); // } // } /** * Shared final operations by all single-premise rules, called in * StructuralRules * * @param newContent The content of the sentence in task * @param newTruth The truth value of the sentence in task * @param newBudget The budget value in task */ public boolean singlePremiseTask(CompoundTerm newContent, TruthValue newTruth, BudgetValue newBudget) { return singlePremiseTask(newContent, getCurrentTask().sentence.punctuation, newTruth, newBudget); } /** * Shared final operations by all single-premise rules, called in * StructuralRules * * @param newContent The content of the sentence in task * @param punctuation The punctuation of the sentence in task * @param newTruth The truth value of the sentence in task * @param newBudget The budget value in task */ public boolean singlePremiseTask(final CompoundTerm newContent, final char punctuation, final TruthValue newTruth, final BudgetValue newBudget) { if (!newBudget.aboveThreshold()) return false; Task parentTask = getCurrentTask().getParentTask(); if (parentTask != null) { if (parentTask.getTerm() == null) { return false; } if (newContent == null) { return false; } if (newContent.equals(parentTask.getTerm())) { return false; } } Sentence taskSentence = getCurrentTask().sentence; final Stamp stamp; if (taskSentence.isJudgment() || getCurrentBelief() == null) { stamp = new Stamp(taskSentence.stamp, time()); } else { // to answer a question with negation in NAL-5 --- move to activated task? stamp = new Stamp(getCurrentBelief().stamp, time()); } if (newContent.subjectOrPredicateIsIndependentVar()) { return false; } return deriveTask(new Task(new Sentence(newContent, punctuation, newTruth, stamp), newBudget, getCurrentTask(), null), false, true, null, null); } public boolean singlePremiseTask(Sentence newSentence, BudgetValue newBudget) { /*if (!newBudget.aboveThreshold()) { return false; }*/ Task newTask = new Task(newSentence, newBudget, getCurrentTask()); return deriveTask(newTask, false, true, null, null); } public long time() { return memory.time(); } /** * @return the currentTask */ public Task getCurrentTask() { return currentTask; } // // /** // * @return the newStamp // */ // public Stamp getTheNewStamp() { // if (newStamp == null) { // //if newStamp==null then newStampBuilder must be available. cache it's return value as newStamp // newStamp = newStampBuilder.build(); // newStampBuilder = null; // } // return newStamp; // } // public Stamp getTheNewStampForRevision() { // if (newStamp == null) { // if (newStampBuilder.overlapping()) { // newStamp = null; // } // else { // newStamp = newStampBuilder.build(); // } // newStampBuilder = null; // } // return newStamp; // } // // /** // * @param newStamp the newStamp to set // */ // public Stamp setNextNewStamp(Stamp newStamp) { // this.newStamp = newStamp; // this.newStampBuilder = null; // return newStamp; // } // // /** // * creates a lazy/deferred StampBuilder which only constructs the stamp if getTheNewStamp() is actually invoked // */ // public void setNextNewStamp(final Stamp first, final Stamp second, final long time) { // newStamp = null; // newStampBuilder = new NewStampBuilder(first, second, time); // } // interface StampBuilder { // // public Stamp build(); // // default public Stamp getFirst() { return null; } // default public Stamp getSecond(){ return null; } // // default public boolean overlapping() { // /*final int stampLength = stamp.baseLength; // for (int i = 0; i < stampLength; i++) { // final long baseI = stamp.evidentialBase[i]; // for (int j = 0; j < stampLength; j++) { // if ((i != j) && (baseI == stamp.evidentialBase[j])) { // throw new RuntimeException("Overlapping Revision Evidence: Should have been discovered earlier: " + Arrays.toString(stamp.evidentialBase)); // } // } // }*/ // // long[] a = getFirst().toSet(); // long[] b = getSecond().toSet(); // for (long ae : a) { // for (long be : b) { // if (ae == be) return true; // } // } // return false; // } // } /** * @return the currentBelief */ public Sentence getCurrentBelief() { return currentBelief; } /** * tasks added with this method will be buffered by this NAL instance; * at the end of the processing they can be reviewed and filtered * then they need to be added to memory with inputTask(t) */ protected void addNewTask(Task t, String reason) { t.setReason(reason); if (newTasks==null) newTasks = new ArrayDeque(4); newTasks.add(t); } /** called from consumers of the tasks that this context generates */ @Override public Task get() { if (newTasks == null || newTasks.isEmpty()) return null; return newTasks.removeFirst(); } /** * Activated task called in MatchingRules.trySolution and * Concept.processGoal * * @param budget The budget value of the new Task * @param sentence The content of the new Task * @param candidateBelief The belief to be used in future logic, for * forward/backward correspondence */ public void addSolution(final Task currentTask, final BudgetValue budget, final Sentence sentence, final Sentence candidateBelief) { addNewTask(new Task(sentence, budget, currentTask, sentence, candidateBelief), "Activated"); } public interface StampBuilder { public Stamp build(); } public static class LazyStampBuilder implements StampBuilder { public final Stamp a, b; public final long creationTime, occurrenceTime; protected Stamp stamp = null; public LazyStampBuilder(Stamp a, Stamp b, long creationTime, long occurrenceTime) { this.a = a; this.b = b; this.creationTime = creationTime; this.occurrenceTime = occurrenceTime; } @Override public Stamp build() { if (stamp == null) stamp = new Stamp(a, b, creationTime).setOccurrenceTime(occurrenceTime); return stamp; } } public StampBuilder newStamp(Sentence a, Sentence b, long at) { return new LazyStampBuilder(a.stamp, b.stamp, time(), at); } public StampBuilder newStamp(Sentence a, Sentence b) { /** eternal by default, it may be changed later */ return newStamp(a, b, Stamp.ETERNAL); } /** returns a new stamp if A and B do not have overlapping evidence; null otherwise */ public StampBuilder newStampIfNotOverlapping(Sentence A, Sentence B) { long[] a = A.stamp.toSet(); long[] b = B.stamp.toSet(); for (long ae : a) { for (long be : b) { if (ae == be) return null; } } return newStamp(A, B); } }
temporal induction fix
nars_java/src/main/java/nars/logic/NAL.java
temporal induction fix
<ide><path>ars_java/src/main/java/nars/logic/NAL.java <ide> <ide> boolean derived = deriveTask(new Task( <ide> new Sentence(newTaskContent, subbedTask.sentence.punctuation, newTruth, newStamp), <del> newBudget, subbedTask, subbedBelief), false, false, null, subbedTask.sentence); <add> newBudget, subbedTask, subbedBelief), false, false, subbedTask, subbedBelief); <ide> <ide> //"Since in principle it is always valid to eternalize a tensed belief" <ide> if (temporalAdd && nal(7) && Parameters.IMMEDIATE_ETERNALIZATION) {
JavaScript
mit
50d1bee9a10125e9a3ee4846296c32a15f1bec24
0
ProseMirror/prosemirror-view
import browser from "./browser" export const domIndex = function(node) { for (var index = 0;; index++) { node = node.previousSibling if (!node) return index } } export const parentNode = function(node) { let parent = node.parentNode return parent && parent.nodeType == 11 ? parent.host : parent } export const textRange = function(node, from, to) { let range = document.createRange() range.setEnd(node, to == null ? node.nodeValue.length : to) range.setStart(node, from || 0) return range } // Scans forward and backward through DOM positions equivalent to the // given one to see if the two are in the same place (i.e. after a // text node vs at the end of that text node) export const isEquivalentPosition = function(node, off, targetNode, targetOff) { return targetNode && (scanFor(node, off, targetNode, targetOff, -1) || scanFor(node, off, targetNode, targetOff, 1)) } const atomElements = /^(img|br|input|textarea|hr)$/i function scanFor(node, off, targetNode, targetOff, dir) { for (;;) { if (node == targetNode && off == targetOff) return true if (off == (dir < 0 ? 0 : nodeSize(node))) { let parent = node.parentNode if (parent.nodeType != 1 || hasBlockDesc(node) || atomElements.test(node.nodeName) || node.contentEditable == "false") return false off = domIndex(node) + (dir < 0 ? 0 : 1) node = parent } else if (node.nodeType == 1) { node = node.childNodes[off + (dir < 0 ? -1 : 0)] off = dir < 0 ? nodeSize(node) : 0 } else { return false } } } export function nodeSize(node) { return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length } function hasBlockDesc(dom) { let desc for (let cur = dom; cur; cur = cur.parentNode) if (desc = cur.pmViewDesc) break return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom) } // Work around Chrome issue https://bugs.chromium.org/p/chromium/issues/detail?id=447523 // (isCollapsed inappropriately returns true in shadow dom) export const selectionCollapsed = function(domSel) { let collapsed = domSel.isCollapsed if (collapsed && browser.chrome && domSel.rangeCount && !domSel.getRangeAt(0).collapsed) collapsed = false return collapsed } export function keyEvent(keyCode, key) { let event = document.createEvent("Event") event.initEvent("keydown", true, true) event.keyCode = keyCode event.key = event.code = key return event }
src/dom.js
import browser from "./browser" export const domIndex = function(node) { for (var index = 0;; index++) { node = node.previousSibling if (!node) return index } } export const parentNode = function(node) { let parent = node.parentNode return parent && parent.nodeType == 11 ? parent.host : parent } export const textRange = function(node, from, to) { let range = document.createRange() range.setEnd(node, to == null ? node.nodeValue.length : to) range.setStart(node, from || 0) return range } // Scans forward and backward through DOM positions equivalent to the // given one to see if the two are in the same place (i.e. after a // text node vs at the end of that text node) export const isEquivalentPosition = function(node, off, targetNode, targetOff) { return targetNode && (scanFor(node, off, targetNode, targetOff, -1) || scanFor(node, off, targetNode, targetOff, 1)) } const atomElements = /^(img|br|input|textarea|hr)$/i function scanFor(node, off, targetNode, targetOff, dir) { for (;;) { if (node == targetNode && off == targetOff) return true if (off == (dir < 0 ? 0 : nodeSize(node))) { let parent = node.parentNode if (parent.nodeType != 1 || hasBlockDesc(node) || atomElements.test(node.nodeName) || node.contentEditable == "false") return false off = domIndex(node) + (dir < 0 ? 0 : 1) node = parent } else if (node.nodeType == 1) { node = node.childNodes[off + (dir < 0 ? -1 : 0)] off = dir < 0 ? nodeSize(node) : 0 } else { return false } } } export function nodeSize(node) { return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length } function hasBlockDesc(dom) { let desc = dom.pmViewDesc return desc && desc.node && desc.node.isBlock } // Work around Chrome issue https://bugs.chromium.org/p/chromium/issues/detail?id=447523 // (isCollapsed inappropriately returns true in shadow dom) export const selectionCollapsed = function(domSel) { let collapsed = domSel.isCollapsed if (collapsed && browser.chrome && domSel.rangeCount && !domSel.getRangeAt(0).collapsed) collapsed = false return collapsed } export function keyEvent(keyCode, key) { let event = document.createEvent("Event") event.initEvent("keydown", true, true) event.keyCode = keyCode event.key = event.code = key return event }
Correct selection when it is outside a node view's contentDOM FIX: Don't leave DOM selection in place when it is inside a node view but not inside its content DOM element. See https://discuss.prosemirror.net/t/nodeview-and-inserting-text-between-elements/2256
src/dom.js
Correct selection when it is outside a node view's contentDOM
<ide><path>rc/dom.js <ide> } <ide> <ide> function hasBlockDesc(dom) { <del> let desc = dom.pmViewDesc <del> return desc && desc.node && desc.node.isBlock <add> let desc <add> for (let cur = dom; cur; cur = cur.parentNode) if (desc = cur.pmViewDesc) break <add> return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom) <ide> } <ide> <ide> // Work around Chrome issue https://bugs.chromium.org/p/chromium/issues/detail?id=447523
JavaScript
mit
cebe030c8792ea7492387dc9ddf57276a18b7851
0
sytac/gulp-commonjs-tasks
var fs = require('fs'), lang = require('lodash/lang'), path = require('path'), util = require('util'); var _task; var runSequence; module.exports = function taskLoader(taskDir, gulp) { runSequence = require('run-sequence') .use(gulp); if (arguments.length < 2) { throw 'Expecting at least two arguments: taskDir and gulp'; } // let's first catch all the arguments here var args = Array.prototype.slice.apply(arguments); // let's add a state object we need to haul with the parser var state = { defaultTaskNames: [], sequenceCount: 0 }; args.unshift(state); var taskNames = []; _task = function() { var args = Array.prototype.slice.apply(arguments); taskNames.push(args[0]); console.log('_task', args); return gulp.task.apply(gulp, args); }; _parse.apply(this, args); if (state.defaultTaskNames.length) { _task('default', state.defaultTaskNames); } return { task: _task, taskNames: taskNames, defaultTaskNames: state.defaultTaskNames }; }; function _parse(state, taskDir, gulp) { var customOptions = ['usage', 'description', 'seq', 'options', 'isDefault' ]; var args = Array.prototype.slice.call(arguments) .splice(2); var currentPriority = -10; // get all tasks // todo: clean this mess up fs.readdirSync(taskDir) .map(function(file) { var stats = fs.statSync(taskDir + path.sep + file); if (stats.isFile() && path.extname(file) === '.js') { var tasks; var requiredTasks = require(taskDir + path.sep + file); if (lang.isFunction(requiredTasks)) { tasks = requiredTasks.apply(null, args); if (lang.isFunction(tasks)) { var taskFn = tasks; var taskName = path.basename(file, '.js'); tasks = {}; tasks[taskName] = { fn: taskFn }; } } else { tasks = requiredTasks; } // let's assume it's an object if (lang.isObject(tasks)) { Object.keys(tasks) .map(function(taskName) { var task = tasks[taskName]; var taskArgs = [taskName]; if (lang.isFunction(task)) { taskArgs.push([]); taskArgs.push(task); } else if (lang.isObject(task)) { // Check for default tasks _defaultTasks(gulp, taskName, task, state); // sequences _sequences(gulp, taskName, task, state); // dependencies var deps = []; var depIndex = 1; var anonCount = 0; if (lang.isArray(task.dep)) { task.dep.map(function(taskDep) { var dep = taskDep; if (lang.isFunction(taskDep)) { var fnName = _getFunctionName(taskDep); if (!fnName) { anonCount++; fnName = util.format('anonymous-%s', anonCount); } var depName = util.format( '%s-(index: %s, fnName: %s)', taskName, depIndex, fnName); _task.apply(gulp, [ depName, [], taskDep ]); depIndex++; dep = depName; console.log('--', depName); } deps.push(dep); }); } taskArgs.push(deps); if (task.fn) { taskArgs.push(task.fn); } } else if (lang.isArray(task)) { taskArgs.push(task); } if (taskArgs.length > 1) { _task.apply(gulp, taskArgs); // priority if (task.description) { var priority = task.priority; if (!priority) { priority = currentPriority; currentPriority = currentPriority - 10; } gulp.tasks[taskName].priority = priority; } customOptions.map(function( customOption) { var taskOption = task[ customOption]; if (taskOption) { gulp.tasks[taskName] [ customOption ] = taskOption; } }); } }); } } }); } function _defaultTasks(gulp, taskName, task, state) { // default task(s) if (task.isDefault) { state.defaultTaskNames.push(taskName); } } function _sequences(gulp, taskName, task, state) { if (task.seq) { state.sequenceCount++; var sequence = []; var localState = { seqIndex: 1, anonCount: 0 }; task.seq = _parseSequence(gulp, taskName, task.seq, state, localState); // If task does not have a function assigned then create one... if (!task.fn) { task.fn = function(done) { runSequence.apply( null, task.seq .concat( done)); }; } else { // ... otherwise chop it off, and place it in a new task at the very end // of the sequence. Yes I could monkey patch the task function but that's // a bit too ghetto I think. var subName = 'post-' + taskName; var origFn = task.fn; _task.apply(gulp, [ subName, [], origFn ]); task.fn = function(done) { runSequence.apply( null, task.seq .concat( subName ) .concat( done)); }; } } } function _parseSequence(gulp, taskName, seqTasks, state, localState) { return seqTasks.map(function(seqTask) { if (lang.isString(seqTask)) { return seqTask; } else if (lang.isFunction(seqTask)) { var fnName = _getFunctionName(seqTask); if (!fnName) { localState.anonCount++; fnName = util.format('anonymous-%s', localState.anonCount); } var seqName = util.format( '%s-(index: %s, fnName: %s)', taskName, localState.seqIndex, fnName); _task.apply(gulp, [ seqName, [], seqTask ]); console.log(_getFunctionName(seqTask)); localState.seqIndex++; return seqName; } else if (lang.isArray(seqTask)) { console.log('array', seqTask); state.sequenceCount++; return _parseSequence(gulp, taskName, seqTask, state, localState); } }); } function _getFunctionName(fn) { var fnName = fn.toString(); fnName = fnName.substr('function '.length); fnName = fnName.substr(0, fnName.indexOf('(')); return fnName; }
task-loader/index.js
var fs = require('fs'), lang = require('lodash/lang'), path = require('path'), util = require('util'); module.exports = function taskLoader(taskDir, gulp) { var customOptions = ['usage', 'description', 'seq', 'options', 'isDefault' ]; var defaultTaskNames = []; var args = []; var sequenceCount = 0; var currentPriority = -10; if (arguments.length > 0) { args = Array.prototype.slice.call(arguments) .splice(1); } // get all tasks var runSequence = require('run-sequence') .use(gulp), taskNames = []; // todo: clean this mess up fs.readdirSync(taskDir) .map(function(file) { var stats = fs.statSync(taskDir + path.sep + file); if (stats.isFile() && path.extname(file) === '.js') { var tasks; var requiredTasks = require(taskDir + path.sep + file); if (lang.isFunction(requiredTasks)) { tasks = requiredTasks.apply(null, args); if (lang.isFunction(tasks)) { var taskFn = tasks; var taskName = path.basename(file, '.js'); tasks = {}; tasks[taskName] = { fn: taskFn }; } } else { tasks = requiredTasks; } // let's assume it's an object if (lang.isObject(tasks)) { Object.keys(tasks) .map(function(taskName) { var task = tasks[taskName]; var taskArgs = [taskName]; if (lang.isFunction(task)) { taskArgs.push([]); taskArgs.push(task); } else if (lang.isObject(task)) { if (task.isDefault) { defaultTaskNames.push(taskName); } if (task.seq) { sequenceCount++; var sequence = []; var seqIndex = 1; var anonCount = 0; var _p = function(seqTasks) { return seqTasks.map(function(seqTask) { if (lang.isString(seqTask)) { return seqTask; } else if (lang.isFunction(seqTask)) { var fnName = _functionName(seqTask); if (!fnName) { anonCount++; fnName = util.format('anonymous-%s', anonCount); } var seqName = util.format( '%s-(index: %s, fnName: %s)', taskName, seqIndex, fnName); gulp.task.apply(gulp, [ seqName, [], seqTask ]); console.log(_functionName(seqTask)); seqIndex++; return seqName; } else if (lang.isArray(seqTask)) { console.log('array', seqTask); sequenceCount++; return _p(seqTask); } }); } task.seq = _p(task.seq); if (!task.fn) { task.fn = function(done) { runSequence.apply( null, task.seq .concat( done)); } } else { var subName = 'post-' + taskName; var origFn = task.fn; gulp.task.apply(gulp, [ subName, [], origFn ]); task.fn = function(done) { runSequence.apply( null, task.seq .concat( subName ) .concat( done)); } } } var deps = []; var depIndex = 1; var anonCount = 0; if (lang.isArray(task.dep)) { task.dep.map(function(taskDep) { var dep = taskDep; if (lang.isFunction(taskDep)) { var fnName = _functionName(taskDep); if (!fnName) { anonCount++; fnName = util.format('anonymous-%s', anonCount); } var depName = util.format( '%s-(index: %s, fnName: %s)', taskName, depIndex, fnName); gulp.task.apply(gulp, [ depName, [], taskDep ]); depIndex++; dep = depName; console.log('--', depName); } deps.push(dep); }); } taskArgs.push(deps); if (task.fn) { taskArgs.push(task.fn); } } else if (lang.isArray(task)) { taskArgs.push(task); } if (taskArgs.length > 1) { taskNames.push(taskArgs[0]); gulp.task.apply(gulp, taskArgs); // priority if (task.description) { var priority = task.priority; if (!priority) { priority = currentPriority; currentPriority = currentPriority - 10; } gulp.tasks[taskName].priority = priority; } customOptions.map(function( customOption) { var taskOption = task[ customOption]; if (taskOption) { gulp.tasks[taskName] [ customOption ] = taskOption; } }); } }); } } }); if (defaultTaskNames.length) { gulp.task('default', defaultTaskNames); } return { taskNames: taskNames }; } function _functionName(fun) { var ret = fun.toString(); ret = ret.substr('function '.length); ret = ret.substr(0, ret.indexOf('(')); return ret; }
Some decomp
task-loader/index.js
Some decomp
<ide><path>ask-loader/index.js <ide> lang = require('lodash/lang'), <ide> path = require('path'), <ide> util = require('util'); <add>var _task; <add>var runSequence; <ide> <ide> module.exports = function taskLoader(taskDir, gulp) { <del> <add> runSequence = require('run-sequence') <add> .use(gulp); <add> if (arguments.length < 2) { <add> throw 'Expecting at least two arguments: taskDir and gulp'; <add> } <add> <add> // let's first catch all the arguments here <add> var args = Array.prototype.slice.apply(arguments); <add> <add> // let's add a state object we need to haul with the parser <add> var state = { <add> defaultTaskNames: [], <add> sequenceCount: 0 <add> }; <add> <add> args.unshift(state); <add> <add> var taskNames = []; <add> <add> _task = function() { <add> var args = Array.prototype.slice.apply(arguments); <add> taskNames.push(args[0]); <add> console.log('_task', args); <add> return gulp.task.apply(gulp, args); <add> }; <add> <add> _parse.apply(this, args); <add> <add> if (state.defaultTaskNames.length) { <add> _task('default', state.defaultTaskNames); <add> } <add> return { <add> task: _task, <add> taskNames: taskNames, <add> defaultTaskNames: state.defaultTaskNames <add> }; <add>}; <add> <add> <add>function _parse(state, taskDir, gulp) { <ide> var customOptions = ['usage', <ide> 'description', <ide> 'seq', <ide> 'isDefault' <ide> ]; <ide> <del> var defaultTaskNames = []; <del> <del> var args = []; <del> <del> var sequenceCount = 0; <add> var args = Array.prototype.slice.call(arguments) <add> .splice(2); <add> <ide> var currentPriority = -10; <ide> <del> if (arguments.length > 0) { <del> args = Array.prototype.slice.call(arguments) <del> .splice(1); <del> } <ide> // get all tasks <ide> <del> var runSequence = require('run-sequence') <del> .use(gulp), <del> taskNames = []; <add> <ide> <ide> // todo: clean this mess up <ide> fs.readdirSync(taskDir) <ide> taskArgs.push([]); <ide> taskArgs.push(task); <ide> } else if (lang.isObject(task)) { <del> if (task.isDefault) { <del> defaultTaskNames.push(taskName); <del> } <del> if (task.seq) { <del> sequenceCount++; <del> var sequence = []; <del> var seqIndex = 1; <del> var anonCount = 0; <del> <del> var _p = function(seqTasks) { <del> return seqTasks.map(function(seqTask) { <del> if (lang.isString(seqTask)) { <del> return seqTask; <del> } else if (lang.isFunction(seqTask)) { <del> var fnName = _functionName(seqTask); <del> if (!fnName) { <del> anonCount++; <del> fnName = util.format('anonymous-%s', <del> anonCount); <del> } <del> <del> <del> var seqName = util.format( <del> '%s-(index: %s, fnName: %s)', taskName, <del> seqIndex, fnName); <del> gulp.task.apply(gulp, [ <del> seqName, [], <del> seqTask <del> ]); <del> <del> console.log(_functionName(seqTask)); <del> <del> seqIndex++; <del> return seqName; <del> } else if (lang.isArray(seqTask)) { <del> console.log('array', seqTask); <del> sequenceCount++; <del> return _p(seqTask); <del> } <del> <del> }); <del> } <del> task.seq = _p(task.seq); <del> if (!task.fn) { <del> task.fn = function(done) { <del> runSequence.apply( <del> null, task.seq <del> .concat( <del> done)); <del> } <del> } else { <del> var subName = 'post-' + <del> taskName; <del> var origFn = task.fn; <del> gulp.task.apply(gulp, [ <del> subName, [], <del> origFn <del> ]); <del> <del> task.fn = function(done) { <del> runSequence.apply( <del> null, task.seq <del> .concat( <del> subName <del> ) <del> .concat( <del> done)); <del> } <del> } <del> } <add> <add> // Check for default tasks <add> _defaultTasks(gulp, taskName, task, state); <add> <add> // sequences <add> _sequences(gulp, taskName, task, state); <add> <add> // dependencies <ide> var deps = []; <ide> var depIndex = 1; <ide> var anonCount = 0; <ide> task.dep.map(function(taskDep) { <ide> var dep = taskDep; <ide> if (lang.isFunction(taskDep)) { <del> var fnName = _functionName(taskDep); <add> var fnName = _getFunctionName(taskDep); <ide> if (!fnName) { <ide> anonCount++; <ide> fnName = util.format('anonymous-%s', <ide> var depName = util.format( <ide> '%s-(index: %s, fnName: %s)', taskName, <ide> depIndex, fnName); <del> gulp.task.apply(gulp, [ <add> _task.apply(gulp, [ <ide> depName, [], <ide> taskDep <ide> ]); <ide> } <ide> <ide> if (taskArgs.length > 1) { <del> taskNames.push(taskArgs[0]); <del> gulp.task.apply(gulp, <add> _task.apply(gulp, <ide> taskArgs); <ide> <ide> // priority <ide> } <ide> gulp.tasks[taskName].priority = priority; <ide> } <add> <ide> customOptions.map(function( <ide> customOption) { <ide> var taskOption = task[ <ide> } <ide> } <ide> }); <del> <del> if (defaultTaskNames.length) { <del> gulp.task('default', defaultTaskNames); <del> } <del> return { <del> taskNames: taskNames <del> }; <del>} <del> <del>function _functionName(fun) { <del> var ret = fun.toString(); <del> ret = ret.substr('function '.length); <del> ret = ret.substr(0, ret.indexOf('(')); <del> return ret; <del>} <add>} <add> <add>function _defaultTasks(gulp, taskName, task, state) { <add> // default task(s) <add> if (task.isDefault) { <add> state.defaultTaskNames.push(taskName); <add> } <add>} <add> <add>function _sequences(gulp, taskName, task, state) { <add> if (task.seq) { <add> state.sequenceCount++; <add> var sequence = []; <add> <add> var localState = { <add> seqIndex: 1, <add> anonCount: 0 <add> }; <add> <add> <add> task.seq = _parseSequence(gulp, taskName, task.seq, state, localState); <add> <add> // If task does not have a function assigned then create one... <add> if (!task.fn) { <add> task.fn = function(done) { <add> runSequence.apply( <add> null, task.seq <add> .concat( <add> done)); <add> }; <add> <add> } else { <add> // ... otherwise chop it off, and place it in a new task at the very end <add> // of the sequence. Yes I could monkey patch the task function but that's <add> // a bit too ghetto I think. <add> var subName = 'post-' + <add> taskName; <add> var origFn = task.fn; <add> _task.apply(gulp, [ <add> subName, [], <add> origFn <add> ]); <add> <add> task.fn = function(done) { <add> runSequence.apply( <add> null, task.seq <add> .concat( <add> subName <add> ) <add> .concat( <add> done)); <add> }; <add> } <add> } <add>} <add> <add>function _parseSequence(gulp, taskName, seqTasks, state, localState) { <add> <add> return seqTasks.map(function(seqTask) { <add> if (lang.isString(seqTask)) { <add> return seqTask; <add> } else if (lang.isFunction(seqTask)) { <add> var fnName = _getFunctionName(seqTask); <add> if (!fnName) { <add> localState.anonCount++; <add> fnName = util.format('anonymous-%s', <add> localState.anonCount); <add> } <add> <add> var seqName = util.format( <add> '%s-(index: %s, fnName: %s)', <add> taskName, <add> localState.seqIndex, fnName); <add> _task.apply(gulp, [ <add> seqName, [], <add> seqTask <add> ]); <add> <add> console.log(_getFunctionName(seqTask)); <add> <add> localState.seqIndex++; <add> return seqName; <add> } else if (lang.isArray(seqTask)) { <add> console.log('array', seqTask); <add> state.sequenceCount++; <add> return _parseSequence(gulp, taskName, seqTask, state, localState); <add> } <add> <add> }); <add>} <add> <add> <add>function _getFunctionName(fn) { <add> var fnName = fn.toString(); <add> fnName = fnName.substr('function '.length); <add> fnName = fnName.substr(0, fnName.indexOf('(')); <add> return fnName; <add>}
Java
mit
4d2b3c16dbdfe17695cdab3cf00c498135d19ff0
0
asascience-open/ncSOS
package com.asascience.ncsos.service; import com.asascience.ncsos.ds.BaseDSHandler; import com.asascience.ncsos.error.ExceptionResponseHandler; import com.asascience.ncsos.gc.GetCapabilitiesRequestHandler; import com.asascience.ncsos.go.GetObservationRequestHandler; import com.asascience.ncsos.outputformatter.CachedFileFormatter; import com.asascience.ncsos.outputformatter.OutputFormatter; import com.asascience.ncsos.util.LogUtils; import com.asascience.ncsos.util.LowerCaseStringMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; import ucar.nc2.dataset.NetcdfDataset; import javax.xml.parsers.ParserConfigurationException; import java.io.*; import java.net.URLDecoder; import java.util.Calendar; import java.util.HashMap; import java.util.Map; public class Parser { public static final String ERROR = "error"; public static final String GETCAPABILITIES = "GetCapabilities"; public static final String GETOBSERVATION = "GetObservation"; public static final String DESCRIBESENSOR = "DescribeSensor"; public static final String OUTPUT_FORMATTER = "outputFormatter"; public static final String SECTIONS = "sections"; public static final String USECACHE = "usecache"; public static final String XML = "xml"; private LowerCaseStringMap queryParameters; private Logger _log; private Map<String, String> coordsHash; private final String defService = "sos"; private final String defVersion = "1.0.0"; private final String TRUE_STRING = "true"; public final static String PROCEDURE = "procedure"; public final static String ACCEPT_VERSIONS = "AcceptVersions"; public final static String VERSION = "version"; public final static String REQUEST = "request"; public final static String SERVICE = "service"; public final static String LAT = "latitude"; public final static String LON = "longitude"; public final static String DEPTH = "depth"; public final static String RESPONSE_FORMAT = "responseFormat"; public final static String OUTPUT_FORMAT = "outputFormat"; public final static String OBSERVED_PROPERTY = "observedProperty"; public final static String OFFERING = "offering"; public final static String EVENT_TIME = "eventTime"; private final int numDays = 7; // millisecs per sec * secs per hour * hour per day * day limit (1 week) private final long CACHE_AGE_LIMIT = 1000 * 3600 * 24 * numDays; // Exception codes - Table 25 of OGC 06-121r3 (OWS Common) protected static String INVALID_PARAMETER = "InvalidParameterValue"; protected static String MISSING_PARAMETER = "MissingParameterValue"; protected static String OPTION_NOT_SUPPORTED = "OptionNotSupported"; protected static String OPERATION_NOT_SUPPORTED = "OperationNotSupported"; protected static String VERSION_NEGOTIATION = "VersionNegotiationFailed"; ExceptionResponseHandler errorHandler = null; /** * Sets the logger for error output using the Parser class. */ public Parser() throws IOException { _log = LoggerFactory.getLogger(Parser.class); errorHandler = new ExceptionResponseHandler(); } /** * enhanceGETRequest - provides direct access to parsing a sos request and create handler for the type of request coming in * @param dataset NetcdfDataset to enhanceGETRequest the NCML * @param query query string provided by request * @param threddsURI * @return * @throws IOException */ public HashMap<String, Object> enhanceGETRequest(final NetcdfDataset dataset, final String query, String threddsURI) throws IOException { return enhanceGETRequest(dataset, query, threddsURI, null); } /** * enhanceGETRequest - provides direct access to parsing a sos request and create handler for the type of request coming in * @param dataset NetcdfDataset to enhanceGETRequest the NCML * @param query query string provided by request * @param threddsURI * @param savePath provides a directory to cache requests for quick replies (currently unsupported) * @return * @throws IOException */ public HashMap<String, Object> enhanceGETRequest(final NetcdfDataset dataset, final String query, String threddsURI, String savePath) throws IOException { // clear anything that can cause issue if we were to use the same parser for multiple requests queryParameters = new LowerCaseStringMap(); coordsHash = new HashMap<String, String>(); if (query != null) { // parse the query string queryParameters.putAll(parseQuery(query)); } else { // we are assuming that a request made here w/o a query string is a 'GetCapabilities' request // add the request to our query parameters, as well as some other default values queryParameters.put(REQUEST, GETCAPABILITIES); queryParameters.put(SERVICE, defService); queryParameters.put(ACCEPT_VERSIONS, defVersion); } // check the query parameters to make sure all required parameters are passed in HashMap<String, Object> retval = checkQueryParameters(); if (retval.containsKey(ERROR)) { retval.put(OUTPUT_FORMATTER, errorHandler.getOutputFormatter()); return retval; } try { String request = queryParameters.get(REQUEST).toString(); if (request.equalsIgnoreCase(GETCAPABILITIES)) { GetCapabilitiesRequestHandler capHandler = null; String sections = "all"; if (queryParameters.containsKey(SECTIONS)) { sections = queryParameters.get(SECTIONS).toString(); } // check to see if cache is enabled if (queryParameters.containsKey(USECACHE) && queryParameters.get(USECACHE).toString().equals(TRUE_STRING) && savePath != null) { //Check to see if get caps exists, if it does not actual parse the file _log.debug("Cache enabled for GetCapabilities"); File f = new File(savePath + getCacheXmlFileName(threddsURI)); if (f.exists()) { //if the file exists check the modified data against current data long fileDateTime = f.lastModified(); Calendar today = Calendar.getInstance(); //if the file is older than seven days (age limit) reprocess the data if (today.getTimeInMillis() - fileDateTime > CACHE_AGE_LIMIT) { _log.debug("File is older than " + Integer.toString(numDays) + " days"); capHandler = createGetCapsCacheFile(dataset, threddsURI, savePath); capHandler.resetCapabilitiesSections(sections); } else { try { // add the cached file to the response retval.put(OUTPUT_FORMATTER, fileIsInDate(f, sections)); } catch (Exception ex) { _log.error(ex.getLocalizedMessage()); errorHandler.setException("Unable to retrieve cached get capabilities document"); retval.put(OUTPUT_FORMATTER, errorHandler.getOutputFormatter()); } } } else { _log.debug("File does NOT exist"); try { //create the file as it does not exist capHandler = createGetCapsCacheFile(dataset, threddsURI, savePath); capHandler.resetCapabilitiesSections(sections); } catch (IOException ex) { _log.error(ex.getMessage()); capHandler = null; } } } else { try { capHandler = new GetCapabilitiesRequestHandler(dataset, threddsURI, sections); } catch (IOException ex) { _log.error(ex.getMessage(), ex); capHandler = null; } } if (capHandler != null) { parseGetCaps(capHandler); retval.put(OUTPUT_FORMATTER, capHandler.getOutputFormatter()); } else if (!retval.containsKey(OUTPUT_FORMATTER)) { errorHandler.setException("Internal Error in preparing output for GetCapabilities request, received null handler."); retval.put(OUTPUT_FORMATTER, errorHandler.getOutputFormatter()); } } else if (request.equalsIgnoreCase(GETOBSERVATION)) { GetObservationRequestHandler obsHandler = null; // setup our coordsHash if (queryParameters.containsKey(LAT)) { coordsHash.put(LAT, queryParameters.get(LAT).toString()); } if (queryParameters.containsKey(LON)) { coordsHash.put(LON, queryParameters.get(LON).toString()); } if (queryParameters.containsKey(DEPTH)) { coordsHash.put(DEPTH, queryParameters.get(DEPTH).toString()); } try { String[] procedure = null; String[] eventTime = null; if (queryParameters.containsKey(PROCEDURE)) { procedure = (String[]) queryParameters.get(PROCEDURE); } if (queryParameters.containsKey(EVENT_TIME)) { eventTime = (String[]) queryParameters.get(EVENT_TIME); } // create a new handler for our get observation request and then write its result to output obsHandler = new GetObservationRequestHandler(dataset, procedure, (String) queryParameters.get(OFFERING), (String[]) queryParameters.get(OBSERVED_PROPERTY), eventTime, queryParameters.get(RESPONSE_FORMAT).toString(), coordsHash); if (obsHandler.getFeatureDataset() == null) { errorHandler.setException("NetCDF-Java can not determine the FeatureType of the dataset."); retval.put(OUTPUT_FORMATTER, errorHandler.getOutputFormatter()); return retval; } else if (obsHandler.getDatasetFeatureType() == ucar.nc2.constants.FeatureType.GRID && obsHandler.getCDMDataset() == null) { // Errors are caught internally in the obsHandler retval.put(OUTPUT_FORMATTER, obsHandler.getOutputFormatter()); return retval; } else { obsHandler.parseObservations(); } // add our handler to the return value retval.put(OUTPUT_FORMATTER, obsHandler.getOutputFormatter()); } catch (Exception ex) { _log.error("Internal Error in creating output for GetObservation request:", ex); errorHandler.setException("Internal Error in creating output for GetObservation request - " + ex.toString()); retval.put(OUTPUT_FORMATTER, errorHandler.getOutputFormatter()); } } else if (request.equalsIgnoreCase(DESCRIBESENSOR)) { try { BaseDSHandler sensorHandler; // get the first procedure String procedure = ((String[]) queryParameters.get(PROCEDURE))[0]; // create a describe sensor handler sensorHandler = new BaseDSHandler(dataset, queryParameters.get(OUTPUT_FORMAT).toString(), procedure, threddsURI, query); retval.put(OUTPUT_FORMATTER, sensorHandler.getOutputFormatter()); } catch (Exception ex) { String message = "Internal System Exception in setting up DescribeSensor response"; _log.error(message, ex); errorHandler.setException(message + " - " + LogUtils.exceptionAsString(ex)); retval.put(OUTPUT_FORMATTER, errorHandler.getOutputFormatter()); return retval; } } else { // return a 'not supported' error String message = queryParameters.get(REQUEST).toString() + " is not a supported request."; _log.error(message); errorHandler.setException(message, OPERATION_NOT_SUPPORTED, "request"); retval.put(OUTPUT_FORMATTER, errorHandler.getOutputFormatter()); return retval; } } catch (IllegalArgumentException ex) { // create a get caps response with exception String message = "Unrecognized request " + queryParameters.get("request").toString(); _log.error(message, ex); errorHandler.setException(message, INVALID_PARAMETER, "request"); retval.put(OUTPUT_FORMATTER, errorHandler.getOutputFormatter()); return retval; } return retval; } private void parseGetCaps(GetCapabilitiesRequestHandler capHandler) throws IOException { // do our parsing capHandler.parseGetCapabilitiesDocument(); } private HashMap<String, Object> parseQuery(String query) { // @TODO: this needs to be rewritten using apache commons URLEncodedUtils sadly not available until 4.0 HashMap<String, Object> queryMap = new HashMap<String, Object>(); String[] queryArguments = query.split("&"); for (String arg : queryArguments) { String[] keyVal = arg.split("="); String key; String value; try { key = URLDecoder.decode(keyVal[0], "UTF-8"); value = URLDecoder.decode(keyVal[1], "UTF-8").trim(); } catch (UnsupportedEncodingException e) { _log.info("Unsupported Encoding exception, continuing", e); continue; } if (key.equalsIgnoreCase(PROCEDURE)) { String[] howManyStation = value.split(","); queryMap.put(key.toLowerCase(), howManyStation); } else if (key.equalsIgnoreCase(RESPONSE_FORMAT)) { parseOutputFormat(RESPONSE_FORMAT, value); } else if (key.equalsIgnoreCase(OUTPUT_FORMAT)) { parseOutputFormat(OUTPUT_FORMAT, value); } else if (key.equalsIgnoreCase(EVENT_TIME)) { String[] eventtime; if (value.contains("/")) { eventtime = value.split("/"); } else { eventtime = new String[]{value}; } queryMap.put(key, eventtime); } else if (key.equalsIgnoreCase(OBSERVED_PROPERTY)) { String[] param; if (value.contains(",")) { param = value.split(","); } else { param = new String[]{value}; } queryMap.put(key, param); } else if (key.equalsIgnoreCase(ACCEPT_VERSIONS)) { String[] param; if (value.contains(",")) { param = value.split(","); } else { param = new String[]{value}; } queryMap.put(ACCEPT_VERSIONS, param); } else { queryMap.put(key, value); } } return queryMap; } public void parseOutputFormat(String fieldName, String value) { queryParameters.put(fieldName, value); } private String getCacheXmlFileName(String threddsURI) { _log.debug("thredds uri: " + threddsURI); String[] splitStr = threddsURI.split("/"); String dName = splitStr[splitStr.length - 1]; splitStr = dName.split("\\."); dName = ""; for (int i = 0; i < splitStr.length - 1; i++) { dName += splitStr[i] + "."; } return "/" + dName + XML; } private GetCapabilitiesRequestHandler createGetCapsCacheFile(NetcdfDataset dataset, String threddsURI, String savePath) throws IOException { _log.debug("Writing cache file for Get Capabilities request."); GetCapabilitiesRequestHandler cacheHandle = new GetCapabilitiesRequestHandler(dataset, threddsURI, "all"); parseGetCaps(cacheHandle); File file = new File(savePath + getCacheXmlFileName(threddsURI)); file.createNewFile(); Writer writer = new BufferedWriter(new FileWriter(file, false)); writer.flush(); cacheHandle.formatter.writeOutput(writer); _log.debug("Write cache to: " + file.getAbsolutePath()); return cacheHandle; } private OutputFormatter fileIsInDate(File f, String sections) throws ParserConfigurationException, SAXException, IOException { _log.debug("Using cached get capabilities doc"); CachedFileFormatter retval = new CachedFileFormatter(f); retval.setSections(sections); return retval; } private HashMap<String, Object> checkQueryParameters() { try { HashMap<String, Object> retval = new HashMap<String, Object>(); String[] requiredGlobalParameters = {REQUEST, SERVICE}; String[] requiredDSParameters = {PROCEDURE, OUTPUT_FORMAT, VERSION}; //required GRID Parameters String[] requiredGOParameters = {OFFERING, OBSERVED_PROPERTY, RESPONSE_FORMAT, VERSION}; // general parameters expected if (queryParameters.containsKey(ERROR)) { errorHandler.setException("Error with request - " + queryParameters.get(ERROR).toString()); retval.put(ERROR, true); return retval; } else { for (String req : requiredGlobalParameters) { if (!queryParameters.containsKey(req.toLowerCase())) { errorHandler.setException("Required parameter '" + req + "' not found. Check GetCapabilities document for required parameters.", MISSING_PARAMETER, req); retval.put(ERROR, true); return retval; } } if (!queryParameters.get(SERVICE).toString().equalsIgnoreCase(defService)) { errorHandler.setException("Currently the only supported service is SOS.", INVALID_PARAMETER, "service"); retval.put(ERROR, true); return retval; } } // specific parameters expected String request = queryParameters.get(REQUEST).toString(); if (request.equalsIgnoreCase(GETCAPABILITIES)) { // check requirements for version and service if (queryParameters.containsKey(ACCEPT_VERSIONS)) { String[] versions = null; if (queryParameters.get(ACCEPT_VERSIONS) instanceof String[]) { versions = (String[]) queryParameters.get(ACCEPT_VERSIONS); } else if (queryParameters.get(ACCEPT_VERSIONS) instanceof String) { versions = new String[]{(String) queryParameters.get(ACCEPT_VERSIONS)}; } if (versions != null && versions.length == 1) { if (!versions[0].equalsIgnoreCase(defVersion)) { errorHandler.setException("Currently only SOS version " + defVersion + " is supported.", VERSION_NEGOTIATION); retval.put(ERROR, true); return retval; } } else { errorHandler.setException("Currently only SOS version " + defVersion + " is supported.", VERSION_NEGOTIATION); retval.put(ERROR, true); return retval; } } } else if (request.equalsIgnoreCase(DESCRIBESENSOR)) { for (String req : requiredDSParameters) { if (!queryParameters.containsKey(req.toLowerCase())) { errorHandler.setException("Required parameter '" + req + "' not found. Check GetCapabilities document for required parameters of DescribeSensor requests.", MISSING_PARAMETER, req); retval.put(ERROR, true); return retval; } } // Check version if (!queryParameters.get(VERSION).equals(defVersion)) { errorHandler.setException("Currently only SOS version " + defVersion + " is supported", INVALID_PARAMETER, "version"); retval.put(ERROR, true); return retval; } } else if (request.equalsIgnoreCase(GETOBSERVATION)) { for (String req : requiredGOParameters) { if (!queryParameters.containsKey(req)) { errorHandler.setException("Required parameter '" + req + "' not found. Check GetCapabilities document for required parameters of GetObservation requests.", MISSING_PARAMETER, req); retval.put(ERROR, true); return retval; } } // Check version if (!queryParameters.get(VERSION).equals(defVersion)) { errorHandler.setException("Currently only SOS version " + defVersion + " is supported", INVALID_PARAMETER, "version"); retval.put(ERROR, true); return retval; } } return retval; } catch (Exception ex) { _log.error(ex.toString()); HashMap<String, Object> retval = new HashMap<String, Object>(); errorHandler.setException("Error in request. Check required parameters from GetCapabilities document and try again."); retval.put(ERROR, true); return retval; } } }
src/main/java/com/asascience/ncsos/service/Parser.java
package com.asascience.ncsos.service; import com.asascience.ncsos.ds.BaseDSHandler; import com.asascience.ncsos.error.ExceptionResponseHandler; import com.asascience.ncsos.gc.GetCapabilitiesRequestHandler; import com.asascience.ncsos.go.GetObservationRequestHandler; import com.asascience.ncsos.outputformatter.CachedFileFormatter; import com.asascience.ncsos.outputformatter.OutputFormatter; import com.asascience.ncsos.util.LogUtils; import com.asascience.ncsos.util.LowerCaseStringMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; import ucar.nc2.dataset.NetcdfDataset; import javax.xml.parsers.ParserConfigurationException; import java.io.*; import java.net.URLDecoder; import java.util.Calendar; import java.util.HashMap; import java.util.Map; public class Parser { public static final String ERROR = "error"; public static final String GETCAPABILITIES = "GetCapabilities"; public static final String GETOBSERVATION = "GetObservation"; public static final String DESCRIBESENSOR = "DescribeSensor"; public static final String OUTPUT_FORMATTER = "outputFormatter"; public static final String SECTIONS = "sections"; public static final String USECACHE = "usecache"; public static final String XML = "xml"; private LowerCaseStringMap queryParameters; private Logger _log; private Map<String, String> coordsHash; private final String defService = "sos"; private final String defVersion = "1.0.0"; private final String TRUE_STRING = "true"; public final static String PROCEDURE = "procedure"; public final static String ACCEPT_VERSIONS = "AcceptVersions"; public final static String VERSION = "version"; public final static String REQUEST = "request"; public final static String SERVICE = "service"; public final static String LAT = "latitude"; public final static String LON = "longitude"; public final static String DEPTH = "depth"; public final static String RESPONSE_FORMAT = "responseFormat"; public final static String OUTPUT_FORMAT = "outputFormat"; public final static String OBSERVED_PROPERTY = "observedProperty"; public final static String OFFERING = "offering"; public final static String EVENT_TIME = "eventTime"; private final int numDays = 7; // millisecs per sec * secs per hour * hour per day * day limit (1 week) private final long CACHE_AGE_LIMIT = 1000 * 3600 * 24 * numDays; // Exception codes - Table 25 of OGC 06-121r3 (OWS Common) protected static String INVALID_PARAMETER = "InvalidParameterValue"; protected static String MISSING_PARAMETER = "MissingParameterValue"; protected static String OPTION_NOT_SUPPORTED = "OptionNotSupported"; protected static String OPERATION_NOT_SUPPORTED = "OperationNotSupported"; protected static String VERSION_NEGOTIATION = "VersionNegotiationFailed"; ExceptionResponseHandler errorHandler = null; /** * Sets the logger for error output using the Parser class. */ public Parser() throws IOException { _log = LoggerFactory.getLogger(Parser.class); errorHandler = new ExceptionResponseHandler(); } /** * enhanceGETRequest - provides direct access to parsing a sos request and create handler for the type of request coming in * @param dataset NetcdfDataset to enhanceGETRequest the NCML * @param query query string provided by request * @param threddsURI * @return * @throws IOException */ public HashMap<String, Object> enhanceGETRequest(final NetcdfDataset dataset, final String query, String threddsURI) throws IOException { return enhanceGETRequest(dataset, query, threddsURI, null); } /** * enhanceGETRequest - provides direct access to parsing a sos request and create handler for the type of request coming in * @param dataset NetcdfDataset to enhanceGETRequest the NCML * @param query query string provided by request * @param threddsURI * @param savePath provides a directory to cache requests for quick replies (currently unsupported) * @return * @throws IOException */ public HashMap<String, Object> enhanceGETRequest(final NetcdfDataset dataset, final String query, String threddsURI, String savePath) throws IOException { // clear anything that can cause issue if we were to use the same parser for multiple requests queryParameters = new LowerCaseStringMap(); coordsHash = new HashMap<String, String>(); if (query != null) { // parse the query string queryParameters.putAll(parseQuery(query)); } else { // we are assuming that a request made here w/o a query string is a 'GetCapabilities' request // add the request to our query parameters, as well as some other default values queryParameters.put(REQUEST, GETCAPABILITIES); queryParameters.put(SERVICE, defService); queryParameters.put(ACCEPT_VERSIONS, defVersion); } // check the query parameters to make sure all required parameters are passed in HashMap<String, Object> retval = checkQueryParameters(); if (retval.containsKey(ERROR)) { retval.put(OUTPUT_FORMATTER, errorHandler.getOutputFormatter()); return retval; } try { String request = queryParameters.get(REQUEST).toString(); if (request.equalsIgnoreCase(GETCAPABILITIES)) { GetCapabilitiesRequestHandler capHandler = null; String sections = "all"; if (queryParameters.containsKey(SECTIONS)) { sections = queryParameters.get(SECTIONS).toString(); } // check to see if cache is enabled if (queryParameters.containsKey(USECACHE) && queryParameters.get(USECACHE).toString().equals(TRUE_STRING) && savePath != null) { //Check to see if get caps exists, if it does not actual parse the file _log.debug("Cache enabled for GetCapabilities"); File f = new File(savePath + getCacheXmlFileName(threddsURI)); if (f.exists()) { //if the file exists check the modified data against current data long fileDateTime = f.lastModified(); Calendar today = Calendar.getInstance(); //if the file is older than seven days (age limit) reprocess the data if (today.getTimeInMillis() - fileDateTime > CACHE_AGE_LIMIT) { _log.debug("File is older than " + Integer.toString(numDays) + " days"); capHandler = createGetCapsCacheFile(dataset, threddsURI, savePath); capHandler.resetCapabilitiesSections(sections); } else { try { // add the cached file to the response retval.put(OUTPUT_FORMATTER, fileIsInDate(f, sections)); } catch (Exception ex) { _log.error(ex.getLocalizedMessage()); errorHandler.setException("Unable to retrieve cached get capabilities document"); retval.put(OUTPUT_FORMATTER, errorHandler.getOutputFormatter()); } } } else { _log.debug("File does NOT exist"); try { //create the file as it does not exist capHandler = createGetCapsCacheFile(dataset, threddsURI, savePath); capHandler.resetCapabilitiesSections(sections); } catch (IOException ex) { _log.error(ex.getMessage()); capHandler = null; } } } else { try { capHandler = new GetCapabilitiesRequestHandler(dataset, threddsURI, sections); } catch (IOException ex) { _log.error(ex.getMessage(), ex); capHandler = null; } } if (capHandler != null) { parseGetCaps(capHandler); retval.put(OUTPUT_FORMATTER, capHandler.getOutputFormatter()); } else if (!retval.containsKey(OUTPUT_FORMATTER)) { errorHandler.setException("Internal Error in preparing output for GetCapabilities request, received null handler."); retval.put(OUTPUT_FORMATTER, errorHandler.getOutputFormatter()); } } else if (request.equalsIgnoreCase(GETOBSERVATION)) { GetObservationRequestHandler obsHandler = null; // setup our coordsHash if (queryParameters.containsKey(LAT)) { coordsHash.put(LAT, queryParameters.get(LAT).toString()); } if (queryParameters.containsKey(LON)) { coordsHash.put(LON, queryParameters.get(LON).toString()); } if (queryParameters.containsKey(DEPTH)) { coordsHash.put(DEPTH, queryParameters.get(DEPTH).toString()); } try { String[] procedure = null; String[] eventTime = null; if (queryParameters.containsKey(PROCEDURE)) { procedure = (String[]) queryParameters.get(PROCEDURE); } if (queryParameters.containsKey(EVENT_TIME)) { eventTime = (String[]) queryParameters.get(EVENT_TIME); } // create a new handler for our get observation request and then write its result to output obsHandler = new GetObservationRequestHandler(dataset, procedure, (String) queryParameters.get(OFFERING), (String[]) queryParameters.get(OBSERVED_PROPERTY), eventTime, queryParameters.get(RESPONSE_FORMAT).toString(), coordsHash); if (obsHandler.getFeatureDataset() == null) { errorHandler.setException("NetCDF-Java can not determine the FeatureType of the dataset."); retval.put(OUTPUT_FORMATTER, errorHandler.getOutputFormatter()); return retval; } else if (obsHandler.getDatasetFeatureType() == ucar.nc2.constants.FeatureType.GRID && obsHandler.getCDMDataset() == null) { // Errors are caught internally in the obsHandler retval.put(OUTPUT_FORMATTER, obsHandler.getOutputFormatter()); return retval; } else { obsHandler.parseObservations(); } // add our handler to the return value retval.put(OUTPUT_FORMATTER, obsHandler.getOutputFormatter()); } catch (Exception ex) { _log.error("Internal Error in creating output for GetObservation request:", ex); errorHandler.setException("Internal Error in creating output for GetObservation request - " + ex.toString()); retval.put(OUTPUT_FORMATTER, errorHandler.getOutputFormatter()); } } else if (request.equalsIgnoreCase(DESCRIBESENSOR)) { try { BaseDSHandler sensorHandler; // get the first procedure String procedure = ((String[]) queryParameters.get(PROCEDURE))[0]; // create a describe sensor handler sensorHandler = new BaseDSHandler(dataset, queryParameters.get(OUTPUT_FORMAT).toString(), procedure, threddsURI, query); retval.put(OUTPUT_FORMATTER, sensorHandler.getOutputFormatter()); } catch (Exception ex) { String message = "Internal System Exception in setting up DescribeSensor response"; _log.error(message, ex); errorHandler.setException(message + " - " + LogUtils.exceptionAsString(ex)); retval.put(OUTPUT_FORMATTER, errorHandler.getOutputFormatter()); return retval; } } else { // return a 'not supported' error String message = queryParameters.get(REQUEST).toString() + " is not a supported request."; _log.error(message); errorHandler.setException(message, OPERATION_NOT_SUPPORTED, "request"); retval.put(OUTPUT_FORMATTER, errorHandler.getOutputFormatter()); return retval; } } catch (IllegalArgumentException ex) { // create a get caps response with exception String message = "Unrecognized request " + queryParameters.get("request").toString(); _log.error(message, ex); errorHandler.setException(message, INVALID_PARAMETER, "request"); retval.put(OUTPUT_FORMATTER, errorHandler.getOutputFormatter()); return retval; } return retval; } private void parseGetCaps(GetCapabilitiesRequestHandler capHandler) throws IOException { // do our parsing capHandler.parseGetCapabilitiesDocument(); } private HashMap<String, Object> parseQuery(String query) { // @TODO: this needs to be rewritten using apache commons URLEncodedUtils sadly not available until 4.0 HashMap<String, Object> queryMap = new HashMap<String, Object>(); String[] queryArguments = query.split("&"); for (String arg : queryArguments) { String[] keyVal = arg.split("="); String key; String value; try { key = URLDecoder.decode(keyVal[0], "UTF-8"); value = URLDecoder.decode(keyVal[1], "UTF-8").trim(); } catch (UnsupportedEncodingException e) { _log.info("Unsupported Encoding exception, continuing", e); continue; } if (key.equalsIgnoreCase(PROCEDURE)) { String[] howManyStation = value.split(","); queryMap.put(key.toLowerCase(), howManyStation); } else if (key.equalsIgnoreCase(RESPONSE_FORMAT)) { parseOutputFormat(RESPONSE_FORMAT, value); } else if (key.equalsIgnoreCase(OUTPUT_FORMAT)) { parseOutputFormat(OUTPUT_FORMAT, value); } else if (key.equalsIgnoreCase(EVENT_TIME)) { String[] eventtime; if (value.contains("/")) { eventtime = value.split("/"); } else { eventtime = new String[]{value}; } queryMap.put(key, eventtime); } else if (key.equalsIgnoreCase(OBSERVED_PROPERTY)) { String[] param; if (value.contains(",")) { param = value.split(","); } else { param = new String[]{value}; } queryMap.put(key, param); } else if (key.equalsIgnoreCase(ACCEPT_VERSIONS)) { String[] param; if (value.contains(",")) { param = value.split(","); } else { param = new String[]{value}; } queryMap.put(ACCEPT_VERSIONS, param); } else { queryMap.put(key, value); } } return queryMap; } public void parseOutputFormat(String fieldName, String value) { queryParameters.put(fieldName, value); } private String getCacheXmlFileName(String threddsURI) { _log.debug("thredds uri: " + threddsURI); String[] splitStr = threddsURI.split("/"); String dName = splitStr[splitStr.length - 1]; splitStr = dName.split("\\."); dName = ""; for (int i = 0; i < splitStr.length - 1; i++) { dName += splitStr[i] + "."; } return "/" + dName + XML; } private GetCapabilitiesRequestHandler createGetCapsCacheFile(NetcdfDataset dataset, String threddsURI, String savePath) throws IOException { _log.debug("Writing cache file for Get Capabilities request."); GetCapabilitiesRequestHandler cacheHandle = new GetCapabilitiesRequestHandler(dataset, threddsURI, "all"); parseGetCaps(cacheHandle); File file = new File(savePath + getCacheXmlFileName(threddsURI)); file.createNewFile(); Writer writer = new BufferedWriter(new FileWriter(file, false)); writer.flush(); cacheHandle.formatter.writeOutput(writer); _log.debug("Write cache to: " + file.getAbsolutePath()); return cacheHandle; } private OutputFormatter fileIsInDate(File f, String sections) throws ParserConfigurationException, SAXException, IOException { _log.debug("Using cached get capabilities doc"); CachedFileFormatter retval = new CachedFileFormatter(f); retval.setSections(sections); return retval; } private HashMap<String, Object> checkQueryParameters() { try { HashMap<String, Object> retval = new HashMap<String, Object>(); String[] requiredGlobalParameters = {REQUEST, SERVICE}; String[] requiredDSParameters = {PROCEDURE, OUTPUT_FORMAT, VERSION}; //required GRID Parameters String[] requiredGOParameters = {OFFERING, OBSERVED_PROPERTY, RESPONSE_FORMAT, VERSION}; // general parameters expected if (queryParameters.containsKey(ERROR)) { errorHandler.setException("Error with request - " + queryParameters.get(ERROR).toString()); retval.put(ERROR, true); return retval; } else { for (String req : requiredGlobalParameters) { if (!queryParameters.containsKey(req.toLowerCase())) { errorHandler.setException("Required parameter '" + req + "' not found. Check GetCapabilities document for required parameters.", MISSING_PARAMETER, req); retval.put(ERROR, true); return retval; } } if (!queryParameters.get(SERVICE).toString().equalsIgnoreCase(defService)) { errorHandler.setException("Currently the only supported service is SOS.", OPERATION_NOT_SUPPORTED, "service"); retval.put(ERROR, true); return retval; } } // specific parameters expected String request = queryParameters.get(REQUEST).toString(); if (request.equalsIgnoreCase(GETCAPABILITIES)) { // check requirements for version and service if (queryParameters.containsKey(ACCEPT_VERSIONS)) { String[] versions = null; if (queryParameters.get(ACCEPT_VERSIONS) instanceof String[]) { versions = (String[]) queryParameters.get(ACCEPT_VERSIONS); } else if (queryParameters.get(ACCEPT_VERSIONS) instanceof String) { versions = new String[]{(String) queryParameters.get(ACCEPT_VERSIONS)}; } if (versions != null && versions.length == 1) { if (!versions[0].equalsIgnoreCase(defVersion)) { errorHandler.setException("Currently only SOS version " + defVersion + " is supported.", VERSION_NEGOTIATION); retval.put(ERROR, true); return retval; } } else { errorHandler.setException("Currently only SOS version " + defVersion + " is supported.", VERSION_NEGOTIATION); retval.put(ERROR, true); return retval; } } } else if (request.equalsIgnoreCase(DESCRIBESENSOR)) { for (String req : requiredDSParameters) { if (!queryParameters.containsKey(req.toLowerCase())) { errorHandler.setException("Required parameter '" + req + "' not found. Check GetCapabilities document for required parameters of DescribeSensor requests.", MISSING_PARAMETER, req); retval.put(ERROR, true); return retval; } } // Check version if (!queryParameters.get(VERSION).equals(defVersion)) { errorHandler.setException("Currently only SOS version " + defVersion + " is supported", INVALID_PARAMETER, "version"); retval.put(ERROR, true); return retval; } } else if (request.equalsIgnoreCase(GETOBSERVATION)) { for (String req : requiredGOParameters) { if (!queryParameters.containsKey(req)) { errorHandler.setException("Required parameter '" + req + "' not found. Check GetCapabilities document for required parameters of GetObservation requests.", MISSING_PARAMETER, req); retval.put(ERROR, true); return retval; } } // Check version if (!queryParameters.get(VERSION).equals(defVersion)) { errorHandler.setException("Currently only SOS version " + defVersion + " is supported", INVALID_PARAMETER, "version"); retval.put(ERROR, true); return retval; } } return retval; } catch (Exception ex) { _log.error(ex.toString()); HashMap<String, Object> retval = new HashMap<String, Object>(); errorHandler.setException("Error in request. Check required parameters from GetCapabilities document and try again."); retval.put(ERROR, true); return retval; } } }
Respond with InvalidParameter if service is not SOS, fixes #127
src/main/java/com/asascience/ncsos/service/Parser.java
Respond with InvalidParameter if service is not SOS, fixes #127
<ide><path>rc/main/java/com/asascience/ncsos/service/Parser.java <ide> } <ide> <ide> if (!queryParameters.get(SERVICE).toString().equalsIgnoreCase(defService)) { <del> errorHandler.setException("Currently the only supported service is SOS.", OPERATION_NOT_SUPPORTED, "service"); <add> errorHandler.setException("Currently the only supported service is SOS.", INVALID_PARAMETER, "service"); <ide> retval.put(ERROR, true); <ide> return retval; <ide> }
JavaScript
mpl-2.0
f0c244def5d464592edf787ab0012494aedaef4d
0
CrystalGamma/quiz-battle,CrystalGamma/quiz-battle,CrystalGamma/quiz-battle
const showGame = login => url => { const $game = buildDom({'':'a.game', href: url}); makeXHR('GET', url, {Accept: 'application/json'}, xhr => { if (xhr.status < 200 || xhr.status >= 300) {return} const ct = xhr.getResponseHeader('Content-Type'); if (ct !== 'application/json') {console.error(`Wrong content type: ${ct}`);return} const game = JSON.parse(xhr.responseText); let selfPlayer = null; game.players.forEach((player, idx) => {if (player[''] === (login.player_||login.player[''])) {selfPlayer = idx}}); if (selfPlayer === null) { $game.parentNode.removeChild($game); // game was concurrently rejected return; } const scores = game.players.map(() => 0); game.questions.forEach(question => question && question.answers.forEach((status, player) => scores[player]+=0|(status === 0))); let bestPlayer = null, bestScore = -1; scores.forEach((score, idx) => {if (score > bestScore && idx != selfPlayer) {bestPlayer = idx;bestScore=score}}); const title = game.players.length > 2 ? [game.players[bestPlayer].name] : [{'':'span.player', c:game.players[bestPlayer].name}, ` und ${game.players.length-2} weitere`]; buildDom(title).forEach(x => $game.appendChild(x)); $game.appendChild(buildDom({'':'span.game-points'+( scores[selfPlayer] > bestScore ? '.winning' : scores[selfPlayer] < bestScore ? '.losing' : '.tied' ), c:`${scores[selfPlayer]} – ${bestScore}`})); const lookup = x => ( x === 0 ? 'g' : x === null ? '-' : 'b' ); $game.appendChild(buildDom({'':'ul.game-report', c:game.questions.map(({answers}) => ({'':'li.'+lookup(answers[selfPlayer])+lookup(answers[bestPlayer])}))})); }).send(); return buildDom({'':'li', c:$game}); };
public/static/game-report.js
const showGame = login => url => { const $game = buildDom({'':'a.game', href: url}); makeXHR('GET', url, {Accept: 'application/json'}, xhr => { if (xhr.status < 200 || xhr.status >= 300) {return} const ct = xhr.getResponseHeader('Content-Type'); if (ct !== 'application/json') {console.error(`Wrong content type: ${ct}`);return} const game = JSON.parse(xhr.responseText); let selfPlayer = null; game.players.forEach((player, idx) => {if (player[''] === (login.player_||login.player[''])) {selfPlayer = idx}}); if (selfPlayer === null) { $game.parentNode.removeChild($game); // game was concurrently rejected return; } const scores = game.players.map(() => 0); game.questions.forEach(question => question && question.answers.forEach((status, player) => scores[player]+=0|(status === 0))); let bestPlayer = null, bestScore = -1; scores.forEach((score, idx) => {if (score > bestScore && idx != selfPlayer) {bestPlayer = idx;bestScore=score}}); const title = game.players.length > 2 ? [game.players[bestPlayer].name] : [{'':'span.player', c:game.players[bestPlayer].name}, ` und ${game.players.length-2} weitere`]; buildDom(title).forEach(x => $game.appendChild(x)); $game.appendChild(buildDom({'':'span.game-points'+( scores[selfPlayer] > bestScore ? '.winning' : scores[selfPlayer] < bestScore ? '.losing' : '.tied' ), c:`${scores[selfPlayer]} – ${bestScore}`})); const lookup = x => ( x === 0 ? 'g' : x === null ? '-' : 'b' ); $game.appendChild(buildDom({'':'ul.game-report', c:game.questions.map(({answers}) => ({'':'li.'+lookup(answers[selfPlayer])+lookup(answers[bestPlayer])}))})); }).send(); const res = buildDom({'':'li', c:$game}); return res; };
cleanup
public/static/game-report.js
cleanup
<ide><path>ublic/static/game-report.js <ide> ); <ide> $game.appendChild(buildDom({'':'ul.game-report', c:game.questions.map(({answers}) => ({'':'li.'+lookup(answers[selfPlayer])+lookup(answers[bestPlayer])}))})); <ide> }).send(); <del> const res = buildDom({'':'li', c:$game}); <del> return res; <add> return buildDom({'':'li', c:$game}); <ide> };
Java
apache-2.0
728412415c2c8f2a03f7abc28e41a1be73ee923f
0
cadrian/jsonref,cadrian/jsonref
/* Copyright 2015 Cyril Adrian <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package net.cadrian.jsonref; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class TestDeserializationProcessor { private DeserializationProcessor that; @Mock private JsonConverter converter; @Before public void setup() { that = new DeserializationProcessor(); } @Test public void testInteger() { when(converter.fromJson("42", Integer.class)).thenReturn(42); when(converter.fromJson("42", int.class)).thenReturn(13); when(converter.fromJson("42", null)).thenReturn(421); Integer i = that.deserialize("42", converter, Integer.class); assertEquals(Integer.valueOf(42), i); i = that.deserialize("42", converter, int.class); assertEquals(13, i.intValue()); i = that.deserialize("42", converter, null); assertEquals(421, i.intValue()); } @Test public void testString() { when(converter.fromJson("\"foo\"", String.class)).thenReturn("bar"); final String s = that.deserialize("\"foo\"", converter, String.class); assertEquals("bar", s); } @Test public void testDate() { final Date now = new Date(); when(converter.fromJson("\"foo\"", Date.class)).thenReturn(now); final Date d = that.deserialize("\"foo\"", converter, Date.class); assertEquals(now, d); } @Test public void testArrayOfObjects() { final Date now = new Date(); when(converter.fromJson("\"now\"", Object.class)).thenReturn(now); final String string = "foobar"; when(converter.fromJson("\"string\"", Object.class)).thenReturn(string); final Object[] objects = that.deserialize("[\"now\",\"string\"]", converter, Object[].class); assertEquals(now, objects[0]); assertEquals(string, objects[1]); } @Test public void testArrayOfStrings() { final String string1 = "foo"; when(converter.fromJson("\"string1\"", String.class)).thenReturn( string1); final String string2 = "bar"; when(converter.fromJson("\"string2\"", String.class)).thenReturn( string2); final String[] strings = that.deserialize("[\"string1\",\"string2\"]", converter, String[].class); assertEquals(string1, strings[0]); assertEquals(string2, strings[1]); } @Test @SuppressWarnings("unchecked") public void testCollection() { final String string1 = "foo"; when(converter.fromJson("\"string1\"", null)).thenReturn(string1); final String string2 = "bar"; when(converter.fromJson("\"string2\"", null)).thenReturn(string2); when( converter .newCollection((Class<? extends Collection<Object>>) Collection.class)) .thenReturn(new ArrayList<Object>()); final Collection<?> objects = that.deserialize( "[\"string1\",\"string2\"]", converter, Collection.class); assertEquals(2, objects.size()); final Iterator<?> iterator = objects.iterator(); assertEquals(string1, iterator.next()); assertEquals(string2, iterator.next()); } @Test @SuppressWarnings("unchecked") public void testMapOfStringsInJsonArray() { final String string1 = "foo"; when(converter.fromJson("\"string1\"", null)).thenReturn(string1); final String string2 = "bar"; when(converter.fromJson("\"string2\"", null)).thenReturn(string2); when(converter.newMap((Class<? extends Map<Object, Object>>) Map.class)) .thenReturn(new HashMap<Object, Object>()); final Map<?, ?> objects = that.deserialize( "[[\"string1\",\"string2\"],[\"string2\",\"string1\"]]", converter, Map.class); assertEquals(2, objects.size()); assertEquals(string1, objects.get(string2)); assertEquals(string2, objects.get(string1)); } @Test @SuppressWarnings("unchecked") public void testMapOfStringsInJsonObject() { final String string1 = "foo"; when(converter.fromJson("\"string1\"", String.class)).thenReturn( string1); when(converter.fromJson("\"string1\"", null)).thenReturn(string1); final String string2 = "bar"; when(converter.fromJson("\"string2\"", String.class)).thenReturn( string2); when(converter.fromJson("\"string2\"", null)).thenReturn(string2); when(converter.newMap((Class<? extends Map<Object, Object>>) Map.class)) .thenReturn(new HashMap<Object, Object>()); final Map<?, ?> objects = that.deserialize( "{\"string1\":\"string2\",\"string2\":\"string1\"}", converter, Map.class); assertEquals(2, objects.size()); assertEquals(string1, objects.get(string2)); assertEquals(string2, objects.get(string1)); } @Test @SuppressWarnings("unchecked") public void testMapOfObjects() { final String string1 = "foo"; when(converter.fromJson("\"string1\"", null)).thenReturn(string1); final String string2 = "bar"; when(converter.fromJson("\"string2\"", null)).thenReturn(string2); final Date now = new Date(); when(converter.fromJson("1", null)).thenReturn(now); final Integer dontPanic = Integer.valueOf(42); when(converter.fromJson("2", null)).thenReturn(dontPanic); when(converter.newMap((Class<? extends Map<Object, Object>>) Map.class)) .thenReturn(new HashMap<Object, Object>()); final Map<?, ?> objects = that.deserialize( "[[1,\"string1\"],[2,\"string2\"]]", converter, Map.class); assertEquals(2, objects.size()); assertEquals(string1, objects.get(now)); assertEquals(string2, objects.get(dontPanic)); } }
jsonref-core/src/test/java/net/cadrian/jsonref/TestDeserializationProcessor.java
/* Copyright 2015 Cyril Adrian <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package net.cadrian.jsonref; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class TestDeserializationProcessor { private DeserializationProcessor that; @Mock private JsonConverter converter; @Before public void setup() { that = new DeserializationProcessor(); } @Test public void testInteger() { when(converter.fromJson("42", Integer.class)).thenReturn(42); when(converter.fromJson("42", int.class)).thenReturn(13); when(converter.fromJson("42", null)).thenReturn(421); Integer i = that.deserialize("42", converter, Integer.class); assertEquals(Integer.valueOf(42), i); i = that.deserialize("42", converter, int.class); assertEquals(13, i.intValue()); i = that.deserialize("42", converter, null); assertEquals(421, i.intValue()); } @Test public void testString() { when(converter.fromJson("\"foo\"", String.class)).thenReturn("bar"); final String s = that.deserialize("\"foo\"", converter, String.class); assertEquals("bar", s); } @Test public void testDate() { final Date now = new Date(); when(converter.fromJson("\"foo\"", Date.class)).thenReturn(now); final Date d = that.deserialize("\"foo\"", converter, Date.class); assertEquals(now, d); } @Test public void testArrayOfObjects() { final Date now = new Date(); when(converter.fromJson("\"now\"", Object.class)).thenReturn(now); final String string = "foobar"; when(converter.fromJson("\"string\"", Object.class)).thenReturn(string); final Object[] objects = that.deserialize("[\"now\",\"string\"]", converter, Object[].class); assertEquals(now, objects[0]); assertEquals(string, objects[1]); } @Test public void testArrayOfStrings() { final String string1 = "foo"; when(converter.fromJson("\"string1\"", String.class)).thenReturn( string1); final String string2 = "bar"; when(converter.fromJson("\"string2\"", String.class)).thenReturn( string2); final String[] strings = that.deserialize("[\"string1\",\"string2\"]", converter, String[].class); assertEquals(string1, strings[0]); assertEquals(string2, strings[1]); } @Test @SuppressWarnings("unchecked") public void testCollection() { final String string1 = "foo"; when(converter.fromJson("\"string1\"", null)).thenReturn(string1); final String string2 = "bar"; when(converter.fromJson("\"string2\"", null)).thenReturn(string2); when( converter .newCollection((Class<? extends Collection<Object>>) Collection.class)) .thenReturn(new ArrayList<Object>()); final Collection<?> objects = that.deserialize( "[\"string1\",\"string2\"]", converter, Collection.class); assertEquals(2, objects.size()); final Iterator<?> iterator = objects.iterator(); assertEquals(string1, iterator.next()); assertEquals(string2, iterator.next()); } @Test @SuppressWarnings("unchecked") public void testMapOfStrings() { final String string1 = "foo"; when(converter.fromJson("\"string1\"", null)).thenReturn(string1); final String string2 = "bar"; when(converter.fromJson("\"string2\"", null)).thenReturn(string2); when(converter.newMap((Class<? extends Map<Object, Object>>) Map.class)) .thenReturn(new HashMap<Object, Object>()); final Map<?, ?> objects = that.deserialize( "[[\"string1\",\"string2\"],[\"string2\",\"string1\"]]", converter, Map.class); assertEquals(2, objects.size()); assertEquals(string1, objects.get(string2)); assertEquals(string2, objects.get(string1)); } @Test public void testMapOfObjects() { // TODO } }
more tests
jsonref-core/src/test/java/net/cadrian/jsonref/TestDeserializationProcessor.java
more tests
<ide><path>sonref-core/src/test/java/net/cadrian/jsonref/TestDeserializationProcessor.java <ide> <ide> @Test <ide> @SuppressWarnings("unchecked") <del> public void testMapOfStrings() { <add> public void testMapOfStringsInJsonArray() { <ide> final String string1 = "foo"; <ide> when(converter.fromJson("\"string1\"", null)).thenReturn(string1); <ide> final String string2 = "bar"; <ide> } <ide> <ide> @Test <add> @SuppressWarnings("unchecked") <add> public void testMapOfStringsInJsonObject() { <add> final String string1 = "foo"; <add> when(converter.fromJson("\"string1\"", String.class)).thenReturn( <add> string1); <add> when(converter.fromJson("\"string1\"", null)).thenReturn(string1); <add> final String string2 = "bar"; <add> when(converter.fromJson("\"string2\"", String.class)).thenReturn( <add> string2); <add> when(converter.fromJson("\"string2\"", null)).thenReturn(string2); <add> when(converter.newMap((Class<? extends Map<Object, Object>>) Map.class)) <add> .thenReturn(new HashMap<Object, Object>()); <add> <add> final Map<?, ?> objects = that.deserialize( <add> "{\"string1\":\"string2\",\"string2\":\"string1\"}", converter, <add> Map.class); <add> assertEquals(2, objects.size()); <add> assertEquals(string1, objects.get(string2)); <add> assertEquals(string2, objects.get(string1)); <add> } <add> <add> @Test <add> @SuppressWarnings("unchecked") <ide> public void testMapOfObjects() { <del> // TODO <add> final String string1 = "foo"; <add> when(converter.fromJson("\"string1\"", null)).thenReturn(string1); <add> final String string2 = "bar"; <add> when(converter.fromJson("\"string2\"", null)).thenReturn(string2); <add> final Date now = new Date(); <add> when(converter.fromJson("1", null)).thenReturn(now); <add> final Integer dontPanic = Integer.valueOf(42); <add> when(converter.fromJson("2", null)).thenReturn(dontPanic); <add> when(converter.newMap((Class<? extends Map<Object, Object>>) Map.class)) <add> .thenReturn(new HashMap<Object, Object>()); <add> <add> final Map<?, ?> objects = that.deserialize( <add> "[[1,\"string1\"],[2,\"string2\"]]", converter, Map.class); <add> assertEquals(2, objects.size()); <add> assertEquals(string1, objects.get(now)); <add> assertEquals(string2, objects.get(dontPanic)); <ide> } <ide> <ide> }
Java
mit
fb0f1da0f27c8fd03ef65c631806c63ddfa23b1c
0
rebeccahughes/react-native-device-info,rebeccahughes/react-native-device-info,rebeccahughes/react-native-device-info,rebeccahughes/react-native-device-info,rebeccahughes/react-native-device-info,rebeccahughes/react-native-device-info
package com.learnium.RNDeviceInfo; import android.Manifest; import android.annotation.SuppressLint; import android.app.KeyguardManager; import android.app.UiModeManager; import android.bluetooth.BluetoothAdapter; import android.content.Context; import android.content.SharedPreferences; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.FeatureInfo; import android.content.res.Configuration; import android.location.LocationManager; import android.net.wifi.WifiManager; import android.net.wifi.WifiInfo; import android.os.AsyncTask; import android.os.Build; import android.os.Environment; import android.os.StatFs; import android.os.BatteryManager; import android.provider.Settings; import android.view.WindowManager; import android.webkit.WebSettings; import android.telephony.TelephonyManager; import android.text.format.Formatter; import android.text.TextUtils; import android.app.ActivityManager; import android.util.DisplayMetrics; import android.hardware.Camera; import android.hardware.camera2.CameraManager; import android.hardware.camera2.CameraAccessException; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Arrays; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import java.lang.Runtime; import java.net.NetworkInterface; import java.math.BigInteger; import java.util.concurrent.ExecutionException; import javax.annotation.Nullable; public class RNDeviceModule extends ReactContextBaseJavaModule { ReactApplicationContext reactContext; WifiInfo wifiInfo; DeviceType deviceType; Map<String, Object> constants; AsyncTask<Void, Void, Map<String, Object>> futureConstants; public RNDeviceModule(ReactApplicationContext reactContext, boolean loadConstantsAsynchronously) { super(reactContext); this.reactContext = reactContext; this.deviceType = getDeviceType(reactContext); if (loadConstantsAsynchronously) { this.futureConstants = new AsyncTask<Void, Void, Map<String, Object>>() { @Override protected Map<String, Object> doInBackground(Void... args) { return generateConstants(); } }.execute(); } else { this.constants = generateConstants(); } } @Override public String getName() { return "RNDeviceInfo"; } private WifiInfo getWifiInfo() { if (this.wifiInfo == null) { WifiManager manager = (WifiManager) reactContext.getApplicationContext().getSystemService(Context.WIFI_SERVICE); this.wifiInfo = manager.getConnectionInfo(); } return this.wifiInfo; } private String getCurrentLanguage() { Locale current; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { current = getReactApplicationContext().getResources().getConfiguration().getLocales().get(0); } else { current = getReactApplicationContext().getResources().getConfiguration().locale; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return current.toLanguageTag(); } else { StringBuilder builder = new StringBuilder(); builder.append(current.getLanguage()); if (current.getCountry() != null) { builder.append("-"); builder.append(current.getCountry()); } return builder.toString(); } } private ArrayList<String> getPreferredLocales() { Configuration configuration = getReactApplicationContext().getResources().getConfiguration(); ArrayList<String> preferred = new ArrayList<>(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { for (int i = 0; i < configuration.getLocales().size(); i++) { preferred.add(configuration.getLocales().get(i).getLanguage()); } } else { preferred.add(configuration.locale.getLanguage()); } return preferred; } private String getCurrentCountry() { Locale current; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { current = getReactApplicationContext().getResources().getConfiguration().getLocales().get(0); } else { current = getReactApplicationContext().getResources().getConfiguration().locale; } return current.getCountry(); } private Boolean isEmulator() { return Build.FINGERPRINT.startsWith("generic") || Build.FINGERPRINT.startsWith("unknown") || Build.MODEL.contains("google_sdk") || Build.MODEL.toLowerCase().contains("droid4x") || Build.MODEL.contains("Emulator") || Build.MODEL.contains("Android SDK built for x86") || Build.MANUFACTURER.contains("Genymotion") || Build.HARDWARE.contains("goldfish") || Build.HARDWARE.contains("ranchu") || Build.HARDWARE.contains("vbox86") || Build.PRODUCT.contains("sdk") || Build.PRODUCT.contains("google_sdk") || Build.PRODUCT.contains("sdk_google") || Build.PRODUCT.contains("sdk_x86") || Build.PRODUCT.contains("vbox86p") || Build.PRODUCT.contains("emulator") || Build.PRODUCT.contains("simulator") || Build.BOARD.toLowerCase().contains("nox") || Build.BOOTLOADER.toLowerCase().contains("nox") || Build.HARDWARE.toLowerCase().contains("nox") || Build.PRODUCT.toLowerCase().contains("nox") || Build.SERIAL.toLowerCase().contains("nox") || (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic")); } private Boolean isTablet() { return deviceType == DeviceType.TABLET; } private static DeviceType getDeviceType(ReactApplicationContext reactContext) { // Detect TVs via ui mode (Android TVs) or system features (Fire TV). if (reactContext.getApplicationContext().getPackageManager().hasSystemFeature("amazon.hardware.fire_tv")) { return DeviceType.TV; } UiModeManager uiManager = (UiModeManager) reactContext.getSystemService(Context.UI_MODE_SERVICE); if (uiManager != null && uiManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION) { return DeviceType.TV; } return getDeviceTypeFromPhysicalSize(reactContext); } private static DeviceType getDeviceTypeFromPhysicalSize(ReactApplicationContext reactContext) { // Find the current window manager, if none is found we can't measure the device physical size. WindowManager windowManager = (WindowManager) reactContext.getSystemService(Context.WINDOW_SERVICE); if (windowManager == null) { return DeviceType.UNKNOWN; } // Get display metrics to see if we can differentiate handsets and tablets. // NOTE: for API level 16 the metrics will exclude window decor. DisplayMetrics metrics = new DisplayMetrics(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { windowManager.getDefaultDisplay().getRealMetrics(metrics); } else { windowManager.getDefaultDisplay().getMetrics(metrics); } // Calculate physical size. double widthInches = metrics.widthPixels / (double) metrics.xdpi; double heightInches = metrics.heightPixels / (double) metrics.ydpi; double diagonalSizeInches = Math.sqrt(Math.pow(widthInches, 2) + Math.pow(heightInches, 2)); if (diagonalSizeInches >= 3.0 && diagonalSizeInches <= 6.9) { // Devices in a sane range for phones are considered to be Handsets. return DeviceType.HANDSET; } else if (diagonalSizeInches > 6.9 && diagonalSizeInches <= 18.0) { // Devices larger than handset and in a sane range for tablets are tablets. return DeviceType.TABLET; } else { // Otherwise, we don't know what device type we're on/ return DeviceType.UNKNOWN; } } private float fontScale() { return getReactApplicationContext().getResources().getConfiguration().fontScale; } private Boolean is24Hour() { return android.text.format.DateFormat.is24HourFormat(this.reactContext.getApplicationContext()); } @ReactMethod public void isPinOrFingerprintSet(Callback callback) { KeyguardManager keyguardManager = (KeyguardManager) this.reactContext.getApplicationContext().getSystemService(Context.KEYGUARD_SERVICE); //api 16+ callback.invoke(keyguardManager.isKeyguardSecure()); } @ReactMethod public void getIpAddress(Promise p) { String ipAddress = Formatter.formatIpAddress(getWifiInfo().getIpAddress()); p.resolve(ipAddress); } @ReactMethod public void getCameraPresence(Promise p) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { CameraManager manager=(CameraManager)getReactApplicationContext().getSystemService(Context.CAMERA_SERVICE); try { p.resolve(manager.getCameraIdList().length > 0); } catch (CameraAccessException e) { p.reject(e); } } else { p.resolve(Camera.getNumberOfCameras()> 0); } } @ReactMethod public void getMacAddress(Promise p) { String macAddress = getWifiInfo().getMacAddress(); String permission = "android.permission.INTERNET"; int res = this.reactContext.checkCallingOrSelfPermission(permission); if (res == PackageManager.PERMISSION_GRANTED) { try { List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface nif : all) { if (!nif.getName().equalsIgnoreCase("wlan0")) continue; byte[] macBytes = nif.getHardwareAddress(); if (macBytes == null) { macAddress = ""; } else { StringBuilder res1 = new StringBuilder(); for (byte b : macBytes) { res1.append(String.format("%02X:",b)); } if (res1.length() > 0) { res1.deleteCharAt(res1.length() - 1); } macAddress = res1.toString(); } } } catch (Exception ex) { } } p.resolve(macAddress); } @ReactMethod public String getCarrier() { TelephonyManager telMgr = (TelephonyManager) this.reactContext.getSystemService(Context.TELEPHONY_SERVICE); return telMgr.getNetworkOperatorName(); } @ReactMethod public BigInteger getTotalDiskCapacity() { try { StatFs root = new StatFs(Environment.getRootDirectory().getAbsolutePath()); return BigInteger.valueOf(root.getBlockCount()).multiply(BigInteger.valueOf(root.getBlockSize())); } catch (Exception e) { e.printStackTrace(); } return null; } @ReactMethod public BigInteger getFreeDiskStorage() { try { StatFs external = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath()); long availableBlocks; long blockSize; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) { availableBlocks = external.getAvailableBlocks(); blockSize = external.getBlockSize(); } else { availableBlocks = external.getAvailableBlocksLong(); blockSize = external.getBlockSizeLong(); } return BigInteger.valueOf(availableBlocks).multiply(BigInteger.valueOf(blockSize)); } catch (Exception e) { e.printStackTrace(); } return null; } @ReactMethod public void isBatteryCharging(Promise p){ IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = this.reactContext.getApplicationContext().registerReceiver(null, ifilter); int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING; p.resolve(isCharging); } @ReactMethod public void getBatteryLevel(Promise p) { Intent batteryIntent = this.reactContext.getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); float batteryLevel = level / (float) scale; p.resolve(batteryLevel); } @ReactMethod public void isAirPlaneMode(Promise p) { boolean isAirPlaneMode; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { isAirPlaneMode = Settings.System.getInt(this.reactContext.getContentResolver(),Settings.System.AIRPLANE_MODE_ON, 0) != 0; } else { isAirPlaneMode = Settings.Global.getInt(this.reactContext.getContentResolver(),Settings.Global.AIRPLANE_MODE_ON, 0) != 0; } p.resolve(isAirPlaneMode); } @ReactMethod public void isAutoDateAndTime(Promise p) { boolean isAutoDateAndTime; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { isAutoDateAndTime = Settings.System.getInt(this.reactContext.getContentResolver(),Settings.System.AUTO_TIME, 0) != 0; } else { isAutoDateAndTime = Settings.Global.getInt(this.reactContext.getContentResolver(),Settings.Global.AUTO_TIME, 0) != 0; } p.resolve(isAutoDateAndTime); } @ReactMethod public void isAutoTimeZone(Promise p) { boolean isAutoTimeZone; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { isAutoTimeZone = Settings.System.getInt(this.reactContext.getContentResolver(),Settings.System.AUTO_TIME_ZONE, 0) != 0; } else { isAutoTimeZone = Settings.Global.getInt(this.reactContext.getContentResolver(),Settings.Global.AUTO_TIME_ZONE, 0) != 0; } p.resolve(isAutoTimeZone); } @ReactMethod public void hasSystemFeature(String feature, Promise p) { if (feature == null || feature == "") { p.resolve(false); return; } boolean hasFeature = this.reactContext.getApplicationContext().getPackageManager().hasSystemFeature(feature); p.resolve(hasFeature); } @ReactMethod public void getSystemAvailableFeatures(Promise p) { final FeatureInfo[] featureList = this.reactContext.getApplicationContext().getPackageManager().getSystemAvailableFeatures(); WritableArray promiseArray = Arguments.createArray(); for (FeatureInfo f : featureList) { if (f.name != null) { promiseArray.pushString(f.name); } } p.resolve(promiseArray); } @ReactMethod public void isLocationEnabled(Promise p) { boolean locationEnabled = false; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { LocationManager mLocationManager = (LocationManager) reactContext.getApplicationContext().getSystemService(Context.LOCATION_SERVICE); locationEnabled = mLocationManager.isLocationEnabled(); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { int locationMode = Settings.Secure.getInt(reactContext.getContentResolver(), Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF); locationEnabled = locationMode != Settings.Secure.LOCATION_MODE_OFF; } else { String locationProviders = Settings.Secure.getString(reactContext.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); locationEnabled = !TextUtils.isEmpty(locationProviders); } p.resolve(locationEnabled); } @ReactMethod public void getAvailableLocationProviders(Promise p) { LocationManager mLocationManager = (LocationManager) reactContext.getApplicationContext().getSystemService(Context.LOCATION_SERVICE); final List<String> providers = mLocationManager.getProviders(false); WritableMap providersAvailability = Arguments.createMap(); for (String provider : providers) { providersAvailability.putBoolean(provider, mLocationManager.isProviderEnabled(provider)); } p.resolve(providersAvailability); } public String getInstallReferrer() { SharedPreferences sharedPref = getReactApplicationContext().getSharedPreferences("react-native-device-info", Context.MODE_PRIVATE); return sharedPref.getString("installReferrer", null); } @SuppressLint({"MissingPermission", "HardwareIds"}) private Map<String, Object> generateConstants() { HashMap<String, Object> constants = new HashMap<String, Object>(); PackageManager packageManager = this.reactContext.getPackageManager(); String packageName = this.reactContext.getPackageName(); constants.put("appVersion", "not available"); constants.put("appName", "not available"); constants.put("buildVersion", "not available"); constants.put("buildNumber", 0); try { PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0); PackageInfo info = packageManager.getPackageInfo(packageName, 0); String applicationName = this.reactContext.getApplicationInfo().loadLabel(this.reactContext.getPackageManager()).toString(); constants.put("appVersion", info.versionName); constants.put("buildNumber", info.versionCode); constants.put("firstInstallTime", info.firstInstallTime); constants.put("lastUpdateTime", info.lastUpdateTime); constants.put("appName", applicationName); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } String deviceName = "Unknown"; String permission = "android.permission.BLUETOOTH"; int res = this.reactContext.checkCallingOrSelfPermission(permission); if (res == PackageManager.PERMISSION_GRANTED) { try { BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter(); if (myDevice != null) { deviceName = myDevice.getName(); } } catch (Exception e) { e.printStackTrace(); } } try { if (Class.forName("com.google.android.gms.iid.InstanceID") != null) { constants.put("instanceId", com.google.android.gms.iid.InstanceID.getInstance(this.reactContext).getId()); } } catch (ClassNotFoundException e) { constants.put("instanceId", "N/A: Add com.google.android.gms:play-services-gcm to your project."); } constants.put("serialNumber", Build.SERIAL); constants.put("deviceName", deviceName); constants.put("systemName", "Android"); constants.put("systemVersion", Build.VERSION.RELEASE); constants.put("model", Build.MODEL); constants.put("brand", Build.BRAND); constants.put("buildId", Build.ID); constants.put("deviceId", Build.BOARD); constants.put("apiLevel", Build.VERSION.SDK_INT); constants.put("bootloader", Build.BOOTLOADER); constants.put("device", Build.DEVICE); constants.put("display", Build.DISPLAY); constants.put("fingerprint", Build.FINGERPRINT); constants.put("hardware", Build.HARDWARE); constants.put("host", Build.HOST); constants.put("product", Build.PRODUCT); constants.put("tags", Build.TAGS); constants.put("type", Build.TYPE); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { constants.put("baseOS", Build.VERSION.BASE_OS); constants.put("previewSdkInt", Build.VERSION.PREVIEW_SDK_INT); constants.put("securityPatch", Build.VERSION.SECURITY_PATCH); } constants.put("codename", Build.VERSION.CODENAME); constants.put("incremental", Build.VERSION.INCREMENTAL); constants.put("deviceLocale", this.getCurrentLanguage()); constants.put("preferredLocales", this.getPreferredLocales()); constants.put("deviceCountry", this.getCurrentCountry()); constants.put("uniqueId", Settings.Secure.getString(this.reactContext.getContentResolver(), Settings.Secure.ANDROID_ID)); constants.put("systemManufacturer", Build.MANUFACTURER); constants.put("bundleId", packageName); try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { constants.put("userAgent", WebSettings.getDefaultUserAgent(this.reactContext)); } else { constants.put("userAgent", System.getProperty("http.agent")); } } catch (RuntimeException e) { constants.put("userAgent", System.getProperty("http.agent")); } constants.put("timezone", TimeZone.getDefault().getID()); constants.put("isEmulator", this.isEmulator()); constants.put("isTablet", this.isTablet()); constants.put("fontScale", this.fontScale()); constants.put("is24Hour", this.is24Hour()); constants.put("carrier", this.getCarrier()); constants.put("totalDiskCapacity", this.getTotalDiskCapacity()); constants.put("freeDiskStorage", this.getFreeDiskStorage()); constants.put("installReferrer", this.getInstallReferrer()); if (reactContext != null && (reactContext.checkCallingOrSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && reactContext.checkCallingOrSelfPermission(Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED) || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && reactContext.checkCallingOrSelfPermission(Manifest.permission.READ_PHONE_NUMBERS) == PackageManager.PERMISSION_GRANTED))) { TelephonyManager telMgr = (TelephonyManager) this.reactContext.getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE); constants.put("phoneNumber", telMgr.getLine1Number()); } else { constants.put("phoneNumber", null); } Runtime rt = Runtime.getRuntime(); constants.put("maxMemory", rt.maxMemory()); ActivityManager actMgr = (ActivityManager) this.reactContext.getSystemService(Context.ACTIVITY_SERVICE); ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo(); actMgr.getMemoryInfo(memInfo); constants.put("totalMemory", memInfo.totalMem); constants.put("deviceType", deviceType.getValue()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { constants.put("supportedABIs", Build.SUPPORTED_ABIS); constants.put("supported32BitAbis", Arrays.asList(Build.SUPPORTED_32_BIT_ABIS)); constants.put("supported64BitAbis", Arrays.asList(Build.SUPPORTED_64_BIT_ABIS)); } else { constants.put("supportedABIs", new String[]{ Build.CPU_ABI }); constants.put("supported32BitAbis", Arrays.asList(new String[] {})); constants.put("supported64BitAbis", Arrays.asList(new String[] {})); } return constants; } @Override public @Nullable Map<String, Object> getConstants() { if (this.constants == null && this.futureConstants != null) { try { this.constants = this.futureConstants.get(); } catch (InterruptedException e) { return null; } catch (ExecutionException e) { throw new RuntimeException(e.getCause()); } } return this.constants; } }
android/src/main/java/com/learnium/RNDeviceInfo/RNDeviceModule.java
package com.learnium.RNDeviceInfo; import android.Manifest; import android.annotation.SuppressLint; import android.app.KeyguardManager; import android.app.UiModeManager; import android.bluetooth.BluetoothAdapter; import android.content.Context; import android.content.SharedPreferences; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.FeatureInfo; import android.content.res.Configuration; import android.location.LocationManager; import android.net.wifi.WifiManager; import android.net.wifi.WifiInfo; import android.os.AsyncTask; import android.os.Build; import android.os.Environment; import android.os.StatFs; import android.os.BatteryManager; import android.provider.Settings; import android.view.WindowManager; import android.webkit.WebSettings; import android.telephony.TelephonyManager; import android.text.format.Formatter; import android.text.TextUtils; import android.app.ActivityManager; import android.util.DisplayMetrics; import android.hardware.Camera; import android.hardware.camera2.CameraManager; import android.hardware.camera2.CameraAccessException; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Arrays; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import java.lang.Runtime; import java.net.NetworkInterface; import java.math.BigInteger; import java.util.concurrent.ExecutionException; import javax.annotation.Nullable; public class RNDeviceModule extends ReactContextBaseJavaModule { ReactApplicationContext reactContext; WifiInfo wifiInfo; DeviceType deviceType; Map<String, Object> constants; AsyncTask<Void, Void, Map<String, Object>> futureConstants; public RNDeviceModule(ReactApplicationContext reactContext, boolean loadConstantsAsynchronously) { super(reactContext); this.reactContext = reactContext; this.deviceType = getDeviceType(reactContext); if (loadConstantsAsynchronously) { this.futureConstants = new AsyncTask<Void, Void, Map<String, Object>>() { @Override protected Map<String, Object> doInBackground(Void... args) { return generateConstants(); } }.execute(); } else { this.constants = generateConstants(); } } @Override public String getName() { return "RNDeviceInfo"; } private WifiInfo getWifiInfo() { if (this.wifiInfo == null) { WifiManager manager = (WifiManager) reactContext.getApplicationContext().getSystemService(Context.WIFI_SERVICE); this.wifiInfo = manager.getConnectionInfo(); } return this.wifiInfo; } private String getCurrentLanguage() { Locale current; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { current = getReactApplicationContext().getResources().getConfiguration().getLocales().get(0); } else { current = getReactApplicationContext().getResources().getConfiguration().locale; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return current.toLanguageTag(); } else { StringBuilder builder = new StringBuilder(); builder.append(current.getLanguage()); if (current.getCountry() != null) { builder.append("-"); builder.append(current.getCountry()); } return builder.toString(); } } private ArrayList<String> getPreferredLocales() { Configuration configuration = getReactApplicationContext().getResources().getConfiguration(); ArrayList<String> preferred = new ArrayList<>(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { for (int i = 0; i < configuration.getLocales().size(); i++) { preferred.add(configuration.getLocales().get(i).getLanguage()); } } else { preferred.add(configuration.locale.getLanguage()); } return preferred; } private String getCurrentCountry() { Locale current; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { current = getReactApplicationContext().getResources().getConfiguration().getLocales().get(0); } else { current = getReactApplicationContext().getResources().getConfiguration().locale; } return current.getCountry(); } private Boolean isEmulator() { return Build.FINGERPRINT.startsWith("generic") || Build.FINGERPRINT.startsWith("unknown") || Build.MODEL.contains("google_sdk") || Build.MODEL.toLowerCase().contains("droid4x") || Build.MODEL.contains("Emulator") || Build.MODEL.contains("Android SDK built for x86") || Build.MANUFACTURER.contains("Genymotion") || Build.HARDWARE.contains("goldfish") || Build.HARDWARE.contains("ranchu") || Build.HARDWARE.contains("vbox86") || Build.PRODUCT.contains("sdk") || Build.PRODUCT.contains("google_sdk") || Build.PRODUCT.contains("sdk_google") || Build.PRODUCT.contains("sdk_x86") || Build.PRODUCT.contains("vbox86p") || Build.PRODUCT.contains("emulator") || Build.PRODUCT.contains("simulator") || Build.BOARD.toLowerCase().contains("nox") || Build.BOOTLOADER.toLowerCase().contains("nox") || Build.HARDWARE.toLowerCase().contains("nox") || Build.PRODUCT.toLowerCase().contains("nox") || Build.SERIAL.toLowerCase().contains("nox") || (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic")); } private Boolean isTablet() { return deviceType == DeviceType.TABLET; } private static DeviceType getDeviceType(ReactApplicationContext reactContext) { // Detect TVs via ui mode (Android TVs) or system features (Fire TV). if (reactContext.getApplicationContext().getPackageManager().hasSystemFeature("amazon.hardware.fire_tv")) { return DeviceType.TV; } UiModeManager uiManager = (UiModeManager) reactContext.getSystemService(Context.UI_MODE_SERVICE); if (uiManager != null && uiManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION) { return DeviceType.TV; } // Find the current window manager, if none is found we can't measure the device physical size. WindowManager windowManager = (WindowManager) reactContext.getSystemService(Context.WINDOW_SERVICE); if (windowManager == null) { return DeviceType.UNKNOWN; } // Get display metrics to see if we can differentiate handsets and tablets. // NOTE: for API level 16 the metrics will exclude window decor. DisplayMetrics metrics = new DisplayMetrics(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { windowManager.getDefaultDisplay().getRealMetrics(metrics); } else { windowManager.getDefaultDisplay().getMetrics(metrics); } // Calculate physical size. double widthInches = metrics.widthPixels / (double) metrics.xdpi; double heightInches = metrics.heightPixels / (double) metrics.ydpi; double diagonalSizeInches = Math.sqrt(Math.pow(widthInches, 2) + Math.pow(heightInches, 2)); if (diagonalSizeInches >= 3.0 && diagonalSizeInches <= 6.9) { // Devices in a sane range for phones are considered to be Handsets. return DeviceType.HANDSET; } else if (diagonalSizeInches > 6.9 && diagonalSizeInches <= 18.0) { // Devices larger than handset and in a sane range for tablets are tablets. return DeviceType.TABLET; } else { // Otherwise, we don't know what device type we're on/ return DeviceType.UNKNOWN; } } private float fontScale() { return getReactApplicationContext().getResources().getConfiguration().fontScale; } private Boolean is24Hour() { return android.text.format.DateFormat.is24HourFormat(this.reactContext.getApplicationContext()); } @ReactMethod public void isPinOrFingerprintSet(Callback callback) { KeyguardManager keyguardManager = (KeyguardManager) this.reactContext.getApplicationContext().getSystemService(Context.KEYGUARD_SERVICE); //api 16+ callback.invoke(keyguardManager.isKeyguardSecure()); } @ReactMethod public void getIpAddress(Promise p) { String ipAddress = Formatter.formatIpAddress(getWifiInfo().getIpAddress()); p.resolve(ipAddress); } @ReactMethod public void getCameraPresence(Promise p) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { CameraManager manager=(CameraManager)getReactApplicationContext().getSystemService(Context.CAMERA_SERVICE); try { p.resolve(manager.getCameraIdList().length > 0); } catch (CameraAccessException e) { p.reject(e); } } else { p.resolve(Camera.getNumberOfCameras()> 0); } } @ReactMethod public void getMacAddress(Promise p) { String macAddress = getWifiInfo().getMacAddress(); String permission = "android.permission.INTERNET"; int res = this.reactContext.checkCallingOrSelfPermission(permission); if (res == PackageManager.PERMISSION_GRANTED) { try { List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface nif : all) { if (!nif.getName().equalsIgnoreCase("wlan0")) continue; byte[] macBytes = nif.getHardwareAddress(); if (macBytes == null) { macAddress = ""; } else { StringBuilder res1 = new StringBuilder(); for (byte b : macBytes) { res1.append(String.format("%02X:",b)); } if (res1.length() > 0) { res1.deleteCharAt(res1.length() - 1); } macAddress = res1.toString(); } } } catch (Exception ex) { } } p.resolve(macAddress); } @ReactMethod public String getCarrier() { TelephonyManager telMgr = (TelephonyManager) this.reactContext.getSystemService(Context.TELEPHONY_SERVICE); return telMgr.getNetworkOperatorName(); } @ReactMethod public BigInteger getTotalDiskCapacity() { try { StatFs root = new StatFs(Environment.getRootDirectory().getAbsolutePath()); return BigInteger.valueOf(root.getBlockCount()).multiply(BigInteger.valueOf(root.getBlockSize())); } catch (Exception e) { e.printStackTrace(); } return null; } @ReactMethod public BigInteger getFreeDiskStorage() { try { StatFs external = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath()); long availableBlocks; long blockSize; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) { availableBlocks = external.getAvailableBlocks(); blockSize = external.getBlockSize(); } else { availableBlocks = external.getAvailableBlocksLong(); blockSize = external.getBlockSizeLong(); } return BigInteger.valueOf(availableBlocks).multiply(BigInteger.valueOf(blockSize)); } catch (Exception e) { e.printStackTrace(); } return null; } @ReactMethod public void isBatteryCharging(Promise p){ IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = this.reactContext.getApplicationContext().registerReceiver(null, ifilter); int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING; p.resolve(isCharging); } @ReactMethod public void getBatteryLevel(Promise p) { Intent batteryIntent = this.reactContext.getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); float batteryLevel = level / (float) scale; p.resolve(batteryLevel); } @ReactMethod public void isAirPlaneMode(Promise p) { boolean isAirPlaneMode; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { isAirPlaneMode = Settings.System.getInt(this.reactContext.getContentResolver(),Settings.System.AIRPLANE_MODE_ON, 0) != 0; } else { isAirPlaneMode = Settings.Global.getInt(this.reactContext.getContentResolver(),Settings.Global.AIRPLANE_MODE_ON, 0) != 0; } p.resolve(isAirPlaneMode); } @ReactMethod public void isAutoDateAndTime(Promise p) { boolean isAutoDateAndTime; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { isAutoDateAndTime = Settings.System.getInt(this.reactContext.getContentResolver(),Settings.System.AUTO_TIME, 0) != 0; } else { isAutoDateAndTime = Settings.Global.getInt(this.reactContext.getContentResolver(),Settings.Global.AUTO_TIME, 0) != 0; } p.resolve(isAutoDateAndTime); } @ReactMethod public void isAutoTimeZone(Promise p) { boolean isAutoTimeZone; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { isAutoTimeZone = Settings.System.getInt(this.reactContext.getContentResolver(),Settings.System.AUTO_TIME_ZONE, 0) != 0; } else { isAutoTimeZone = Settings.Global.getInt(this.reactContext.getContentResolver(),Settings.Global.AUTO_TIME_ZONE, 0) != 0; } p.resolve(isAutoTimeZone); } @ReactMethod public void hasSystemFeature(String feature, Promise p) { if (feature == null || feature == "") { p.resolve(false); return; } boolean hasFeature = this.reactContext.getApplicationContext().getPackageManager().hasSystemFeature(feature); p.resolve(hasFeature); } @ReactMethod public void getSystemAvailableFeatures(Promise p) { final FeatureInfo[] featureList = this.reactContext.getApplicationContext().getPackageManager().getSystemAvailableFeatures(); WritableArray promiseArray = Arguments.createArray(); for (FeatureInfo f : featureList) { if (f.name != null) { promiseArray.pushString(f.name); } } p.resolve(promiseArray); } @ReactMethod public void isLocationEnabled(Promise p) { boolean locationEnabled = false; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { LocationManager mLocationManager = (LocationManager) reactContext.getApplicationContext().getSystemService(Context.LOCATION_SERVICE); locationEnabled = mLocationManager.isLocationEnabled(); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { int locationMode = Settings.Secure.getInt(reactContext.getContentResolver(), Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF); locationEnabled = locationMode != Settings.Secure.LOCATION_MODE_OFF; } else { String locationProviders = Settings.Secure.getString(reactContext.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); locationEnabled = !TextUtils.isEmpty(locationProviders); } p.resolve(locationEnabled); } @ReactMethod public void getAvailableLocationProviders(Promise p) { LocationManager mLocationManager = (LocationManager) reactContext.getApplicationContext().getSystemService(Context.LOCATION_SERVICE); final List<String> providers = mLocationManager.getProviders(false); WritableMap providersAvailability = Arguments.createMap(); for (String provider : providers) { providersAvailability.putBoolean(provider, mLocationManager.isProviderEnabled(provider)); } p.resolve(providersAvailability); } public String getInstallReferrer() { SharedPreferences sharedPref = getReactApplicationContext().getSharedPreferences("react-native-device-info", Context.MODE_PRIVATE); return sharedPref.getString("installReferrer", null); } @SuppressLint({"MissingPermission", "HardwareIds"}) private Map<String, Object> generateConstants() { HashMap<String, Object> constants = new HashMap<String, Object>(); PackageManager packageManager = this.reactContext.getPackageManager(); String packageName = this.reactContext.getPackageName(); constants.put("appVersion", "not available"); constants.put("appName", "not available"); constants.put("buildVersion", "not available"); constants.put("buildNumber", 0); try { PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0); PackageInfo info = packageManager.getPackageInfo(packageName, 0); String applicationName = this.reactContext.getApplicationInfo().loadLabel(this.reactContext.getPackageManager()).toString(); constants.put("appVersion", info.versionName); constants.put("buildNumber", info.versionCode); constants.put("firstInstallTime", info.firstInstallTime); constants.put("lastUpdateTime", info.lastUpdateTime); constants.put("appName", applicationName); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } String deviceName = "Unknown"; String permission = "android.permission.BLUETOOTH"; int res = this.reactContext.checkCallingOrSelfPermission(permission); if (res == PackageManager.PERMISSION_GRANTED) { try { BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter(); if (myDevice != null) { deviceName = myDevice.getName(); } } catch (Exception e) { e.printStackTrace(); } } try { if (Class.forName("com.google.android.gms.iid.InstanceID") != null) { constants.put("instanceId", com.google.android.gms.iid.InstanceID.getInstance(this.reactContext).getId()); } } catch (ClassNotFoundException e) { constants.put("instanceId", "N/A: Add com.google.android.gms:play-services-gcm to your project."); } constants.put("serialNumber", Build.SERIAL); constants.put("deviceName", deviceName); constants.put("systemName", "Android"); constants.put("systemVersion", Build.VERSION.RELEASE); constants.put("model", Build.MODEL); constants.put("brand", Build.BRAND); constants.put("buildId", Build.ID); constants.put("deviceId", Build.BOARD); constants.put("apiLevel", Build.VERSION.SDK_INT); constants.put("bootloader", Build.BOOTLOADER); constants.put("device", Build.DEVICE); constants.put("display", Build.DISPLAY); constants.put("fingerprint", Build.FINGERPRINT); constants.put("hardware", Build.HARDWARE); constants.put("host", Build.HOST); constants.put("product", Build.PRODUCT); constants.put("tags", Build.TAGS); constants.put("type", Build.TYPE); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { constants.put("baseOS", Build.VERSION.BASE_OS); constants.put("previewSdkInt", Build.VERSION.PREVIEW_SDK_INT); constants.put("securityPatch", Build.VERSION.SECURITY_PATCH); } constants.put("codename", Build.VERSION.CODENAME); constants.put("incremental", Build.VERSION.INCREMENTAL); constants.put("deviceLocale", this.getCurrentLanguage()); constants.put("preferredLocales", this.getPreferredLocales()); constants.put("deviceCountry", this.getCurrentCountry()); constants.put("uniqueId", Settings.Secure.getString(this.reactContext.getContentResolver(), Settings.Secure.ANDROID_ID)); constants.put("systemManufacturer", Build.MANUFACTURER); constants.put("bundleId", packageName); try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { constants.put("userAgent", WebSettings.getDefaultUserAgent(this.reactContext)); } else { constants.put("userAgent", System.getProperty("http.agent")); } } catch (RuntimeException e) { constants.put("userAgent", System.getProperty("http.agent")); } constants.put("timezone", TimeZone.getDefault().getID()); constants.put("isEmulator", this.isEmulator()); constants.put("isTablet", this.isTablet()); constants.put("fontScale", this.fontScale()); constants.put("is24Hour", this.is24Hour()); constants.put("carrier", this.getCarrier()); constants.put("totalDiskCapacity", this.getTotalDiskCapacity()); constants.put("freeDiskStorage", this.getFreeDiskStorage()); constants.put("installReferrer", this.getInstallReferrer()); if (reactContext != null && (reactContext.checkCallingOrSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && reactContext.checkCallingOrSelfPermission(Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED) || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && reactContext.checkCallingOrSelfPermission(Manifest.permission.READ_PHONE_NUMBERS) == PackageManager.PERMISSION_GRANTED))) { TelephonyManager telMgr = (TelephonyManager) this.reactContext.getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE); constants.put("phoneNumber", telMgr.getLine1Number()); } else { constants.put("phoneNumber", null); } Runtime rt = Runtime.getRuntime(); constants.put("maxMemory", rt.maxMemory()); ActivityManager actMgr = (ActivityManager) this.reactContext.getSystemService(Context.ACTIVITY_SERVICE); ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo(); actMgr.getMemoryInfo(memInfo); constants.put("totalMemory", memInfo.totalMem); constants.put("deviceType", deviceType.getValue()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { constants.put("supportedABIs", Build.SUPPORTED_ABIS); constants.put("supported32BitAbis", Arrays.asList(Build.SUPPORTED_32_BIT_ABIS)); constants.put("supported64BitAbis", Arrays.asList(Build.SUPPORTED_64_BIT_ABIS)); } else { constants.put("supportedABIs", new String[]{ Build.CPU_ABI }); constants.put("supported32BitAbis", Arrays.asList(new String[] {})); constants.put("supported64BitAbis", Arrays.asList(new String[] {})); } return constants; } @Override public @Nullable Map<String, Object> getConstants() { if (this.constants == null && this.futureConstants != null) { try { this.constants = this.futureConstants.get(); } catch (InterruptedException e) { return null; } catch (ExecutionException e) { throw new RuntimeException(e.getCause()); } } return this.constants; } }
Move size based logic to separate function
android/src/main/java/com/learnium/RNDeviceInfo/RNDeviceModule.java
Move size based logic to separate function
<ide><path>ndroid/src/main/java/com/learnium/RNDeviceInfo/RNDeviceModule.java <ide> return DeviceType.TV; <ide> } <ide> <add> return getDeviceTypeFromPhysicalSize(reactContext); <add> } <add> <add> private static DeviceType getDeviceTypeFromPhysicalSize(ReactApplicationContext reactContext) { <ide> // Find the current window manager, if none is found we can't measure the device physical size. <ide> WindowManager windowManager = (WindowManager) reactContext.getSystemService(Context.WINDOW_SERVICE); <add> <ide> if (windowManager == null) { <ide> return DeviceType.UNKNOWN; <ide> }
Java
mit
5376fe16449f4c70c4eacf3b34b680c5d23dbbe6
0
marcshilling/react-native-image-picker,marcshilling/react-native-image-picker,react-community/react-native-image-picker,react-community/react-native-image-picker,marcshilling/react-native-image-picker,marcshilling/react-native-image-picker,react-community/react-native-image-picker,react-community/react-native-image-picker
package com.imagepicker; import android.Manifest; import android.app.Activity; import android.content.ClipData; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.hardware.camera2.CameraCharacteristics; import android.media.MediaMetadataRetriever; import android.net.Uri; import android.os.Build; import android.os.ParcelFileDescriptor; import android.provider.MediaStore; import android.provider.OpenableColumns; import android.util.Base64; import android.util.Log; import android.webkit.MimeTypeMap; import androidx.core.app.ActivityCompat; import androidx.core.content.FileProvider; import androidx.exifinterface.media.ExifInterface; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.TimeZone; import java.util.UUID; import static com.imagepicker.ImagePickerModule.*; public class Utils { public static String fileNamePrefix = "rn_image_picker_lib_temp_"; public static String errCameraUnavailable = "camera_unavailable"; public static String errPermission = "permission"; public static String errOthers = "others"; public static String mediaTypePhoto = "photo"; public static String mediaTypeVideo = "video"; public static String cameraPermissionDescription = "This library does not require Manifest.permission.CAMERA, if you add this permission in manifest then you have to obtain the same."; public static File createFile(Context reactContext, String fileType) { try { String filename = fileNamePrefix + UUID.randomUUID() + "." + fileType; // getCacheDir will auto-clean according to android docs File fileDir = reactContext.getCacheDir(); File file = new File(fileDir, filename); file.createNewFile(); return file; } catch (Exception e) { e.printStackTrace(); return null; } } public static Uri createUri(File file, Context reactContext) { String authority = reactContext.getApplicationContext().getPackageName() + ".imagepickerprovider"; return FileProvider.getUriForFile(reactContext, authority, file); } public static void saveToPublicDirectory(Uri uri, Context context, String mediaType) { ContentResolver resolver = context.getContentResolver(); Uri mediaStoreUri; ContentValues fileDetails = new ContentValues(); if (mediaType.equals("video")) { fileDetails.put(MediaStore.Video.Media.DISPLAY_NAME, UUID.randomUUID().toString()); fileDetails.put(MediaStore.Video.Media.MIME_TYPE, resolver.getType(uri)); mediaStoreUri = resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, fileDetails); } else { fileDetails.put(MediaStore.Images.Media.DISPLAY_NAME, UUID.randomUUID().toString()); fileDetails.put(MediaStore.Images.Media.MIME_TYPE, resolver.getType(uri)); mediaStoreUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, fileDetails); } copyUri(uri, mediaStoreUri, resolver); } public static void copyUri(Uri fromUri, Uri toUri, ContentResolver resolver) { try { OutputStream os = resolver.openOutputStream(toUri); InputStream is = resolver.openInputStream(fromUri); byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } } catch (IOException e) { e.printStackTrace(); } } // Make a copy of shared storage files inside app specific storage so that users can access it later. public static Uri getAppSpecificStorageUri(Uri sharedStorageUri, Context context) { if (sharedStorageUri == null) { return null; } ContentResolver contentResolver = context.getContentResolver(); String fileType = getFileTypeFromMime(contentResolver.getType(sharedStorageUri)); Uri toUri = Uri.fromFile(createFile(context, fileType)); copyUri(sharedStorageUri, toUri, contentResolver); return toUri; } public static boolean isCameraAvailable(Context reactContext) { return reactContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA) || reactContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY); } // Opening front camera is not officially supported in android, the below hack is obtained from various online sources public static void setFrontCamera(Intent intent) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { intent.putExtra("android.intent.extras.CAMERA_FACING", CameraCharacteristics.LENS_FACING_FRONT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { intent.putExtra("android.intent.extra.USE_FRONT_CAMERA", true); } } else { intent.putExtra("android.intent.extras.CAMERA_FACING", 1); } } public static int[] getImageDimensions(Uri uri, Context reactContext) { InputStream inputStream; try { inputStream = reactContext.getContentResolver().openInputStream(uri); } catch (FileNotFoundException e) { e.printStackTrace(); return new int[]{0, 0}; } BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(inputStream,null, options); return new int[]{options.outWidth, options.outHeight}; } static boolean hasPermission(final Activity activity) { final int writePermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); return writePermission == PackageManager.PERMISSION_GRANTED ? true : false; } static String getBase64String(Uri uri, Context reactContext) { InputStream inputStream; try { inputStream = reactContext.getContentResolver().openInputStream(uri); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } byte[] bytes; byte[] buffer = new byte[8192]; int bytesRead; ByteArrayOutputStream output = new ByteArrayOutputStream(); try { while ((bytesRead = inputStream.read(buffer)) != -1) { output.write(buffer, 0, bytesRead); } } catch (IOException e) { e.printStackTrace(); } bytes = output.toByteArray(); return Base64.encodeToString(bytes, Base64.NO_WRAP); } // Resize image // When decoding a jpg to bitmap all exif meta data will be lost, so make sure to copy orientation exif to new file else image might have wrong orientations public static Uri resizeImage(Uri uri, Context context, Options options) { try { int[] origDimens = getImageDimensions(uri, context); if (!shouldResizeImage(origDimens[0], origDimens[1], options)) { return uri; } int[] newDimens = getImageDimensBasedOnConstraints(origDimens[0], origDimens[1], options); InputStream imageStream = context.getContentResolver().openInputStream(uri); String mimeType = getMimeTypeFromFileUri(uri); Bitmap b = BitmapFactory.decodeStream(imageStream); b = Bitmap.createScaledBitmap(b, newDimens[0], newDimens[1], true); String originalOrientation = getOrientation(uri, context); File file = createFile(context, getFileTypeFromMime(mimeType)); OutputStream os = context.getContentResolver().openOutputStream(Uri.fromFile(file)); b.compress(getBitmapCompressFormat(mimeType), options.quality, os); setOrientation(file, originalOrientation, context); return Uri.fromFile(file); } catch (Exception e) { e.printStackTrace(); return uri; // cannot resize the image, return the original uri } } static String getOrientation(Uri uri, Context context) throws IOException { ExifInterface exifInterface = new ExifInterface(context.getContentResolver().openInputStream(uri)); return exifInterface.getAttribute(ExifInterface.TAG_ORIENTATION); } // ExifInterface.saveAttributes is costly operation so don't set exif for unnecessary orientations static void setOrientation(File file, String orientation, Context context) throws IOException { if (orientation.equals(String.valueOf(ExifInterface.ORIENTATION_NORMAL)) || orientation.equals(String.valueOf(ExifInterface.ORIENTATION_UNDEFINED))) { return; } ExifInterface exifInterface = new ExifInterface(file); exifInterface.setAttribute(ExifInterface.TAG_ORIENTATION, orientation); exifInterface.saveAttributes(); } static int[] getImageDimensBasedOnConstraints(int origWidth, int origHeight, Options options) { int width = origWidth; int height = origHeight; if (options.maxWidth == 0 || options.maxHeight == 0) { return new int[]{width, height}; } if (options.maxWidth < width) { height = (int) (((float) options.maxWidth / width) * height); width = options.maxWidth; } if (options.maxHeight < height) { width = (int) (((float) options.maxHeight / height) * width); height = options.maxHeight; } return new int[]{width, height}; } static double getFileSize(Uri uri, Context context) { try { ParcelFileDescriptor f = context.getContentResolver().openFileDescriptor(uri, "r"); return f.getStatSize(); } catch (Exception e) { e.printStackTrace(); return 0; } } static int getDuration(Uri uri, Context context) { MediaMetadataRetriever m = new MediaMetadataRetriever(); m.setDataSource(context, uri); int duration = Math.round(Float.parseFloat(m.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION))) / 1000; m.release(); return duration; } static boolean shouldResizeImage(int origWidth, int origHeight, Options options) { if ((options.maxWidth == 0 || options.maxHeight == 0) && options.quality == 100) { return false; } if (options.maxWidth >= origWidth && options.maxHeight >= origHeight && options.quality == 100) { return false; } return true; } static Bitmap.CompressFormat getBitmapCompressFormat(String mimeType) { switch (mimeType) { case "image/jpeg": return Bitmap.CompressFormat.JPEG; case "image/png": return Bitmap.CompressFormat.PNG; } return Bitmap.CompressFormat.JPEG; } static String getFileTypeFromMime(String mimeType) { if (mimeType == null) { return "jpg"; } switch (mimeType) { case "image/jpeg": return "jpg"; case "image/png": return "png"; case "image/gif": return "gif"; } return "jpg"; } static void deleteFile(Uri uri) { new File(uri.getPath()).delete(); } static String getMimeTypeFromFileUri(Uri uri) { return MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(uri.toString())); } // Since library users can have many modules in their project, we should respond to onActivityResult only for our request. static boolean isValidRequestCode(int requestCode) { switch (requestCode) { case REQUEST_LAUNCH_IMAGE_CAPTURE: case REQUEST_LAUNCH_VIDEO_CAPTURE: case REQUEST_LAUNCH_LIBRARY: return true; default: return false; } } // This library does not require Manifest.permission.CAMERA permission, but if user app declares as using this permission which is not granted, then attempting to use ACTION_IMAGE_CAPTURE|ACTION_VIDEO_CAPTURE will result in a SecurityException. // https://issuetracker.google.com/issues/37063818 public static boolean isCameraPermissionFulfilled(Context context, Activity activity) { try { String[] declaredPermissions = context.getPackageManager() .getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS) .requestedPermissions; if (declaredPermissions == null) { return true; } if (Arrays.asList(declaredPermissions).contains(Manifest.permission.CAMERA) && ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { return false; } return true; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); return true; } } static boolean isImageType(Uri uri, Context context) { final String imageMimeType = "image/"; return getMimeType(uri, context).contains(imageMimeType); } static boolean isVideoType(Uri uri, Context context) { final String videoMimeType = "video/"; return getMimeType(uri, context).contains(videoMimeType); } static String getMimeType(Uri uri, Context context) { if (uri.getScheme().equals("file")) { return getMimeTypeFromFileUri(uri); } ContentResolver contentResolver = context.getContentResolver(); return contentResolver.getType(uri); } static List<Uri> collectUrisFromData(Intent data) { // Default Gallery app on older Android versions doesn't support multiple image // picking and thus never uses clip data. if (data.getClipData() == null) { return Collections.singletonList(data.getData()); } ClipData clipData = data.getClipData(); List<Uri> fileUris = new ArrayList<>(clipData.getItemCount()); for (int i = 0; i < clipData.getItemCount(); ++i) { fileUris.add(clipData.getItemAt(i).getUri()); } return fileUris; } static ReadableMap getImageResponseMap(Uri uri, Options options, Context context) { String fileName = uri.getLastPathSegment(); int[] dimensions = getImageDimensions(uri, context); WritableMap map = Arguments.createMap(); map.putString("uri", uri.toString()); map.putDouble("fileSize", getFileSize(uri, context)); map.putString("fileName", fileName); map.putString("type", getMimeTypeFromFileUri(uri)); map.putInt("width", dimensions[0]); map.putInt("height", dimensions[1]); map.putString("type", getMimeType(uri, context)); if (options.includeBase64) { map.putString("base64", getBase64String(uri, context)); } if(options.includeExtra) { try (InputStream inputStream = context.getContentResolver().openInputStream(uri)) { ExifInterface exif = new ExifInterface(inputStream); Date datetime = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss").parse(exif.getAttribute(ExifInterface.TAG_DATETIME)); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); formatter.setTimeZone(TimeZone.getTimeZone("UTC")); String datetimeAsString = formatter.format(datetime); // Add more exif data here ... map.putString("timestamp", datetimeAsString); } catch (Exception e) { Log.e("RNIP", "Could not load image exif data: " + e.getMessage()); } } return map; } static ReadableMap getVideoResponseMap(Uri uri, Context context) { String fileName = uri.getLastPathSegment(); WritableMap map = Arguments.createMap(); map.putString("uri", uri.toString()); map.putDouble("fileSize", getFileSize(uri, context)); map.putInt("duration", getDuration(uri, context)); map.putString("fileName", fileName); map.putString("type", getMimeType(uri, context)); return map; } static ReadableMap getResponseMap(List<Uri> fileUris, Options options, Context context) throws RuntimeException { WritableArray assets = Arguments.createArray(); for(int i = 0; i < fileUris.size(); ++i) { Uri uri = fileUris.get(i); if (isImageType(uri, context)) { if (uri.getScheme().contains("content")) { uri = getAppSpecificStorageUri(uri, context); } uri = resizeImage(uri, context, options); assets.pushMap(getImageResponseMap(uri, options, context)); } else if (isVideoType(uri, context)) { assets.pushMap(getVideoResponseMap(uri, context)); } else { throw new RuntimeException("Unsupported file type"); } } WritableMap response = Arguments.createMap(); response.putArray("assets", assets); return response; } static ReadableMap getErrorMap(String errCode, String errMsg) { WritableMap map = Arguments.createMap(); map.putString("errorCode", errCode); if (errMsg != null) { map.putString("errorMessage", errMsg); } return map; } static ReadableMap getCancelMap() { WritableMap map = Arguments.createMap(); map.putBoolean("didCancel", true); return map; } }
android/src/main/java/com/imagepicker/Utils.java
package com.imagepicker; import android.Manifest; import android.app.Activity; import android.content.ClipData; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.hardware.camera2.CameraCharacteristics; import android.media.MediaMetadataRetriever; import android.net.Uri; import android.os.Build; import android.os.ParcelFileDescriptor; import android.provider.MediaStore; import android.provider.OpenableColumns; import android.util.Base64; import android.util.Log; import android.webkit.MimeTypeMap; import androidx.core.app.ActivityCompat; import androidx.core.content.FileProvider; import androidx.exifinterface.media.ExifInterface; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.TimeZone; import java.util.UUID; import static com.imagepicker.ImagePickerModule.*; public class Utils { public static String fileNamePrefix = "rn_image_picker_lib_temp_"; public static String errCameraUnavailable = "camera_unavailable"; public static String errPermission = "permission"; public static String errOthers = "others"; public static String mediaTypePhoto = "photo"; public static String mediaTypeVideo = "video"; public static String cameraPermissionDescription = "This library does not require Manifest.permission.CAMERA, if you add this permission in manifest then you have to obtain the same."; public static File createFile(Context reactContext, String fileType) { try { String filename = fileNamePrefix + UUID.randomUUID() + "." + fileType; // getCacheDir will auto-clean according to android docs File fileDir = reactContext.getCacheDir(); File file = new File(fileDir, filename); file.createNewFile(); return file; } catch (Exception e) { e.printStackTrace(); return null; } } public static Uri createUri(File file, Context reactContext) { String authority = reactContext.getApplicationContext().getPackageName() + ".imagepickerprovider"; return FileProvider.getUriForFile(reactContext, authority, file); } public static void saveToPublicDirectory(Uri uri, Context context, String mediaType) { ContentResolver resolver = context.getContentResolver(); Uri mediaStoreUri; ContentValues fileDetails = new ContentValues(); if (mediaType.equals("video")) { fileDetails.put(MediaStore.Video.Media.DISPLAY_NAME, UUID.randomUUID().toString()); fileDetails.put(MediaStore.Video.Media.MIME_TYPE, resolver.getType(uri)); mediaStoreUri = resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, fileDetails); } else { fileDetails.put(MediaStore.Images.Media.DISPLAY_NAME, UUID.randomUUID().toString()); fileDetails.put(MediaStore.Images.Media.MIME_TYPE, resolver.getType(uri)); mediaStoreUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, fileDetails); } copyUri(uri, mediaStoreUri, resolver); } public static void copyUri(Uri fromUri, Uri toUri, ContentResolver resolver) { try { OutputStream os = resolver.openOutputStream(toUri); InputStream is = resolver.openInputStream(fromUri); byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } } catch (IOException e) { e.printStackTrace(); } } // Make a copy of shared storage files inside app specific storage so that users can access it later. public static Uri getAppSpecificStorageUri(Uri sharedStorageUri, Context context) { if (sharedStorageUri == null) { return null; } ContentResolver contentResolver = context.getContentResolver(); String fileType = getFileTypeFromMime(contentResolver.getType(sharedStorageUri)); Uri toUri = Uri.fromFile(createFile(context, fileType)); copyUri(sharedStorageUri, toUri, contentResolver); return toUri; } public static boolean isCameraAvailable(Context reactContext) { return reactContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA) || reactContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY); } // Opening front camera is not officially supported in android, the below hack is obtained from various online sources public static void setFrontCamera(Intent intent) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { intent.putExtra("android.intent.extras.CAMERA_FACING", CameraCharacteristics.LENS_FACING_FRONT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { intent.putExtra("android.intent.extra.USE_FRONT_CAMERA", true); } } else { intent.putExtra("android.intent.extras.CAMERA_FACING", 1); } } public static int[] getImageDimensions(Uri uri, Context reactContext) { InputStream inputStream; try { inputStream = reactContext.getContentResolver().openInputStream(uri); } catch (FileNotFoundException e) { e.printStackTrace(); return new int[]{0, 0}; } BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(inputStream,null, options); return new int[]{options.outWidth, options.outHeight}; } static boolean hasPermission(final Activity activity) { final int writePermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); return writePermission == PackageManager.PERMISSION_GRANTED ? true : false; } static String getBase64String(Uri uri, Context reactContext) { InputStream inputStream; try { inputStream = reactContext.getContentResolver().openInputStream(uri); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } byte[] bytes; byte[] buffer = new byte[8192]; int bytesRead; ByteArrayOutputStream output = new ByteArrayOutputStream(); try { while ((bytesRead = inputStream.read(buffer)) != -1) { output.write(buffer, 0, bytesRead); } } catch (IOException e) { e.printStackTrace(); } bytes = output.toByteArray(); return Base64.encodeToString(bytes, Base64.NO_WRAP); } // Resize image // When decoding a jpg to bitmap all exif meta data will be lost, so make sure to copy orientation exif to new file else image might have wrong orientations public static Uri resizeImage(Uri uri, Context context, Options options) { try { int[] origDimens = getImageDimensions(uri, context); if (!shouldResizeImage(origDimens[0], origDimens[1], options)) { return uri; } int[] newDimens = getImageDimensBasedOnConstraints(origDimens[0], origDimens[1], options); InputStream imageStream = context.getContentResolver().openInputStream(uri); String mimeType = getMimeTypeFromFileUri(uri); Bitmap b = BitmapFactory.decodeStream(imageStream); b = Bitmap.createScaledBitmap(b, newDimens[0], newDimens[1], true); String originalOrientation = getOrientation(uri, context); File file = createFile(context, getFileTypeFromMime(mimeType)); OutputStream os = context.getContentResolver().openOutputStream(Uri.fromFile(file)); b.compress(getBitmapCompressFormat(mimeType), options.quality, os); setOrientation(file, originalOrientation, context); return Uri.fromFile(file); } catch (Exception e) { e.printStackTrace(); return null; } } static String getOrientation(Uri uri, Context context) throws IOException { ExifInterface exifInterface = new ExifInterface(context.getContentResolver().openInputStream(uri)); return exifInterface.getAttribute(ExifInterface.TAG_ORIENTATION); } // ExifInterface.saveAttributes is costly operation so don't set exif for unnecessary orientations static void setOrientation(File file, String orientation, Context context) throws IOException { if (orientation.equals(String.valueOf(ExifInterface.ORIENTATION_NORMAL)) || orientation.equals(String.valueOf(ExifInterface.ORIENTATION_UNDEFINED))) { return; } ExifInterface exifInterface = new ExifInterface(file); exifInterface.setAttribute(ExifInterface.TAG_ORIENTATION, orientation); exifInterface.saveAttributes(); } static int[] getImageDimensBasedOnConstraints(int origWidth, int origHeight, Options options) { int width = origWidth; int height = origHeight; if (options.maxWidth == 0 || options.maxHeight == 0) { return new int[]{width, height}; } if (options.maxWidth < width) { height = (int) (((float) options.maxWidth / width) * height); width = options.maxWidth; } if (options.maxHeight < height) { width = (int) (((float) options.maxHeight / height) * width); height = options.maxHeight; } return new int[]{width, height}; } static double getFileSize(Uri uri, Context context) { try { ParcelFileDescriptor f = context.getContentResolver().openFileDescriptor(uri, "r"); return f.getStatSize(); } catch (Exception e) { e.printStackTrace(); return 0; } } static int getDuration(Uri uri, Context context) { MediaMetadataRetriever m = new MediaMetadataRetriever(); m.setDataSource(context, uri); int duration = Math.round(Float.parseFloat(m.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION))) / 1000; m.release(); return duration; } static boolean shouldResizeImage(int origWidth, int origHeight, Options options) { if ((options.maxWidth == 0 || options.maxHeight == 0) && options.quality == 100) { return false; } if (options.maxWidth >= origWidth && options.maxHeight >= origHeight && options.quality == 100) { return false; } return true; } static Bitmap.CompressFormat getBitmapCompressFormat(String mimeType) { switch (mimeType) { case "image/jpeg": return Bitmap.CompressFormat.JPEG; case "image/png": return Bitmap.CompressFormat.PNG; } return Bitmap.CompressFormat.JPEG; } static String getFileTypeFromMime(String mimeType) { if (mimeType == null) { return "jpg"; } switch (mimeType) { case "image/jpeg": return "jpg"; case "image/png": return "png"; case "image/gif": return "gif"; } return "jpg"; } static void deleteFile(Uri uri) { new File(uri.getPath()).delete(); } static String getMimeTypeFromFileUri(Uri uri) { return MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(uri.toString())); } // Since library users can have many modules in their project, we should respond to onActivityResult only for our request. static boolean isValidRequestCode(int requestCode) { switch (requestCode) { case REQUEST_LAUNCH_IMAGE_CAPTURE: case REQUEST_LAUNCH_VIDEO_CAPTURE: case REQUEST_LAUNCH_LIBRARY: return true; default: return false; } } // This library does not require Manifest.permission.CAMERA permission, but if user app declares as using this permission which is not granted, then attempting to use ACTION_IMAGE_CAPTURE|ACTION_VIDEO_CAPTURE will result in a SecurityException. // https://issuetracker.google.com/issues/37063818 public static boolean isCameraPermissionFulfilled(Context context, Activity activity) { try { String[] declaredPermissions = context.getPackageManager() .getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS) .requestedPermissions; if (declaredPermissions == null) { return true; } if (Arrays.asList(declaredPermissions).contains(Manifest.permission.CAMERA) && ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { return false; } return true; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); return true; } } static boolean isImageType(Uri uri, Context context) { final String imageMimeType = "image/"; return getMimeType(uri, context).contains(imageMimeType); } static boolean isVideoType(Uri uri, Context context) { final String videoMimeType = "video/"; return getMimeType(uri, context).contains(videoMimeType); } static String getMimeType(Uri uri, Context context) { if (uri.getScheme().equals("file")) { return getMimeTypeFromFileUri(uri); } ContentResolver contentResolver = context.getContentResolver(); return contentResolver.getType(uri); } static List<Uri> collectUrisFromData(Intent data) { // Default Gallery app on older Android versions doesn't support multiple image // picking and thus never uses clip data. if (data.getClipData() == null) { return Collections.singletonList(data.getData()); } ClipData clipData = data.getClipData(); List<Uri> fileUris = new ArrayList<>(clipData.getItemCount()); for (int i = 0; i < clipData.getItemCount(); ++i) { fileUris.add(clipData.getItemAt(i).getUri()); } return fileUris; } static ReadableMap getImageResponseMap(Uri uri, Options options, Context context) { String fileName = uri.getLastPathSegment(); int[] dimensions = getImageDimensions(uri, context); WritableMap map = Arguments.createMap(); map.putString("uri", uri.toString()); map.putDouble("fileSize", getFileSize(uri, context)); map.putString("fileName", fileName); map.putString("type", getMimeTypeFromFileUri(uri)); map.putInt("width", dimensions[0]); map.putInt("height", dimensions[1]); map.putString("type", getMimeType(uri, context)); if (options.includeBase64) { map.putString("base64", getBase64String(uri, context)); } if(options.includeExtra) { try (InputStream inputStream = context.getContentResolver().openInputStream(uri)) { ExifInterface exif = new ExifInterface(inputStream); Date datetime = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss").parse(exif.getAttribute(ExifInterface.TAG_DATETIME)); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); formatter.setTimeZone(TimeZone.getTimeZone("UTC")); String datetimeAsString = formatter.format(datetime); // Add more exif data here ... map.putString("timestamp", datetimeAsString); } catch (Exception e) { Log.e("RNIP", "Could not load image exif data: " + e.getMessage()); } } return map; } static ReadableMap getVideoResponseMap(Uri uri, Context context) { String fileName = uri.getLastPathSegment(); WritableMap map = Arguments.createMap(); map.putString("uri", uri.toString()); map.putDouble("fileSize", getFileSize(uri, context)); map.putInt("duration", getDuration(uri, context)); map.putString("fileName", fileName); map.putString("type", getMimeType(uri, context)); return map; } static ReadableMap getResponseMap(List<Uri> fileUris, Options options, Context context) throws RuntimeException { WritableArray assets = Arguments.createArray(); for(int i = 0; i < fileUris.size(); ++i) { Uri uri = fileUris.get(i); if (isImageType(uri, context)) { if (uri.getScheme().contains("content")) { uri = getAppSpecificStorageUri(uri, context); } uri = resizeImage(uri, context, options); assets.pushMap(getImageResponseMap(uri, options, context)); } else if (isVideoType(uri, context)) { assets.pushMap(getVideoResponseMap(uri, context)); } else { throw new RuntimeException("Unsupported file type"); } } WritableMap response = Arguments.createMap(); response.putArray("assets", assets); return response; } static ReadableMap getErrorMap(String errCode, String errMsg) { WritableMap map = Arguments.createMap(); map.putString("errorCode", errCode); if (errMsg != null) { map.putString("errorMessage", errMsg); } return map; } static ReadableMap getCancelMap() { WritableMap map = Arguments.createMap(); map.putBoolean("didCancel", true); return map; } }
Return the original 'uri' instead of null when resizeImage has failed (#1862)
android/src/main/java/com/imagepicker/Utils.java
Return the original 'uri' instead of null when resizeImage has failed (#1862)
<ide><path>ndroid/src/main/java/com/imagepicker/Utils.java <ide> <ide> } catch (Exception e) { <ide> e.printStackTrace(); <del> return null; <add> return uri; // cannot resize the image, return the original uri <ide> } <ide> } <ide>
Java
apache-2.0
6af065402a0a7bb9f8566a6483f121d237ee69b2
0
apuder/DragSortRecycler,emileb/DragSortRecycler
/* * DragSortRecycler * * Added drag and drop functionality to your RecyclerView * * * Copyright 2014 Emile Belanger. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.emtronics.dragsortrecycler; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.support.annotation.Nullable; public class DragSortRecycler extends RecyclerView.ItemDecoration implements RecyclerView.OnItemTouchListener { final String TAG = "RecyclerDragSort"; final boolean DEBUG = false; private int dragHandleWidth = 0; private long selectedDragItem = -1; private int fingerAnchorY; private int fingerY; private int fingerOffsetInViewY; private float autoScrollWindow = 0.1f; private float autoScrollSpeed = 0.5f; private BitmapDrawable floatingItem; private Rect floatingItemStatingBounds; private Rect floatingItemBounds; private float floatingItemAlpha = 0.5f; private int floatingItemBgColor = 0; private int viewHandleId = -1; ItemMovedInterface moveInterface; private boolean isDragging; @Nullable OnDragStateChangedListener dragStateChangedListener; public interface ItemMovedInterface { public void moveElement(int from, int to); } public interface OnDragStateChangedListener { public void onDragStart(); public void onDragStop(); } private void debugLog(String log) { if (DEBUG) Log.d(TAG, log); } public RecyclerView.OnScrollListener getScrollListener() { return scrollListener; } /* * Set the item move interface */ public void setItemMoveInterface(ItemMovedInterface swif) { moveInterface = swif; } public void setViewHandleId(int id) { viewHandleId = id; } public void setLeftDragArea(int w) { dragHandleWidth = w; } public void setFloatingAlpha(float a) { floatingItemAlpha = a; } public void setFloatingBgColor(int c) { floatingItemBgColor = c; } /* Set the window at top and bottom of list, must be between 0 and 0.5 For example 0.1 uses the top and bottom 10% of the lists for scrolling */ public void setAutoScrollWindow(float w) { autoScrollWindow = w; } /* Set the autoscroll speed, default is 0.5 */ public void setAutoScrollSpeed(float speed) { autoScrollSpeed = speed; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView rv, RecyclerView.State state) { super.getItemOffsets(outRect, view, rv, state); debugLog("getItemOffsets"); debugLog("View top = " + view.getTop()); if (selectedDragItem != -1) { long itemId = rv.getChildItemId(view); debugLog("itemId =" + itemId); //Movement of finger float totalMovment = fingerY-fingerAnchorY; if (itemId == selectedDragItem) { view.setVisibility(View.INVISIBLE); } else { //Make view visible uncase invisible view.setVisibility(View.VISIBLE); //Find middle of the floatingItem float floatMiddleY = floatingItemBounds.top + floatingItemBounds.height()/2; //Moving down the list //These will auto-animate if the device continually send touch motion events // if (totalMovment>0) { if ((itemId > selectedDragItem) && (view.getTop() < floatMiddleY)) { float amountUp = ((float)floatMiddleY - view.getTop()) / (float)view.getHeight(); // amountUp *= 0.5f; if (amountUp > 1) amountUp = 1; outRect.top = -(int)(floatingItemBounds.height()*amountUp); outRect.bottom = (int)(floatingItemBounds.height()*amountUp); } }//Moving up the list // else if (totalMovment < 0) { if((itemId < selectedDragItem) && (view.getBottom() > floatMiddleY)) { float amountDown = ((float)view.getBottom() - floatMiddleY) / (float)view.getHeight(); // amountDown *= 0.5f; if (amountDown > 1) amountDown = 1; outRect.top = (int)(floatingItemBounds.height()*amountDown); outRect.bottom = -(int)(floatingItemBounds.height()*amountDown); } } } } else { outRect.top = 0; outRect.bottom = 0; //Make view visible incase invisible view.setVisibility(View.VISIBLE); } } /** * Find the new position by scanning through the items on * screen and finding the positional relationship. * This *seems* to work, another method would be to use * getItemOffsets, but I think that could miss items?.. */ private long getNewPostion(RecyclerView rv) { int itemsOnScreen = rv.getLayoutManager().getChildCount(); float floatMiddleY = floatingItemBounds.top + floatingItemBounds.height()/2; long above=0; long below = rv.getLayoutManager().getItemCount(); for (int n=0;n < itemsOnScreen;n++) //Scan though items on screen, however they may not { // be in order! View view = rv.getLayoutManager().getChildAt(n); long itemId = rv.getChildItemId(view); if (itemId == selectedDragItem) //Don't check against itself! continue; float viewMiddleY = view.getTop() + view.getHeight()/2; if (floatMiddleY > viewMiddleY) //Is above this item { if (itemId > above) above = itemId; } else if (floatMiddleY <= viewMiddleY) //Is below this item { if (itemId < below) below = itemId; } } debugLog("above = " + above + " below = " + below); if (below < selectedDragItem) //Need to count itself below++; return below - 1; } @Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { Log.d(TAG,"onInterceptTouchEvent"); //if (e.getAction() == MotionEvent.ACTION_DOWN) { View itemView = rv.findChildViewUnder(e.getX(), e.getY()); if (itemView==null) return false; boolean dragging = false; if ((dragHandleWidth > 0 ) && (e.getX() < dragHandleWidth)) { dragging = true; } else if (viewHandleId != -1) { //Find the handle in the list item View handleView = itemView.findViewById(viewHandleId); if (handleView == null) { Log.e(TAG, "The view ID " + viewHandleId + " was not found in the RecycleView item"); return false; } //We need to find the relative position of the handle to the parent view //Then we can work out if the touch is within the handle int[] parentItemPos = new int[2]; itemView.getLocationInWindow(parentItemPos); int[] handlePos = new int[2]; handleView.getLocationInWindow(handlePos); int xRel = handlePos[0] - parentItemPos[0]; int yRel = handlePos[1] - parentItemPos[1]; Rect touchBounds = new Rect(itemView.getLeft() + xRel, itemView.getTop() + yRel, itemView.getLeft() + xRel + handleView.getWidth(), itemView.getTop() + yRel + handleView.getHeight() ); if (touchBounds.contains((int)e.getX(), (int)e.getY())) dragging = true; debugLog("parentItemPos = " + parentItemPos[0] + " " + parentItemPos[1]); debugLog("handlePos = " + handlePos[0] + " " + handlePos[1]); } setIsDragging(dragging); if (dragging) { debugLog("Started Drag"); floatingItem = creatFloatingBitmap(itemView); fingerAnchorY = (int)e.getY(); fingerOffsetInViewY = fingerAnchorY - itemView.getTop(); fingerY = fingerAnchorY; selectedDragItem = rv.getChildItemId(itemView); debugLog("selectedDragItem = " + selectedDragItem); return true; } } return false; } @Override public void onTouchEvent(RecyclerView rv, MotionEvent e) { debugLog("onTouchEvent"); if ((e.getAction() == MotionEvent.ACTION_UP) || (e.getAction() == MotionEvent.ACTION_CANCEL)) { if ((e.getAction() == MotionEvent.ACTION_UP) && selectedDragItem != -1) { long newPos = getNewPostion(rv); if (moveInterface != null) moveInterface.moveElement((int) selectedDragItem, (int) newPos); } selectedDragItem = -1; floatingItem = null; rv.invalidateItemDecorations(); return; } fingerY = (int)e.getY(); if (floatingItem!=null) { floatingItemBounds.top = fingerY - fingerOffsetInViewY; if (floatingItemBounds.top < -floatingItemStatingBounds.height()/2) //Allow half the view out the top floatingItemBounds.top = -floatingItemStatingBounds.height()/2; floatingItemBounds.bottom = floatingItemBounds.top + floatingItemStatingBounds.height(); floatingItem.setBounds(floatingItemBounds); } //Do auto scrolling at end of list float scrollAmmount=0; if (fingerY > (rv.getHeight() * (1-autoScrollWindow))) { scrollAmmount = (fingerY - (rv.getHeight() * (1-autoScrollWindow))); } else if (fingerY < (rv.getHeight() * autoScrollWindow)) { scrollAmmount = (fingerY - (rv.getHeight() * autoScrollWindow)); } debugLog("Scroll: " + scrollAmmount); scrollAmmount *= autoScrollSpeed; rv.scrollBy(0, (int)scrollAmmount); rv.invalidateItemDecorations();// Redraw } private void setIsDragging(final boolean dragging) { if(dragging != isDragging) { isDragging = dragging; if(dragStateChangedListener != null) { if (isDragging) { dragStateChangedListener.onDragStart(); } else { dragStateChangedListener.onDragStop(); } } } } public void setDragStateChangedListener(final OnDragStateChangedListener dragStateChangedListener) { this.dragStateChangedListener = dragStateChangedListener; } Paint bgColor = new Paint(); @Override public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { if (floatingItem != null) { floatingItem.setAlpha((int)(255 * floatingItemAlpha)); bgColor.setColor(floatingItemBgColor); c.drawRect(floatingItemBounds,bgColor); floatingItem.draw(c); } } RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { // TODO Auto-generated method stub super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); debugLog("Scrolled: " + dx + " " + dy); fingerAnchorY -= dy; } }; private BitmapDrawable creatFloatingBitmap(View v) { floatingItemStatingBounds = new Rect(v.getLeft(), v.getTop(),v.getRight(), v.getBottom()); floatingItemBounds = new Rect(floatingItemStatingBounds); Bitmap bitmap = Bitmap.createBitmap(floatingItemStatingBounds.width(), floatingItemStatingBounds.height(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); v.draw(canvas); BitmapDrawable retDrawable = new BitmapDrawable(v.getResources(), bitmap); retDrawable.setBounds(floatingItemBounds); return retDrawable; } }
Library/src/main/java/com/emtronics/dragsortrecycler/DragSortRecycler.java
/* * DragSortRecycler * * Added drag and drop functionality to your RecyclerView * * * Copyright 2014 Emile Belanger. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.emtronics.dragsortrecycler; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.MotionEvent; import android.view.View; public class DragSortRecycler extends RecyclerView.ItemDecoration implements RecyclerView.OnItemTouchListener { final String TAG = "RecyclerDragSort"; final boolean DEBUG = false; private int dragHandleWidth = 0; private long selectedDragItem = -1; private int fingerAnchorY; private int fingerY; private int fingerOffsetInViewY; private float autoScrollWindow = 0.1f; private float autoScrollSpeed = 0.5f; private BitmapDrawable floatingItem; private Rect floatingItemStatingBounds; private Rect floatingItemBounds; private float floatingItemAlpha = 0.5f; private int floatingItemBgColor = 0; private int viewHandleId = -1; ItemMovedInterface moveInterface; public interface ItemMovedInterface { public void moveElement(int from, int to); } private void debugLog(String log) { if (DEBUG) Log.d(TAG, log); } public RecyclerView.OnScrollListener getScrollListener() { return scrollListener; } /* * Set the item move interface */ public void setItemMoveInterface(ItemMovedInterface swif) { moveInterface = swif; } public void setViewHandleId(int id) { viewHandleId = id; } public void setLeftDragArea(int w) { dragHandleWidth = w; } public void setFloatingAlpha(float a) { floatingItemAlpha = a; } public void setFloatingBgColor(int c) { floatingItemBgColor = c; } /* Set the window at top and bottom of list, must be between 0 and 0.5 For example 0.1 uses the top and bottom 10% of the lists for scrolling */ public void setAutoScrollWindow(float w) { autoScrollWindow = w; } /* Set the autoscroll speed, default is 0.5 */ public void setAutoScrollSpeed(float speed) { autoScrollSpeed = speed; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView rv, RecyclerView.State state) { super.getItemOffsets(outRect, view, rv, state); debugLog("getItemOffsets"); debugLog("View top = " + view.getTop()); if (selectedDragItem != -1) { long itemId = rv.getChildItemId(view); debugLog("itemId =" + itemId); //Movement of finger float totalMovment = fingerY-fingerAnchorY; if (itemId == selectedDragItem) { view.setVisibility(View.INVISIBLE); } else { //Make view visible uncase invisible view.setVisibility(View.VISIBLE); //Find middle of the floatingItem float floatMiddleY = floatingItemBounds.top + floatingItemBounds.height()/2; //Moving down the list //These will auto-animate if the device continually send touch motion events // if (totalMovment>0) { if ((itemId > selectedDragItem) && (view.getTop() < floatMiddleY)) { float amountUp = ((float)floatMiddleY - view.getTop()) / (float)view.getHeight(); // amountUp *= 0.5f; if (amountUp > 1) amountUp = 1; outRect.top = -(int)(floatingItemBounds.height()*amountUp); outRect.bottom = (int)(floatingItemBounds.height()*amountUp); } }//Moving up the list // else if (totalMovment < 0) { if((itemId < selectedDragItem) && (view.getBottom() > floatMiddleY)) { float amountDown = ((float)view.getBottom() - floatMiddleY) / (float)view.getHeight(); // amountDown *= 0.5f; if (amountDown > 1) amountDown = 1; outRect.top = (int)(floatingItemBounds.height()*amountDown); outRect.bottom = -(int)(floatingItemBounds.height()*amountDown); } } } } else { outRect.top = 0; outRect.bottom = 0; //Make view visible incase invisible view.setVisibility(View.VISIBLE); } } /** * Find the new position by scanning through the items on * screen and finding the positional relationship. * This *seems* to work, another method would be to use * getItemOffsets, but I think that could miss items?.. */ private long getNewPostion(RecyclerView rv) { int itemsOnScreen = rv.getLayoutManager().getChildCount(); float floatMiddleY = floatingItemBounds.top + floatingItemBounds.height()/2; long above=0; long below = rv.getLayoutManager().getItemCount(); for (int n=0;n < itemsOnScreen;n++) //Scan though items on screen, however they may not { // be in order! View view = rv.getLayoutManager().getChildAt(n); long itemId = rv.getChildItemId(view); if (itemId == selectedDragItem) //Don't check against itself! continue; float viewMiddleY = view.getTop() + view.getHeight()/2; if (floatMiddleY > viewMiddleY) //Is above this item { if (itemId > above) above = itemId; } else if (floatMiddleY <= viewMiddleY) //Is below this item { if (itemId < below) below = itemId; } } debugLog("above = " + above + " below = " + below); if (below < selectedDragItem) //Need to count itself below++; return below - 1; } @Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { Log.d(TAG,"onInterceptTouchEvent"); //if (e.getAction() == MotionEvent.ACTION_DOWN) { View itemView = rv.findChildViewUnder(e.getX(), e.getY()); if (itemView==null) return false; boolean dragging = false; if ((dragHandleWidth > 0 ) && (e.getX() < dragHandleWidth)) { dragging = true; } else if (viewHandleId != -1) { //Find the handle in the list item View handleView = itemView.findViewById(viewHandleId); if (handleView == null) { Log.e(TAG, "The view ID " + viewHandleId + " was not found in the RecycleView item"); return false; } //We need to find the relative position of the handle to the parent view //Then we can work out if the touch is within the handle int[] parentItemPos = new int[2]; itemView.getLocationInWindow(parentItemPos); int[] handlePos = new int[2]; handleView.getLocationInWindow(handlePos); int xRel = handlePos[0] - parentItemPos[0]; int yRel = handlePos[1] - parentItemPos[1]; Rect touchBounds = new Rect(itemView.getLeft() + xRel, itemView.getTop() + yRel, itemView.getLeft() + xRel + handleView.getWidth(), itemView.getTop() + yRel + handleView.getHeight() ); if (touchBounds.contains((int)e.getX(), (int)e.getY())) dragging = true; debugLog("parentItemPos = " + parentItemPos[0] + " " + parentItemPos[1]); debugLog("handlePos = " + handlePos[0] + " " + handlePos[1]); } if (dragging) { debugLog("Started Drag"); floatingItem = creatFloatingBitmap(itemView); fingerAnchorY = (int)e.getY(); fingerOffsetInViewY = fingerAnchorY - itemView.getTop(); fingerY = fingerAnchorY; selectedDragItem = rv.getChildItemId(itemView); debugLog("selectedDragItem = " + selectedDragItem); return true; } } return false; } @Override public void onTouchEvent(RecyclerView rv, MotionEvent e) { debugLog("onTouchEvent"); if ((e.getAction() == MotionEvent.ACTION_UP) || (e.getAction() == MotionEvent.ACTION_CANCEL)) { if ((e.getAction() == MotionEvent.ACTION_UP) && selectedDragItem != -1) { long newPos = getNewPostion(rv); if (moveInterface != null) moveInterface.moveElement((int) selectedDragItem, (int) newPos); } selectedDragItem = -1; floatingItem = null; rv.invalidateItemDecorations(); return; } fingerY = (int)e.getY(); if (floatingItem!=null) { floatingItemBounds.top = fingerY - fingerOffsetInViewY; if (floatingItemBounds.top < -floatingItemStatingBounds.height()/2) //Allow half the view out the top floatingItemBounds.top = -floatingItemStatingBounds.height()/2; floatingItemBounds.bottom = floatingItemBounds.top + floatingItemStatingBounds.height(); floatingItem.setBounds(floatingItemBounds); } //Do auto scrolling at end of list float scrollAmmount=0; if (fingerY > (rv.getHeight() * (1-autoScrollWindow))) { scrollAmmount = (fingerY - (rv.getHeight() * (1-autoScrollWindow))); } else if (fingerY < (rv.getHeight() * autoScrollWindow)) { scrollAmmount = (fingerY - (rv.getHeight() * autoScrollWindow)); } debugLog("Scroll: " + scrollAmmount); scrollAmmount *= autoScrollSpeed; rv.scrollBy(0, (int)scrollAmmount); rv.invalidateItemDecorations();// Redraw } Paint bgColor = new Paint(); @Override public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { if (floatingItem != null) { floatingItem.setAlpha((int)(255 * floatingItemAlpha)); bgColor.setColor(floatingItemBgColor); c.drawRect(floatingItemBounds,bgColor); floatingItem.draw(c); } } RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { // TODO Auto-generated method stub super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); debugLog("Scrolled: " + dx + " " + dy); fingerAnchorY -= dy; } }; private BitmapDrawable creatFloatingBitmap(View v) { floatingItemStatingBounds = new Rect(v.getLeft(), v.getTop(),v.getRight(), v.getBottom()); floatingItemBounds = new Rect(floatingItemStatingBounds); Bitmap bitmap = Bitmap.createBitmap(floatingItemStatingBounds.width(), floatingItemStatingBounds.height(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); v.draw(canvas); BitmapDrawable retDrawable = new BitmapDrawable(v.getResources(), bitmap); retDrawable.setBounds(floatingItemBounds); return retDrawable; } }
Add OnDragStateChangedListener This listener could be used to react when the user start or stop dragging items around
Library/src/main/java/com/emtronics/dragsortrecycler/DragSortRecycler.java
Add OnDragStateChangedListener
<ide><path>ibrary/src/main/java/com/emtronics/dragsortrecycler/DragSortRecycler.java <ide> import android.util.Log; <ide> import android.view.MotionEvent; <ide> import android.view.View; <add>import android.support.annotation.Nullable; <ide> <ide> <ide> public class DragSortRecycler extends RecyclerView.ItemDecoration implements RecyclerView.OnItemTouchListener { <ide> <ide> <ide> ItemMovedInterface moveInterface; <add> private boolean isDragging; <add> @Nullable <add> OnDragStateChangedListener dragStateChangedListener; <add> <ide> <ide> <ide> public interface ItemMovedInterface <ide> { <ide> public void moveElement(int from, int to); <add> } <add> <add> public interface OnDragStateChangedListener { <add> public void onDragStart(); <add> public void onDragStop(); <ide> } <ide> <ide> private void debugLog(String log) <ide> <ide> } <ide> <add> setIsDragging(dragging); <ide> if (dragging) <ide> { <ide> debugLog("Started Drag"); <ide> <ide> rv.invalidateItemDecorations();// Redraw <ide> } <add> <add> private void setIsDragging(final boolean dragging) { <add> if(dragging != isDragging) { <add> isDragging = dragging; <add> if(dragStateChangedListener != null) { <add> if (isDragging) { <add> dragStateChangedListener.onDragStart(); <add> } else { <add> dragStateChangedListener.onDragStop(); <add> } <add> } <add> } <add> } <add> <add> public void setDragStateChangedListener(final OnDragStateChangedListener dragStateChangedListener) { <add> this.dragStateChangedListener = dragStateChangedListener; <add> } <add> <ide> <ide> Paint bgColor = new Paint(); <ide> @Override
Java
apache-2.0
c3a7d94a4acc62ecb0b4c588aa2f276e9b2b2fef
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.daemon.impl; import com.intellij.codeHighlighting.Pass; import com.intellij.codeInsight.daemon.GutterMark; import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInsight.intention.IntentionManager; import com.intellij.codeInspection.*; import com.intellij.codeInspection.ex.GlobalInspectionToolWrapper; import com.intellij.codeInspection.ex.InspectionToolWrapper; import com.intellij.codeInspection.ex.LocalInspectionToolWrapper; import com.intellij.lang.ASTNode; import com.intellij.lang.annotation.Annotation; import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.lang.annotation.ProblemGroup; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.HighlighterColors; import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.editor.colors.*; import com.intellij.openapi.editor.ex.RangeHighlighterEx; import com.intellij.openapi.editor.markup.GutterIconRenderer; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.util.*; import com.intellij.openapi.util.text.StringUtil; import com.intellij.profile.codeInspection.InspectionProjectProfileManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.util.ArrayUtil; import com.intellij.util.BitUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.xml.util.XmlStringUtil; import org.intellij.lang.annotations.MagicConstant; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.util.*; import java.util.List; public class HighlightInfo implements Segment { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.HighlightInfo"); // optimization: if tooltip contains this marker object, then it replaced with description field in getTooltip() private static final String DESCRIPTION_PLACEHOLDER = "\u0000"; private static final byte BIJECTIVE_MASK = 0x1; private static final byte HAS_HINT_MASK = 0x2; private static final byte FROM_INJECTION_MASK = 0x4; private static final byte AFTER_END_OF_LINE_MASK = 0x8; private static final byte FILE_LEVEL_ANNOTATION_MASK = 0x10; private static final byte NEEDS_UPDATE_ON_TYPING_MASK = 0x20; @MagicConstant(intValues = { BIJECTIVE_MASK, HAS_HINT_MASK, FROM_INJECTION_MASK, AFTER_END_OF_LINE_MASK, FILE_LEVEL_ANNOTATION_MASK, NEEDS_UPDATE_ON_TYPING_MASK}) private @interface FlagConstant { } public final TextAttributes forcedTextAttributes; public final TextAttributesKey forcedTextAttributesKey; @NotNull public final HighlightInfoType type; public final int startOffset; public final int endOffset; public List<Pair<IntentionActionDescriptor, TextRange>> quickFixActionRanges; public List<Pair<IntentionActionDescriptor, RangeMarker>> quickFixActionMarkers; private final String description; private final String toolTip; @NotNull private final HighlightSeverity severity; private final GutterMark gutterIconRenderer; private final ProblemGroup myProblemGroup; private final String inspectionToolId; private int group; private int fixStartOffset; private int fixEndOffset; /** * @see FlagConstant for allowed values */ private volatile byte myFlags; final int navigationShift; JComponent fileLevelComponent; @Nullable("null means it the same as highlighter") RangeMarker fixMarker; volatile RangeHighlighterEx highlighter; // modified in EDT only PsiElement psiElement; /** * Returns the HighlightInfo instance from which the given range highlighter was created, or null if there isn't any. */ @Nullable public static HighlightInfo fromRangeHighlighter(@NotNull RangeHighlighter highlighter) { Object errorStripeTooltip = highlighter.getErrorStripeTooltip(); return errorStripeTooltip instanceof HighlightInfo ? (HighlightInfo)errorStripeTooltip : null; } @NotNull ProperTextRange getFixTextRange() { return new ProperTextRange(fixStartOffset, fixEndOffset); } void setFromInjection(boolean fromInjection) { setFlag(FROM_INJECTION_MASK, fromInjection); } @Nullable public String getToolTip() { String toolTip = this.toolTip; String description = this.description; if (toolTip == null || description == null || !toolTip.contains(DESCRIPTION_PLACEHOLDER)) return toolTip; String decoded = StringUtil.replace(toolTip, DESCRIPTION_PLACEHOLDER, XmlStringUtil.escapeString(description)); return XmlStringUtil.wrapInHtml(decoded); } /** * Encodes \p tooltip so that substrings equal to a \p description * are replaced with the special placeholder to reduce size of the * tooltip. If encoding takes place, <html></html> tags are * stripped of the tooltip. * * @param tooltip - html text * @param description - plain text (not escaped) * * @return encoded tooltip (stripped html text with one or more placeholder characters) * or tooltip without changes. */ private static String encodeTooltip(String tooltip, String description) { if (tooltip == null || description == null || description.isEmpty()) return tooltip; String encoded = StringUtil.replace(tooltip, XmlStringUtil.escapeString(description), DESCRIPTION_PLACEHOLDER); //noinspection StringEquality if (encoded == tooltip) { return tooltip; } if (encoded.equals(DESCRIPTION_PLACEHOLDER)) encoded = DESCRIPTION_PLACEHOLDER; return XmlStringUtil.stripHtml(encoded); } public String getDescription() { return description; } @Nullable public String getInspectionToolId() { return inspectionToolId; } private boolean isFlagSet(@FlagConstant byte mask) { return BitUtil.isSet(myFlags, mask); } private void setFlag(@FlagConstant byte mask, boolean value) { myFlags = BitUtil.set(myFlags, mask, value); } boolean isFileLevelAnnotation() { return isFlagSet(FILE_LEVEL_ANNOTATION_MASK); } boolean isBijective() { return isFlagSet(BIJECTIVE_MASK); } void setBijective(boolean bijective) { setFlag(BIJECTIVE_MASK, bijective); } @NotNull public HighlightSeverity getSeverity() { return severity; } public RangeHighlighterEx getHighlighter() { return highlighter; } /** * Modified only in EDT. */ public void setHighlighter(@Nullable RangeHighlighterEx highlighter) { ApplicationManager.getApplication().assertIsDispatchThread(); this.highlighter = highlighter; } public boolean isAfterEndOfLine() { return isFlagSet(AFTER_END_OF_LINE_MASK); } @Nullable public TextAttributes getTextAttributes(@Nullable PsiElement element, @Nullable EditorColorsScheme editorColorsScheme) { if (forcedTextAttributes != null) { return forcedTextAttributes; } EditorColorsScheme colorsScheme = getColorsScheme(editorColorsScheme); if (forcedTextAttributesKey != null) { return colorsScheme.getAttributes(forcedTextAttributesKey); } return getAttributesByType(element, type, colorsScheme); } public static TextAttributes getAttributesByType(@Nullable PsiElement element, @NotNull HighlightInfoType type, @NotNull TextAttributesScheme colorsScheme) { SeverityRegistrar severityRegistrar = SeverityRegistrar.getSeverityRegistrar(element != null ? element.getProject() : null); TextAttributes textAttributes = severityRegistrar.getTextAttributesBySeverity(type.getSeverity(element)); if (textAttributes != null) return textAttributes; TextAttributesKey key = type.getAttributesKey(); return colorsScheme.getAttributes(key); } @Nullable @SuppressWarnings("deprecation") Color getErrorStripeMarkColor(@NotNull PsiElement element, @Nullable("when null, a global scheme will be used") EditorColorsScheme colorsScheme) { if (forcedTextAttributes != null) { return forcedTextAttributes.getErrorStripeColor(); } EditorColorsScheme scheme = getColorsScheme(colorsScheme); if (forcedTextAttributesKey != null) { TextAttributes forcedTextAttributes = scheme.getAttributes(forcedTextAttributesKey); if (forcedTextAttributes != null) { Color errorStripeColor = forcedTextAttributes.getErrorStripeColor(); // let's copy above behaviour of forcedTextAttributes stripe color, but I'm not sure the behaviour is correct in general if (errorStripeColor != null) { return errorStripeColor; } } } if (getSeverity() == HighlightSeverity.ERROR) { return scheme.getAttributes(CodeInsightColors.ERRORS_ATTRIBUTES).getErrorStripeColor(); } if (getSeverity() == HighlightSeverity.WARNING) { return scheme.getAttributes(CodeInsightColors.WARNINGS_ATTRIBUTES).getErrorStripeColor(); } if (getSeverity() == HighlightSeverity.INFO){ return scheme.getAttributes(CodeInsightColors.INFO_ATTRIBUTES).getErrorStripeColor(); } if (getSeverity() == HighlightSeverity.WEAK_WARNING){ return scheme.getAttributes(CodeInsightColors.WEAK_WARNING_ATTRIBUTES).getErrorStripeColor(); } if (getSeverity() == HighlightSeverity.GENERIC_SERVER_ERROR_OR_WARNING) { return scheme.getAttributes(CodeInsightColors.GENERIC_SERVER_ERROR_OR_WARNING).getErrorStripeColor(); } TextAttributes attributes = getAttributesByType(element, type, scheme); return attributes == null ? null : attributes.getErrorStripeColor(); } @NotNull private static EditorColorsScheme getColorsScheme(@Nullable EditorColorsScheme customScheme) { return customScheme != null ? customScheme : EditorColorsManager.getInstance().getGlobalScheme(); } @Nullable private static String htmlEscapeToolTip(@Nullable String unescapedTooltip) { return unescapedTooltip == null ? null : XmlStringUtil.wrapInHtml(XmlStringUtil.escapeString(unescapedTooltip)); } private static class Holder { private static final HighlightInfoFilter[] FILTERS = HighlightInfoFilter.EXTENSION_POINT_NAME.getExtensions(); } boolean needUpdateOnTyping() { return isFlagSet(NEEDS_UPDATE_ON_TYPING_MASK); } protected HighlightInfo(@Nullable TextAttributes forcedTextAttributes, @Nullable TextAttributesKey forcedTextAttributesKey, @NotNull HighlightInfoType type, int startOffset, int endOffset, @Nullable String escapedDescription, @Nullable String escapedToolTip, @NotNull HighlightSeverity severity, boolean afterEndOfLine, @Nullable Boolean needsUpdateOnTyping, boolean isFileLevelAnnotation, int navigationShift, ProblemGroup problemGroup, @Nullable String inspectionToolId, GutterMark gutterIconRenderer, int group) { if (startOffset < 0 || startOffset > endOffset) { LOG.error("Incorrect highlightInfo bounds. description="+escapedDescription+"; startOffset="+startOffset+"; endOffset="+endOffset+";type="+type); } this.forcedTextAttributes = forcedTextAttributes; this.forcedTextAttributesKey = forcedTextAttributesKey; this.type = type; this.startOffset = startOffset; this.endOffset = endOffset; fixStartOffset = startOffset; fixEndOffset = endOffset; description = escapedDescription; // optimization: do not retain extra memory if can recompute toolTip = encodeTooltip(escapedToolTip, escapedDescription); this.severity = severity; setFlag(AFTER_END_OF_LINE_MASK, afterEndOfLine); setFlag(NEEDS_UPDATE_ON_TYPING_MASK, calcNeedUpdateOnTyping(needsUpdateOnTyping, type)); setFlag(FILE_LEVEL_ANNOTATION_MASK, isFileLevelAnnotation); this.navigationShift = navigationShift; myProblemGroup = problemGroup; this.gutterIconRenderer = gutterIconRenderer; this.inspectionToolId = inspectionToolId; this.group = group; } private static boolean calcNeedUpdateOnTyping(@Nullable Boolean needsUpdateOnTyping, HighlightInfoType type) { if (needsUpdateOnTyping != null) { return needsUpdateOnTyping.booleanValue(); } if (type instanceof HighlightInfoType.UpdateOnTypingSuppressible) { return ((HighlightInfoType.UpdateOnTypingSuppressible)type).needsUpdateOnTyping(); } return true; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof HighlightInfo)) return false; HighlightInfo info = (HighlightInfo)obj; return info.getSeverity() == getSeverity() && info.startOffset == startOffset && info.endOffset == endOffset && Comparing.equal(info.type, type) && Comparing.equal(info.gutterIconRenderer, gutterIconRenderer) && Comparing.equal(info.forcedTextAttributes, forcedTextAttributes) && Comparing.equal(info.forcedTextAttributesKey, forcedTextAttributesKey) && Comparing.strEqual(info.getDescription(), getDescription()); } protected boolean equalsByActualOffset(@NotNull HighlightInfo info) { if (info == this) return true; return info.getSeverity() == getSeverity() && info.getActualStartOffset() == getActualStartOffset() && info.getActualEndOffset() == getActualEndOffset() && Comparing.equal(info.type, type) && Comparing.equal(info.gutterIconRenderer, gutterIconRenderer) && Comparing.equal(info.forcedTextAttributes, forcedTextAttributes) && Comparing.equal(info.forcedTextAttributesKey, forcedTextAttributesKey) && Comparing.strEqual(info.getDescription(), getDescription()); } @Override public int hashCode() { return startOffset; } @Override public String toString() { String s = "HighlightInfo(" + startOffset + "," + endOffset+")"; if (getActualStartOffset() != startOffset || getActualEndOffset() != endOffset) { s += "; actual: (" + getActualStartOffset() + "," + getActualEndOffset() + ")"; } if (highlighter != null) s += " text='" + getText() + "'"; if (getDescription() != null) s+= ", description='" + getDescription() + "'"; s += " severity=" + getSeverity(); s += " group=" + getGroup(); if (quickFixActionRanges != null) { s+= "; quickFixes: "+quickFixActionRanges; } if (gutterIconRenderer != null) { s += "; gutter: " + gutterIconRenderer; } return s; } @NotNull public static Builder newHighlightInfo(@NotNull HighlightInfoType type) { return new B(type); } void setGroup(int group) { this.group = group; } public interface Builder { // only one 'range' call allowed @NotNull Builder range(@NotNull TextRange textRange); @NotNull Builder range(@NotNull ASTNode node); @NotNull Builder range(@NotNull PsiElement element); @NotNull Builder range(@NotNull PsiElement element, @NotNull TextRange rangeInElement); @NotNull Builder range(@NotNull PsiElement element, int start, int end); @NotNull Builder range(int start, int end); @NotNull Builder gutterIconRenderer(@NotNull GutterIconRenderer gutterIconRenderer); @NotNull Builder problemGroup(@NotNull ProblemGroup problemGroup); @NotNull Builder inspectionToolId(@NotNull String inspectionTool); // only one allowed @NotNull Builder description(@NotNull String description); @NotNull Builder descriptionAndTooltip(@NotNull String description); // only one allowed @NotNull Builder textAttributes(@NotNull TextAttributes attributes); @NotNull Builder textAttributes(@NotNull TextAttributesKey attributesKey); // only one allowed @NotNull Builder unescapedToolTip(@NotNull String unescapedToolTip); @NotNull Builder escapedToolTip(@NotNull String escapedToolTip); @NotNull Builder endOfLine(); @NotNull Builder needsUpdateOnTyping(boolean update); @NotNull Builder severity(@NotNull HighlightSeverity severity); @NotNull Builder fileLevelAnnotation(); @NotNull Builder navigationShift(int navigationShift); @NotNull Builder group(int group); @Nullable("null means filtered out") HighlightInfo create(); @NotNull HighlightInfo createUnconditionally(); } private static boolean isAcceptedByFilters(@NotNull HighlightInfo info, @Nullable PsiElement psiElement) { PsiFile file = psiElement == null ? null : psiElement.getContainingFile(); for (HighlightInfoFilter filter : Holder.FILTERS) { if (!filter.accept(info, file)) { return false; } } info.psiElement = psiElement; return true; } private static class B implements Builder { private Boolean myNeedsUpdateOnTyping; private TextAttributes forcedTextAttributes; private TextAttributesKey forcedTextAttributesKey; private final HighlightInfoType type; private int startOffset = -1; private int endOffset = -1; private String escapedDescription; private String escapedToolTip; private HighlightSeverity severity; private boolean isAfterEndOfLine; private boolean isFileLevelAnnotation; private int navigationShift; private GutterIconRenderer gutterIconRenderer; private ProblemGroup problemGroup; private String inspectionToolId; private PsiElement psiElement; private int group; private B(@NotNull HighlightInfoType type) { this.type = type; } @NotNull @Override public Builder gutterIconRenderer(@NotNull GutterIconRenderer gutterIconRenderer) { assert this.gutterIconRenderer == null : "gutterIconRenderer already set"; this.gutterIconRenderer = gutterIconRenderer; return this; } @NotNull @Override public Builder problemGroup(@NotNull ProblemGroup problemGroup) { assert this.problemGroup == null : "problemGroup already set"; this.problemGroup = problemGroup; return this; } @NotNull @Override public Builder inspectionToolId(@NotNull String inspectionToolId) { assert this.inspectionToolId == null : "inspectionToolId already set"; this.inspectionToolId = inspectionToolId; return this; } @NotNull @Override public Builder description(@NotNull String description) { assert escapedDescription == null : "description already set"; escapedDescription = description; return this; } @NotNull @Override public Builder descriptionAndTooltip(@NotNull String description) { return description(description).unescapedToolTip(description); } @NotNull @Override public Builder textAttributes(@NotNull TextAttributes attributes) { assert forcedTextAttributes == null : "textAttributes already set"; forcedTextAttributes = attributes; return this; } @NotNull @Override public Builder textAttributes(@NotNull TextAttributesKey attributesKey) { assert forcedTextAttributesKey == null : "textAttributesKey already set"; forcedTextAttributesKey = attributesKey; return this; } @NotNull @Override public Builder unescapedToolTip(@NotNull String unescapedToolTip) { assert escapedToolTip == null : "Tooltip was already set"; escapedToolTip = htmlEscapeToolTip(unescapedToolTip); return this; } @NotNull @Override public Builder escapedToolTip(@NotNull String escapedToolTip) { assert this.escapedToolTip == null : "Tooltip was already set"; this.escapedToolTip = escapedToolTip; return this; } @NotNull @Override public Builder range(int start, int end) { assert startOffset == -1 && endOffset == -1 : "Offsets already set"; startOffset = start; endOffset = end; return this; } @NotNull @Override public Builder range(@NotNull TextRange textRange) { assert startOffset == -1 && endOffset == -1 : "Offsets already set"; startOffset = textRange.getStartOffset(); endOffset = textRange.getEndOffset(); return this; } @NotNull @Override public Builder range(@NotNull ASTNode node) { return range(node.getPsi()); } @NotNull @Override public Builder range(@NotNull PsiElement element) { assert psiElement == null : " psiElement already set"; psiElement = element; return range(element.getTextRange()); } @NotNull @Override public Builder range(@NotNull PsiElement element, @NotNull TextRange rangeInElement) { TextRange absoluteRange = rangeInElement.shiftRight(element.getTextRange().getStartOffset()); return range(element, absoluteRange.getStartOffset(), absoluteRange.getEndOffset()); } @NotNull @Override public Builder range(@NotNull PsiElement element, int start, int end) { assert psiElement == null : " psiElement already set"; psiElement = element; return range(start, end); } @NotNull @Override public Builder endOfLine() { isAfterEndOfLine = true; return this; } @NotNull @Override public Builder needsUpdateOnTyping(boolean update) { assert myNeedsUpdateOnTyping == null : " needsUpdateOnTyping already set"; myNeedsUpdateOnTyping = update; return this; } @NotNull @Override public Builder severity(@NotNull HighlightSeverity severity) { assert this.severity == null : " severity already set"; this.severity = severity; return this; } @NotNull @Override public Builder fileLevelAnnotation() { isFileLevelAnnotation = true; return this; } @NotNull @Override public Builder navigationShift(int navigationShift) { this.navigationShift = navigationShift; return this; } @NotNull @Override public Builder group(int group) { this.group = group; return this; } @Nullable @Override public HighlightInfo create() { HighlightInfo info = createUnconditionally(); LOG.assertTrue(psiElement != null || severity == HighlightInfoType.SYMBOL_TYPE_SEVERITY || severity == HighlightInfoType.INJECTED_FRAGMENT_SEVERITY || ArrayUtil.find(HighlightSeverity.DEFAULT_SEVERITIES, severity) != -1, "Custom type requires not-null element to detect its text attributes"); if (!isAcceptedByFilters(info, psiElement)) return null; return info; } @NotNull @Override public HighlightInfo createUnconditionally() { if (severity == null) { severity = type.getSeverity(psiElement); } return new HighlightInfo(forcedTextAttributes, forcedTextAttributesKey, type, startOffset, endOffset, escapedDescription, escapedToolTip, severity, isAfterEndOfLine, myNeedsUpdateOnTyping, isFileLevelAnnotation, navigationShift, problemGroup, inspectionToolId, gutterIconRenderer, group); } } public GutterMark getGutterIconRenderer() { return gutterIconRenderer; } @Nullable public ProblemGroup getProblemGroup() { return myProblemGroup; } @NotNull public static HighlightInfo fromAnnotation(@NotNull Annotation annotation) { return fromAnnotation(annotation, false); } @NotNull static HighlightInfo fromAnnotation(@NotNull Annotation annotation, boolean batchMode) { TextAttributes forcedAttributes = annotation.getEnforcedTextAttributes(); TextAttributesKey key = annotation.getTextAttributes(); TextAttributesKey forcedAttributesKey = forcedAttributes == null && key != HighlighterColors.NO_HIGHLIGHTING ? key : null; HighlightInfo info = new HighlightInfo( forcedAttributes, forcedAttributesKey, convertType(annotation), annotation.getStartOffset(), annotation.getEndOffset(), annotation.getMessage(), annotation.getTooltip(), annotation.getSeverity(), annotation.isAfterEndOfLine(), annotation.needsUpdateOnTyping(), annotation.isFileLevelAnnotation(), 0, annotation.getProblemGroup(), null, annotation.getGutterIconRenderer(), Pass.UPDATE_ALL); List<? extends Annotation.QuickFixInfo> fixes = batchMode ? annotation.getBatchFixes() : annotation.getQuickFixes(); if (fixes != null) { for (Annotation.QuickFixInfo quickFixInfo : fixes) { TextRange range = quickFixInfo.textRange; HighlightDisplayKey k = quickFixInfo.key != null ? quickFixInfo.key : HighlightDisplayKey.find(ANNOTATOR_INSPECTION_SHORT_NAME); info.registerFix(quickFixInfo.quickFix, null, HighlightDisplayKey.getDisplayNameByKey(k), range, k); } } return info; } private static final String ANNOTATOR_INSPECTION_SHORT_NAME = "Annotator"; @NotNull private static HighlightInfoType convertType(@NotNull Annotation annotation) { ProblemHighlightType type = annotation.getHighlightType(); if (type == ProblemHighlightType.LIKE_UNUSED_SYMBOL) return HighlightInfoType.UNUSED_SYMBOL; if (type == ProblemHighlightType.LIKE_UNKNOWN_SYMBOL) return HighlightInfoType.WRONG_REF; if (type == ProblemHighlightType.LIKE_DEPRECATED) return HighlightInfoType.DEPRECATED; if (type == ProblemHighlightType.LIKE_MARKED_FOR_REMOVAL) return HighlightInfoType.MARKED_FOR_REMOVAL; return convertSeverity(annotation.getSeverity()); } @NotNull @SuppressWarnings("deprecation") public static HighlightInfoType convertSeverity(@NotNull HighlightSeverity severity) { return severity == HighlightSeverity.ERROR? HighlightInfoType.ERROR : severity == HighlightSeverity.WARNING ? HighlightInfoType.WARNING : severity == HighlightSeverity.INFO ? HighlightInfoType.INFO : severity == HighlightSeverity.WEAK_WARNING ? HighlightInfoType.WEAK_WARNING : severity ==HighlightSeverity.GENERIC_SERVER_ERROR_OR_WARNING ? HighlightInfoType.GENERIC_WARNINGS_OR_ERRORS_FROM_SERVER : HighlightInfoType.INFORMATION; } @NotNull public static ProblemHighlightType convertType(HighlightInfoType infoType) { if (infoType == HighlightInfoType.ERROR || infoType == HighlightInfoType.WRONG_REF) return ProblemHighlightType.ERROR; if (infoType == HighlightInfoType.WARNING) return ProblemHighlightType.WARNING; if (infoType == HighlightInfoType.INFORMATION) return ProblemHighlightType.INFORMATION; return ProblemHighlightType.WEAK_WARNING; } @NotNull @SuppressWarnings("deprecation") public static ProblemHighlightType convertSeverityToProblemHighlight(HighlightSeverity severity) { return severity == HighlightSeverity.ERROR ? ProblemHighlightType.ERROR : severity == HighlightSeverity.WARNING ? ProblemHighlightType.WARNING : severity == HighlightSeverity.INFO ? ProblemHighlightType.INFO : severity == HighlightSeverity.WEAK_WARNING ? ProblemHighlightType.WEAK_WARNING : ProblemHighlightType.INFORMATION; } public boolean hasHint() { return isFlagSet(HAS_HINT_MASK); } void setHint(boolean hasHint) { setFlag(HAS_HINT_MASK, hasHint); } public int getActualStartOffset() { RangeHighlighterEx h = highlighter; return h == null || !h.isValid() ? startOffset : h.getStartOffset(); } public int getActualEndOffset() { RangeHighlighterEx h = highlighter; return h == null || !h.isValid() ? endOffset : h.getEndOffset(); } public static class IntentionActionDescriptor { private final IntentionAction myAction; private volatile List<IntentionAction> myOptions; private volatile HighlightDisplayKey myKey; private final ProblemGroup myProblemGroup; private final HighlightSeverity mySeverity; private final String myDisplayName; private final Icon myIcon; private Boolean myCanCleanup; IntentionActionDescriptor(@NotNull IntentionAction action, List<IntentionAction> options, String displayName) { this(action, options, displayName, null); } public IntentionActionDescriptor(@NotNull IntentionAction action, Icon icon) { this(action, null, null, icon); } IntentionActionDescriptor(@NotNull IntentionAction action, @Nullable List<IntentionAction> options, @Nullable String displayName, @Nullable Icon icon) { this(action, options, displayName, icon, null, null, null); } public IntentionActionDescriptor(@NotNull IntentionAction action, @Nullable List<IntentionAction> options, @Nullable String displayName, @Nullable Icon icon, @Nullable HighlightDisplayKey key, @Nullable ProblemGroup problemGroup, @Nullable HighlightSeverity severity) { myAction = action; myOptions = options; myDisplayName = displayName; myIcon = icon; myKey = key; myProblemGroup = problemGroup; mySeverity = severity; } @NotNull public IntentionAction getAction() { return myAction; } boolean isError() { return mySeverity == null || mySeverity.compareTo(HighlightSeverity.ERROR) >= 0; } boolean isInformation() { return HighlightSeverity.INFORMATION.equals(mySeverity); } boolean canCleanup(@NotNull PsiElement element) { if (myCanCleanup == null) { InspectionProfile profile = InspectionProjectProfileManager.getInstance(element.getProject()).getCurrentProfile(); HighlightDisplayKey key = myKey; if (key == null) { myCanCleanup = false; } else { InspectionToolWrapper toolWrapper = profile.getInspectionTool(key.toString(), element); myCanCleanup = toolWrapper != null && toolWrapper.isCleanupTool(); } } return myCanCleanup; } @Nullable public List<IntentionAction> getOptions(@NotNull PsiElement element, @Nullable Editor editor) { if (editor != null && Boolean.FALSE.equals(editor.getUserData(IntentionManager.SHOW_INTENTION_OPTIONS_KEY))) { return null; } List<IntentionAction> options = myOptions; HighlightDisplayKey key = myKey; if (myProblemGroup != null) { String problemName = myProblemGroup.getProblemName(); HighlightDisplayKey problemGroupKey = problemName != null ? HighlightDisplayKey.findById(problemName) : null; if (problemGroupKey != null) { key = problemGroupKey; } } if (options != null || key == null) { return options; } IntentionManager intentionManager = IntentionManager.getInstance(); List<IntentionAction> newOptions = intentionManager.getStandardIntentionOptions(key, element); InspectionProfile profile = InspectionProjectProfileManager.getInstance(element.getProject()).getCurrentProfile(); InspectionToolWrapper toolWrapper = profile.getInspectionTool(key.toString(), element); if (!(toolWrapper instanceof LocalInspectionToolWrapper)) { HighlightDisplayKey idKey = HighlightDisplayKey.findById(key.toString()); if (idKey != null) { toolWrapper = profile.getInspectionTool(idKey.toString(), element); } } if (toolWrapper != null) { myCanCleanup = toolWrapper.isCleanupTool(); IntentionAction fixAllIntention = intentionManager.createFixAllIntention(toolWrapper, myAction); InspectionProfileEntry wrappedTool = toolWrapper instanceof LocalInspectionToolWrapper ? ((LocalInspectionToolWrapper)toolWrapper).getTool() : ((GlobalInspectionToolWrapper)toolWrapper).getTool(); if (wrappedTool instanceof DefaultHighlightVisitorBasedInspection.AnnotatorBasedInspection) { List<IntentionAction> actions = Collections.emptyList(); if (myProblemGroup instanceof SuppressableProblemGroup) { actions = Arrays.asList(((SuppressableProblemGroup)myProblemGroup).getSuppressActions(element)); } if (fixAllIntention != null) { if (actions.isEmpty()) { return Collections.singletonList(fixAllIntention); } else { actions = new ArrayList<>(actions); actions.add(fixAllIntention); } } return actions; } ContainerUtil.addIfNotNull(newOptions, fixAllIntention); if (wrappedTool instanceof CustomSuppressableInspectionTool) { IntentionAction[] suppressActions = ((CustomSuppressableInspectionTool)wrappedTool).getSuppressActions(element); if (suppressActions != null) { ContainerUtil.addAll(newOptions, suppressActions); } } else { SuppressQuickFix[] suppressFixes = wrappedTool.getBatchSuppressActions(element); if (suppressFixes.length > 0) { newOptions.addAll(ContainerUtil.map(suppressFixes, SuppressIntentionActionFromFix::convertBatchToSuppressIntentionAction)); } } } if (myProblemGroup instanceof SuppressableProblemGroup) { IntentionAction[] suppressActions = ((SuppressableProblemGroup)myProblemGroup).getSuppressActions(element); ContainerUtil.addAll(newOptions, suppressActions); } //noinspection SynchronizeOnThis synchronized (this) { options = myOptions; if (options == null) { myOptions = options = newOptions; } myKey = null; } return options; } @Nullable public String getDisplayName() { return myDisplayName; } @Override public String toString() { String text = getAction().getText(); return "descriptor: " + (text.isEmpty() ? getAction().getClass() : text); } @Nullable public Icon getIcon() { return myIcon; } @Override public boolean equals(Object obj) { return obj instanceof IntentionActionDescriptor && myAction.equals(((IntentionActionDescriptor)obj).myAction); } } @Override public int getStartOffset() { return getActualStartOffset(); } @Override public int getEndOffset() { return getActualEndOffset(); } int getGroup() { return group; } boolean isFromInjection() { return isFlagSet(FROM_INJECTION_MASK); } @NotNull public String getText() { if (isFileLevelAnnotation()) return ""; RangeHighlighterEx highlighter = this.highlighter; if (highlighter == null) { throw new RuntimeException("info not applied yet"); } if (!highlighter.isValid()) return ""; return highlighter.getDocument().getText(TextRange.create(highlighter)); } public void registerFix(@Nullable IntentionAction action, @Nullable List<IntentionAction> options, @Nullable String displayName, @Nullable TextRange fixRange, @Nullable HighlightDisplayKey key) { if (action == null) return; if (fixRange == null) fixRange = new TextRange(startOffset, endOffset); if (quickFixActionRanges == null) { quickFixActionRanges = ContainerUtil.createLockFreeCopyOnWriteList(); } IntentionActionDescriptor desc = new IntentionActionDescriptor(action, options, displayName, null, key, getProblemGroup(), getSeverity()); quickFixActionRanges.add(Pair.create(desc, fixRange)); fixStartOffset = Math.min (fixStartOffset, fixRange.getStartOffset()); fixEndOffset = Math.max (fixEndOffset, fixRange.getEndOffset()); if (action instanceof HintAction) { setHint(true); } } public void unregisterQuickFix(@NotNull Condition<? super IntentionAction> condition) { if (quickFixActionRanges != null) { quickFixActionRanges.removeIf(pair -> condition.value(pair.first.getAction())); } } }
platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/HighlightInfo.java
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.daemon.impl; import com.intellij.codeHighlighting.Pass; import com.intellij.codeInsight.daemon.GutterMark; import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInsight.intention.IntentionManager; import com.intellij.codeInspection.*; import com.intellij.codeInspection.ex.GlobalInspectionToolWrapper; import com.intellij.codeInspection.ex.InspectionToolWrapper; import com.intellij.codeInspection.ex.LocalInspectionToolWrapper; import com.intellij.lang.ASTNode; import com.intellij.lang.annotation.Annotation; import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.lang.annotation.ProblemGroup; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.HighlighterColors; import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.editor.colors.*; import com.intellij.openapi.editor.ex.RangeHighlighterEx; import com.intellij.openapi.editor.markup.GutterIconRenderer; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.util.*; import com.intellij.openapi.util.text.StringUtil; import com.intellij.profile.codeInspection.InspectionProjectProfileManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.util.ArrayUtil; import com.intellij.util.BitUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.xml.util.XmlStringUtil; import org.intellij.lang.annotations.MagicConstant; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.util.*; import java.util.List; public class HighlightInfo implements Segment { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.HighlightInfo"); // optimization: if tooltip contains this marker object, then it replaced with description field in getTooltip() private static final String DESCRIPTION_PLACEHOLDER = "\u0000"; private static final byte BIJECTIVE_MASK = 0x1; private static final byte HAS_HINT_MASK = 0x2; private static final byte FROM_INJECTION_MASK = 0x4; private static final byte AFTER_END_OF_LINE_MASK = 0x8; private static final byte FILE_LEVEL_ANNOTATION_MASK = 0x10; private static final byte NEEDS_UPDATE_ON_TYPING_MASK = 0x20; @MagicConstant(intValues = { BIJECTIVE_MASK, HAS_HINT_MASK, FROM_INJECTION_MASK, AFTER_END_OF_LINE_MASK, FILE_LEVEL_ANNOTATION_MASK, NEEDS_UPDATE_ON_TYPING_MASK}) private @interface FlagConstant { } public final TextAttributes forcedTextAttributes; public final TextAttributesKey forcedTextAttributesKey; @NotNull public final HighlightInfoType type; public final int startOffset; public final int endOffset; public List<Pair<IntentionActionDescriptor, TextRange>> quickFixActionRanges; public List<Pair<IntentionActionDescriptor, RangeMarker>> quickFixActionMarkers; private final String description; private final String toolTip; @NotNull private final HighlightSeverity severity; private final GutterMark gutterIconRenderer; private final ProblemGroup myProblemGroup; private final String inspectionToolId; private int group; private int fixStartOffset; private int fixEndOffset; /** * @see FlagConstant for allowed values */ private volatile byte myFlags; final int navigationShift; JComponent fileLevelComponent; @Nullable("null means it the same as highlighter") RangeMarker fixMarker; volatile RangeHighlighterEx highlighter; // modified in EDT only PsiElement psiElement; /** * Returns the HighlightInfo instance from which the given range highlighter was created, or null if there isn't any. */ @Nullable public static HighlightInfo fromRangeHighlighter(@NotNull RangeHighlighter highlighter) { Object errorStripeTooltip = highlighter.getErrorStripeTooltip(); return errorStripeTooltip instanceof HighlightInfo ? (HighlightInfo)errorStripeTooltip : null; } @NotNull ProperTextRange getFixTextRange() { return new ProperTextRange(fixStartOffset, fixEndOffset); } void setFromInjection(boolean fromInjection) { setFlag(FROM_INJECTION_MASK, fromInjection); } @Nullable public String getToolTip() { String toolTip = this.toolTip; String description = this.description; if (toolTip == null || description == null || !toolTip.contains(DESCRIPTION_PLACEHOLDER)) return toolTip; String decoded = StringUtil.replace(toolTip, DESCRIPTION_PLACEHOLDER, XmlStringUtil.escapeString(description)); return XmlStringUtil.wrapInHtml(decoded); } /** * Encodes \p tooltip so that substrings equal to a \p description * are replaced with the special placeholder to reduce size of the * tooltip. If encoding takes place, <html></html> tags are * stripped of the tooltip. * * @param tooltip - html text * @param description - plain text (not escaped) * * @return encoded tooltip (stripped html text with one or more placeholder characters) * or tooltip without changes. */ private static String encodeTooltip(String tooltip, String description) { if (tooltip == null || description == null || description.isEmpty()) return tooltip; String encoded = StringUtil.replace(tooltip, XmlStringUtil.escapeString(description), DESCRIPTION_PLACEHOLDER); //noinspection StringEquality if (encoded == tooltip) { return tooltip; } if (encoded.equals(DESCRIPTION_PLACEHOLDER)) encoded = DESCRIPTION_PLACEHOLDER; return XmlStringUtil.stripHtml(encoded); } public String getDescription() { return description; } @Nullable public String getInspectionToolId() { return inspectionToolId; } private boolean isFlagSet(@FlagConstant byte mask) { return BitUtil.isSet(myFlags, mask); } private void setFlag(@FlagConstant byte mask, boolean value) { myFlags = BitUtil.set(myFlags, mask, value); } boolean isFileLevelAnnotation() { return isFlagSet(FILE_LEVEL_ANNOTATION_MASK); } boolean isBijective() { return isFlagSet(BIJECTIVE_MASK); } void setBijective(boolean bijective) { setFlag(BIJECTIVE_MASK, bijective); } @NotNull public HighlightSeverity getSeverity() { return severity; } public RangeHighlighterEx getHighlighter() { return highlighter; } /** * Modified only in EDT. */ public void setHighlighter(@Nullable RangeHighlighterEx highlighter) { ApplicationManager.getApplication().assertIsDispatchThread(); this.highlighter = highlighter; } public boolean isAfterEndOfLine() { return isFlagSet(AFTER_END_OF_LINE_MASK); } @Nullable public TextAttributes getTextAttributes(@Nullable PsiElement element, @Nullable EditorColorsScheme editorColorsScheme) { if (forcedTextAttributes != null) { return forcedTextAttributes; } EditorColorsScheme colorsScheme = getColorsScheme(editorColorsScheme); if (forcedTextAttributesKey != null) { return colorsScheme.getAttributes(forcedTextAttributesKey); } return getAttributesByType(element, type, colorsScheme); } public static TextAttributes getAttributesByType(@Nullable PsiElement element, @NotNull HighlightInfoType type, @NotNull TextAttributesScheme colorsScheme) { SeverityRegistrar severityRegistrar = SeverityRegistrar.getSeverityRegistrar(element != null ? element.getProject() : null); TextAttributes textAttributes = severityRegistrar.getTextAttributesBySeverity(type.getSeverity(element)); if (textAttributes != null) return textAttributes; TextAttributesKey key = type.getAttributesKey(); return colorsScheme.getAttributes(key); } @Nullable @SuppressWarnings("deprecation") Color getErrorStripeMarkColor(@NotNull PsiElement element, @Nullable("when null, a global scheme will be used") EditorColorsScheme colorsScheme) { if (forcedTextAttributes != null) { return forcedTextAttributes.getErrorStripeColor(); } EditorColorsScheme scheme = getColorsScheme(colorsScheme); if (forcedTextAttributesKey != null) { TextAttributes forcedTextAttributes = scheme.getAttributes(forcedTextAttributesKey); if (forcedTextAttributes != null) { Color errorStripeColor = forcedTextAttributes.getErrorStripeColor(); // let's copy above behaviour of forcedTextAttributes stripe color, but I'm not sure the behaviour is correct in general if (errorStripeColor != null) { return errorStripeColor; } } } if (getSeverity() == HighlightSeverity.ERROR) { return scheme.getAttributes(CodeInsightColors.ERRORS_ATTRIBUTES).getErrorStripeColor(); } if (getSeverity() == HighlightSeverity.WARNING) { return scheme.getAttributes(CodeInsightColors.WARNINGS_ATTRIBUTES).getErrorStripeColor(); } if (getSeverity() == HighlightSeverity.INFO){ return scheme.getAttributes(CodeInsightColors.INFO_ATTRIBUTES).getErrorStripeColor(); } if (getSeverity() == HighlightSeverity.WEAK_WARNING){ return scheme.getAttributes(CodeInsightColors.WEAK_WARNING_ATTRIBUTES).getErrorStripeColor(); } if (getSeverity() == HighlightSeverity.GENERIC_SERVER_ERROR_OR_WARNING) { return scheme.getAttributes(CodeInsightColors.GENERIC_SERVER_ERROR_OR_WARNING).getErrorStripeColor(); } TextAttributes attributes = getAttributesByType(element, type, scheme); return attributes == null ? null : attributes.getErrorStripeColor(); } @NotNull private static EditorColorsScheme getColorsScheme(@Nullable EditorColorsScheme customScheme) { return customScheme != null ? customScheme : EditorColorsManager.getInstance().getGlobalScheme(); } @Nullable private static String htmlEscapeToolTip(@Nullable String unescapedTooltip) { return unescapedTooltip == null ? null : XmlStringUtil.wrapInHtml(XmlStringUtil.escapeString(unescapedTooltip)); } private static class Holder { private static final HighlightInfoFilter[] FILTERS = HighlightInfoFilter.EXTENSION_POINT_NAME.getExtensions(); } boolean needUpdateOnTyping() { return isFlagSet(NEEDS_UPDATE_ON_TYPING_MASK); } HighlightInfo(@Nullable TextAttributes forcedTextAttributes, @Nullable TextAttributesKey forcedTextAttributesKey, @NotNull HighlightInfoType type, int startOffset, int endOffset, @Nullable String escapedDescription, @Nullable String escapedToolTip, @NotNull HighlightSeverity severity, boolean afterEndOfLine, @Nullable Boolean needsUpdateOnTyping, boolean isFileLevelAnnotation, int navigationShift, ProblemGroup problemGroup, @Nullable String inspectionToolId, GutterMark gutterIconRenderer, int group) { if (startOffset < 0 || startOffset > endOffset) { LOG.error("Incorrect highlightInfo bounds. description="+escapedDescription+"; startOffset="+startOffset+"; endOffset="+endOffset+";type="+type); } this.forcedTextAttributes = forcedTextAttributes; this.forcedTextAttributesKey = forcedTextAttributesKey; this.type = type; this.startOffset = startOffset; this.endOffset = endOffset; fixStartOffset = startOffset; fixEndOffset = endOffset; description = escapedDescription; // optimization: do not retain extra memory if can recompute toolTip = encodeTooltip(escapedToolTip, escapedDescription); this.severity = severity; setFlag(AFTER_END_OF_LINE_MASK, afterEndOfLine); setFlag(NEEDS_UPDATE_ON_TYPING_MASK, calcNeedUpdateOnTyping(needsUpdateOnTyping, type)); setFlag(FILE_LEVEL_ANNOTATION_MASK, isFileLevelAnnotation); this.navigationShift = navigationShift; myProblemGroup = problemGroup; this.gutterIconRenderer = gutterIconRenderer; this.inspectionToolId = inspectionToolId; this.group = group; } private static boolean calcNeedUpdateOnTyping(@Nullable Boolean needsUpdateOnTyping, HighlightInfoType type) { if (needsUpdateOnTyping != null) { return needsUpdateOnTyping.booleanValue(); } if (type instanceof HighlightInfoType.UpdateOnTypingSuppressible) { return ((HighlightInfoType.UpdateOnTypingSuppressible)type).needsUpdateOnTyping(); } return true; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof HighlightInfo)) return false; HighlightInfo info = (HighlightInfo)obj; return info.getSeverity() == getSeverity() && info.startOffset == startOffset && info.endOffset == endOffset && Comparing.equal(info.type, type) && Comparing.equal(info.gutterIconRenderer, gutterIconRenderer) && Comparing.equal(info.forcedTextAttributes, forcedTextAttributes) && Comparing.equal(info.forcedTextAttributesKey, forcedTextAttributesKey) && Comparing.strEqual(info.getDescription(), getDescription()); } protected boolean equalsByActualOffset(@NotNull HighlightInfo info) { if (info == this) return true; return info.getSeverity() == getSeverity() && info.getActualStartOffset() == getActualStartOffset() && info.getActualEndOffset() == getActualEndOffset() && Comparing.equal(info.type, type) && Comparing.equal(info.gutterIconRenderer, gutterIconRenderer) && Comparing.equal(info.forcedTextAttributes, forcedTextAttributes) && Comparing.equal(info.forcedTextAttributesKey, forcedTextAttributesKey) && Comparing.strEqual(info.getDescription(), getDescription()); } @Override public int hashCode() { return startOffset; } @Override public String toString() { String s = "HighlightInfo(" + startOffset + "," + endOffset+")"; if (getActualStartOffset() != startOffset || getActualEndOffset() != endOffset) { s += "; actual: (" + getActualStartOffset() + "," + getActualEndOffset() + ")"; } if (highlighter != null) s += " text='" + getText() + "'"; if (getDescription() != null) s+= ", description='" + getDescription() + "'"; s += " severity=" + getSeverity(); s += " group=" + getGroup(); if (quickFixActionRanges != null) { s+= "; quickFixes: "+quickFixActionRanges; } if (gutterIconRenderer != null) { s += "; gutter: " + gutterIconRenderer; } return s; } @NotNull public static Builder newHighlightInfo(@NotNull HighlightInfoType type) { return new B(type); } void setGroup(int group) { this.group = group; } public interface Builder { // only one 'range' call allowed @NotNull Builder range(@NotNull TextRange textRange); @NotNull Builder range(@NotNull ASTNode node); @NotNull Builder range(@NotNull PsiElement element); @NotNull Builder range(@NotNull PsiElement element, @NotNull TextRange rangeInElement); @NotNull Builder range(@NotNull PsiElement element, int start, int end); @NotNull Builder range(int start, int end); @NotNull Builder gutterIconRenderer(@NotNull GutterIconRenderer gutterIconRenderer); @NotNull Builder problemGroup(@NotNull ProblemGroup problemGroup); @NotNull Builder inspectionToolId(@NotNull String inspectionTool); // only one allowed @NotNull Builder description(@NotNull String description); @NotNull Builder descriptionAndTooltip(@NotNull String description); // only one allowed @NotNull Builder textAttributes(@NotNull TextAttributes attributes); @NotNull Builder textAttributes(@NotNull TextAttributesKey attributesKey); // only one allowed @NotNull Builder unescapedToolTip(@NotNull String unescapedToolTip); @NotNull Builder escapedToolTip(@NotNull String escapedToolTip); @NotNull Builder endOfLine(); @NotNull Builder needsUpdateOnTyping(boolean update); @NotNull Builder severity(@NotNull HighlightSeverity severity); @NotNull Builder fileLevelAnnotation(); @NotNull Builder navigationShift(int navigationShift); @NotNull Builder group(int group); @Nullable("null means filtered out") HighlightInfo create(); @NotNull HighlightInfo createUnconditionally(); } private static boolean isAcceptedByFilters(@NotNull HighlightInfo info, @Nullable PsiElement psiElement) { PsiFile file = psiElement == null ? null : psiElement.getContainingFile(); for (HighlightInfoFilter filter : Holder.FILTERS) { if (!filter.accept(info, file)) { return false; } } info.psiElement = psiElement; return true; } private static class B implements Builder { private Boolean myNeedsUpdateOnTyping; private TextAttributes forcedTextAttributes; private TextAttributesKey forcedTextAttributesKey; private final HighlightInfoType type; private int startOffset = -1; private int endOffset = -1; private String escapedDescription; private String escapedToolTip; private HighlightSeverity severity; private boolean isAfterEndOfLine; private boolean isFileLevelAnnotation; private int navigationShift; private GutterIconRenderer gutterIconRenderer; private ProblemGroup problemGroup; private String inspectionToolId; private PsiElement psiElement; private int group; private B(@NotNull HighlightInfoType type) { this.type = type; } @NotNull @Override public Builder gutterIconRenderer(@NotNull GutterIconRenderer gutterIconRenderer) { assert this.gutterIconRenderer == null : "gutterIconRenderer already set"; this.gutterIconRenderer = gutterIconRenderer; return this; } @NotNull @Override public Builder problemGroup(@NotNull ProblemGroup problemGroup) { assert this.problemGroup == null : "problemGroup already set"; this.problemGroup = problemGroup; return this; } @NotNull @Override public Builder inspectionToolId(@NotNull String inspectionToolId) { assert this.inspectionToolId == null : "inspectionToolId already set"; this.inspectionToolId = inspectionToolId; return this; } @NotNull @Override public Builder description(@NotNull String description) { assert escapedDescription == null : "description already set"; escapedDescription = description; return this; } @NotNull @Override public Builder descriptionAndTooltip(@NotNull String description) { return description(description).unescapedToolTip(description); } @NotNull @Override public Builder textAttributes(@NotNull TextAttributes attributes) { assert forcedTextAttributes == null : "textAttributes already set"; forcedTextAttributes = attributes; return this; } @NotNull @Override public Builder textAttributes(@NotNull TextAttributesKey attributesKey) { assert forcedTextAttributesKey == null : "textAttributesKey already set"; forcedTextAttributesKey = attributesKey; return this; } @NotNull @Override public Builder unescapedToolTip(@NotNull String unescapedToolTip) { assert escapedToolTip == null : "Tooltip was already set"; escapedToolTip = htmlEscapeToolTip(unescapedToolTip); return this; } @NotNull @Override public Builder escapedToolTip(@NotNull String escapedToolTip) { assert this.escapedToolTip == null : "Tooltip was already set"; this.escapedToolTip = escapedToolTip; return this; } @NotNull @Override public Builder range(int start, int end) { assert startOffset == -1 && endOffset == -1 : "Offsets already set"; startOffset = start; endOffset = end; return this; } @NotNull @Override public Builder range(@NotNull TextRange textRange) { assert startOffset == -1 && endOffset == -1 : "Offsets already set"; startOffset = textRange.getStartOffset(); endOffset = textRange.getEndOffset(); return this; } @NotNull @Override public Builder range(@NotNull ASTNode node) { return range(node.getPsi()); } @NotNull @Override public Builder range(@NotNull PsiElement element) { assert psiElement == null : " psiElement already set"; psiElement = element; return range(element.getTextRange()); } @NotNull @Override public Builder range(@NotNull PsiElement element, @NotNull TextRange rangeInElement) { TextRange absoluteRange = rangeInElement.shiftRight(element.getTextRange().getStartOffset()); return range(element, absoluteRange.getStartOffset(), absoluteRange.getEndOffset()); } @NotNull @Override public Builder range(@NotNull PsiElement element, int start, int end) { assert psiElement == null : " psiElement already set"; psiElement = element; return range(start, end); } @NotNull @Override public Builder endOfLine() { isAfterEndOfLine = true; return this; } @NotNull @Override public Builder needsUpdateOnTyping(boolean update) { assert myNeedsUpdateOnTyping == null : " needsUpdateOnTyping already set"; myNeedsUpdateOnTyping = update; return this; } @NotNull @Override public Builder severity(@NotNull HighlightSeverity severity) { assert this.severity == null : " severity already set"; this.severity = severity; return this; } @NotNull @Override public Builder fileLevelAnnotation() { isFileLevelAnnotation = true; return this; } @NotNull @Override public Builder navigationShift(int navigationShift) { this.navigationShift = navigationShift; return this; } @NotNull @Override public Builder group(int group) { this.group = group; return this; } @Nullable @Override public HighlightInfo create() { HighlightInfo info = createUnconditionally(); LOG.assertTrue(psiElement != null || severity == HighlightInfoType.SYMBOL_TYPE_SEVERITY || severity == HighlightInfoType.INJECTED_FRAGMENT_SEVERITY || ArrayUtil.find(HighlightSeverity.DEFAULT_SEVERITIES, severity) != -1, "Custom type requires not-null element to detect its text attributes"); if (!isAcceptedByFilters(info, psiElement)) return null; return info; } @NotNull @Override public HighlightInfo createUnconditionally() { if (severity == null) { severity = type.getSeverity(psiElement); } return new HighlightInfo(forcedTextAttributes, forcedTextAttributesKey, type, startOffset, endOffset, escapedDescription, escapedToolTip, severity, isAfterEndOfLine, myNeedsUpdateOnTyping, isFileLevelAnnotation, navigationShift, problemGroup, inspectionToolId, gutterIconRenderer, group); } } public GutterMark getGutterIconRenderer() { return gutterIconRenderer; } @Nullable public ProblemGroup getProblemGroup() { return myProblemGroup; } @NotNull public static HighlightInfo fromAnnotation(@NotNull Annotation annotation) { return fromAnnotation(annotation, false); } @NotNull static HighlightInfo fromAnnotation(@NotNull Annotation annotation, boolean batchMode) { TextAttributes forcedAttributes = annotation.getEnforcedTextAttributes(); TextAttributesKey key = annotation.getTextAttributes(); TextAttributesKey forcedAttributesKey = forcedAttributes == null && key != HighlighterColors.NO_HIGHLIGHTING ? key : null; HighlightInfo info = new HighlightInfo( forcedAttributes, forcedAttributesKey, convertType(annotation), annotation.getStartOffset(), annotation.getEndOffset(), annotation.getMessage(), annotation.getTooltip(), annotation.getSeverity(), annotation.isAfterEndOfLine(), annotation.needsUpdateOnTyping(), annotation.isFileLevelAnnotation(), 0, annotation.getProblemGroup(), null, annotation.getGutterIconRenderer(), Pass.UPDATE_ALL); List<? extends Annotation.QuickFixInfo> fixes = batchMode ? annotation.getBatchFixes() : annotation.getQuickFixes(); if (fixes != null) { for (Annotation.QuickFixInfo quickFixInfo : fixes) { TextRange range = quickFixInfo.textRange; HighlightDisplayKey k = quickFixInfo.key != null ? quickFixInfo.key : HighlightDisplayKey.find(ANNOTATOR_INSPECTION_SHORT_NAME); info.registerFix(quickFixInfo.quickFix, null, HighlightDisplayKey.getDisplayNameByKey(k), range, k); } } return info; } private static final String ANNOTATOR_INSPECTION_SHORT_NAME = "Annotator"; @NotNull private static HighlightInfoType convertType(@NotNull Annotation annotation) { ProblemHighlightType type = annotation.getHighlightType(); if (type == ProblemHighlightType.LIKE_UNUSED_SYMBOL) return HighlightInfoType.UNUSED_SYMBOL; if (type == ProblemHighlightType.LIKE_UNKNOWN_SYMBOL) return HighlightInfoType.WRONG_REF; if (type == ProblemHighlightType.LIKE_DEPRECATED) return HighlightInfoType.DEPRECATED; if (type == ProblemHighlightType.LIKE_MARKED_FOR_REMOVAL) return HighlightInfoType.MARKED_FOR_REMOVAL; return convertSeverity(annotation.getSeverity()); } @NotNull @SuppressWarnings("deprecation") public static HighlightInfoType convertSeverity(@NotNull HighlightSeverity severity) { return severity == HighlightSeverity.ERROR? HighlightInfoType.ERROR : severity == HighlightSeverity.WARNING ? HighlightInfoType.WARNING : severity == HighlightSeverity.INFO ? HighlightInfoType.INFO : severity == HighlightSeverity.WEAK_WARNING ? HighlightInfoType.WEAK_WARNING : severity ==HighlightSeverity.GENERIC_SERVER_ERROR_OR_WARNING ? HighlightInfoType.GENERIC_WARNINGS_OR_ERRORS_FROM_SERVER : HighlightInfoType.INFORMATION; } @NotNull public static ProblemHighlightType convertType(HighlightInfoType infoType) { if (infoType == HighlightInfoType.ERROR || infoType == HighlightInfoType.WRONG_REF) return ProblemHighlightType.ERROR; if (infoType == HighlightInfoType.WARNING) return ProblemHighlightType.WARNING; if (infoType == HighlightInfoType.INFORMATION) return ProblemHighlightType.INFORMATION; return ProblemHighlightType.WEAK_WARNING; } @NotNull @SuppressWarnings("deprecation") public static ProblemHighlightType convertSeverityToProblemHighlight(HighlightSeverity severity) { return severity == HighlightSeverity.ERROR ? ProblemHighlightType.ERROR : severity == HighlightSeverity.WARNING ? ProblemHighlightType.WARNING : severity == HighlightSeverity.INFO ? ProblemHighlightType.INFO : severity == HighlightSeverity.WEAK_WARNING ? ProblemHighlightType.WEAK_WARNING : ProblemHighlightType.INFORMATION; } public boolean hasHint() { return isFlagSet(HAS_HINT_MASK); } void setHint(boolean hasHint) { setFlag(HAS_HINT_MASK, hasHint); } public int getActualStartOffset() { RangeHighlighterEx h = highlighter; return h == null || !h.isValid() ? startOffset : h.getStartOffset(); } public int getActualEndOffset() { RangeHighlighterEx h = highlighter; return h == null || !h.isValid() ? endOffset : h.getEndOffset(); } public static class IntentionActionDescriptor { private final IntentionAction myAction; private volatile List<IntentionAction> myOptions; private volatile HighlightDisplayKey myKey; private final ProblemGroup myProblemGroup; private final HighlightSeverity mySeverity; private final String myDisplayName; private final Icon myIcon; private Boolean myCanCleanup; IntentionActionDescriptor(@NotNull IntentionAction action, List<IntentionAction> options, String displayName) { this(action, options, displayName, null); } public IntentionActionDescriptor(@NotNull IntentionAction action, Icon icon) { this(action, null, null, icon); } IntentionActionDescriptor(@NotNull IntentionAction action, @Nullable List<IntentionAction> options, @Nullable String displayName, @Nullable Icon icon) { this(action, options, displayName, icon, null, null, null); } public IntentionActionDescriptor(@NotNull IntentionAction action, @Nullable List<IntentionAction> options, @Nullable String displayName, @Nullable Icon icon, @Nullable HighlightDisplayKey key, @Nullable ProblemGroup problemGroup, @Nullable HighlightSeverity severity) { myAction = action; myOptions = options; myDisplayName = displayName; myIcon = icon; myKey = key; myProblemGroup = problemGroup; mySeverity = severity; } @NotNull public IntentionAction getAction() { return myAction; } boolean isError() { return mySeverity == null || mySeverity.compareTo(HighlightSeverity.ERROR) >= 0; } boolean isInformation() { return HighlightSeverity.INFORMATION.equals(mySeverity); } boolean canCleanup(@NotNull PsiElement element) { if (myCanCleanup == null) { InspectionProfile profile = InspectionProjectProfileManager.getInstance(element.getProject()).getCurrentProfile(); HighlightDisplayKey key = myKey; if (key == null) { myCanCleanup = false; } else { InspectionToolWrapper toolWrapper = profile.getInspectionTool(key.toString(), element); myCanCleanup = toolWrapper != null && toolWrapper.isCleanupTool(); } } return myCanCleanup; } @Nullable public List<IntentionAction> getOptions(@NotNull PsiElement element, @Nullable Editor editor) { if (editor != null && Boolean.FALSE.equals(editor.getUserData(IntentionManager.SHOW_INTENTION_OPTIONS_KEY))) { return null; } List<IntentionAction> options = myOptions; HighlightDisplayKey key = myKey; if (myProblemGroup != null) { String problemName = myProblemGroup.getProblemName(); HighlightDisplayKey problemGroupKey = problemName != null ? HighlightDisplayKey.findById(problemName) : null; if (problemGroupKey != null) { key = problemGroupKey; } } if (options != null || key == null) { return options; } IntentionManager intentionManager = IntentionManager.getInstance(); List<IntentionAction> newOptions = intentionManager.getStandardIntentionOptions(key, element); InspectionProfile profile = InspectionProjectProfileManager.getInstance(element.getProject()).getCurrentProfile(); InspectionToolWrapper toolWrapper = profile.getInspectionTool(key.toString(), element); if (!(toolWrapper instanceof LocalInspectionToolWrapper)) { HighlightDisplayKey idKey = HighlightDisplayKey.findById(key.toString()); if (idKey != null) { toolWrapper = profile.getInspectionTool(idKey.toString(), element); } } if (toolWrapper != null) { myCanCleanup = toolWrapper.isCleanupTool(); IntentionAction fixAllIntention = intentionManager.createFixAllIntention(toolWrapper, myAction); InspectionProfileEntry wrappedTool = toolWrapper instanceof LocalInspectionToolWrapper ? ((LocalInspectionToolWrapper)toolWrapper).getTool() : ((GlobalInspectionToolWrapper)toolWrapper).getTool(); if (wrappedTool instanceof DefaultHighlightVisitorBasedInspection.AnnotatorBasedInspection) { List<IntentionAction> actions = Collections.emptyList(); if (myProblemGroup instanceof SuppressableProblemGroup) { actions = Arrays.asList(((SuppressableProblemGroup)myProblemGroup).getSuppressActions(element)); } if (fixAllIntention != null) { if (actions.isEmpty()) { return Collections.singletonList(fixAllIntention); } else { actions = new ArrayList<>(actions); actions.add(fixAllIntention); } } return actions; } ContainerUtil.addIfNotNull(newOptions, fixAllIntention); if (wrappedTool instanceof CustomSuppressableInspectionTool) { IntentionAction[] suppressActions = ((CustomSuppressableInspectionTool)wrappedTool).getSuppressActions(element); if (suppressActions != null) { ContainerUtil.addAll(newOptions, suppressActions); } } else { SuppressQuickFix[] suppressFixes = wrappedTool.getBatchSuppressActions(element); if (suppressFixes.length > 0) { newOptions.addAll(ContainerUtil.map(suppressFixes, SuppressIntentionActionFromFix::convertBatchToSuppressIntentionAction)); } } } if (myProblemGroup instanceof SuppressableProblemGroup) { IntentionAction[] suppressActions = ((SuppressableProblemGroup)myProblemGroup).getSuppressActions(element); ContainerUtil.addAll(newOptions, suppressActions); } //noinspection SynchronizeOnThis synchronized (this) { options = myOptions; if (options == null) { myOptions = options = newOptions; } myKey = null; } return options; } @Nullable public String getDisplayName() { return myDisplayName; } @Override public String toString() { String text = getAction().getText(); return "descriptor: " + (text.isEmpty() ? getAction().getClass() : text); } @Nullable public Icon getIcon() { return myIcon; } @Override public boolean equals(Object obj) { return obj instanceof IntentionActionDescriptor && myAction.equals(((IntentionActionDescriptor)obj).myAction); } } @Override public int getStartOffset() { return getActualStartOffset(); } @Override public int getEndOffset() { return getActualEndOffset(); } int getGroup() { return group; } boolean isFromInjection() { return isFlagSet(FROM_INJECTION_MASK); } @NotNull public String getText() { if (isFileLevelAnnotation()) return ""; RangeHighlighterEx highlighter = this.highlighter; if (highlighter == null) { throw new RuntimeException("info not applied yet"); } if (!highlighter.isValid()) return ""; return highlighter.getDocument().getText(TextRange.create(highlighter)); } public void registerFix(@Nullable IntentionAction action, @Nullable List<IntentionAction> options, @Nullable String displayName, @Nullable TextRange fixRange, @Nullable HighlightDisplayKey key) { if (action == null) return; if (fixRange == null) fixRange = new TextRange(startOffset, endOffset); if (quickFixActionRanges == null) { quickFixActionRanges = ContainerUtil.createLockFreeCopyOnWriteList(); } IntentionActionDescriptor desc = new IntentionActionDescriptor(action, options, displayName, null, key, getProblemGroup(), getSeverity()); quickFixActionRanges.add(Pair.create(desc, fixRange)); fixStartOffset = Math.min (fixStartOffset, fixRange.getStartOffset()); fixEndOffset = Math.max (fixEndOffset, fixRange.getEndOffset()); if (action instanceof HintAction) { setHint(true); } } public void unregisterQuickFix(@NotNull Condition<? super IntentionAction> condition) { if (quickFixActionRanges != null) { quickFixActionRanges.removeIf(pair -> condition.value(pair.first.getAction())); } } }
Fix visibility for Rider. GitOrigin-RevId: 6f3c31acd97559eebb549b6cd872d58434cc18b7
platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/HighlightInfo.java
Fix visibility for Rider.
<ide><path>latform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/HighlightInfo.java <ide> return isFlagSet(NEEDS_UPDATE_ON_TYPING_MASK); <ide> } <ide> <del> HighlightInfo(@Nullable TextAttributes forcedTextAttributes, <add> protected HighlightInfo(@Nullable TextAttributes forcedTextAttributes, <ide> @Nullable TextAttributesKey forcedTextAttributesKey, <ide> @NotNull HighlightInfoType type, <ide> int startOffset,
Java
apache-2.0
15b031a5a63323cd4f4474a999ea753a29c5a4ec
0
masaki-yamakawa/geode,davebarnes97/geode,masaki-yamakawa/geode,pdxrunner/geode,PurelyApplied/geode,masaki-yamakawa/geode,jdeppe-pivotal/geode,smgoller/geode,jdeppe-pivotal/geode,pivotal-amurmann/geode,davinash/geode,pivotal-amurmann/geode,smgoller/geode,pdxrunner/geode,deepakddixit/incubator-geode,PurelyApplied/geode,smanvi-pivotal/geode,PurelyApplied/geode,deepakddixit/incubator-geode,charliemblack/geode,PurelyApplied/geode,deepakddixit/incubator-geode,masaki-yamakawa/geode,smgoller/geode,charliemblack/geode,davinash/geode,charliemblack/geode,smgoller/geode,masaki-yamakawa/geode,davinash/geode,masaki-yamakawa/geode,pivotal-amurmann/geode,pivotal-amurmann/geode,pdxrunner/geode,jdeppe-pivotal/geode,PurelyApplied/geode,pdxrunner/geode,smgoller/geode,deepakddixit/incubator-geode,deepakddixit/incubator-geode,davebarnes97/geode,PurelyApplied/geode,davinash/geode,charliemblack/geode,davebarnes97/geode,smgoller/geode,davebarnes97/geode,PurelyApplied/geode,deepakddixit/incubator-geode,smanvi-pivotal/geode,jdeppe-pivotal/geode,davinash/geode,pdxrunner/geode,pivotal-amurmann/geode,davebarnes97/geode,masaki-yamakawa/geode,jdeppe-pivotal/geode,smgoller/geode,davebarnes97/geode,davinash/geode,smanvi-pivotal/geode,jdeppe-pivotal/geode,charliemblack/geode,pdxrunner/geode,pdxrunner/geode,smanvi-pivotal/geode,davebarnes97/geode,deepakddixit/incubator-geode,jdeppe-pivotal/geode,smanvi-pivotal/geode,davinash/geode
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.management.internal.cli.commands; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Pattern; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import org.apache.commons.lang.StringUtils; import org.springframework.shell.core.annotation.CliAvailabilityIndicator; import org.springframework.shell.core.annotation.CliCommand; import org.springframework.shell.core.annotation.CliOption; import org.apache.geode.LogWriter; import org.apache.geode.cache.DataPolicy; import org.apache.geode.cache.ExpirationAttributes; import org.apache.geode.cache.PartitionResolver; import org.apache.geode.cache.Region; import org.apache.geode.cache.RegionAttributes; import org.apache.geode.cache.RegionShortcut; import org.apache.geode.cache.Scope; import org.apache.geode.cache.execute.ResultCollector; import org.apache.geode.compression.Compressor; import org.apache.geode.distributed.DistributedMember; import org.apache.geode.distributed.internal.DistributionManager; import org.apache.geode.distributed.internal.membership.InternalDistributedMember; import org.apache.geode.internal.ClassPathLoader; import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.internal.i18n.LocalizedStrings; import org.apache.geode.internal.security.IntegratedSecurityService; import org.apache.geode.internal.security.SecurityService; import org.apache.geode.management.DistributedRegionMXBean; import org.apache.geode.management.DistributedSystemMXBean; import org.apache.geode.management.ManagementService; import org.apache.geode.management.RegionAttributesData; import org.apache.geode.management.RegionMXBean; import org.apache.geode.management.cli.CliMetaData; import org.apache.geode.management.cli.ConverterHint; import org.apache.geode.management.cli.Result; import org.apache.geode.management.cli.Result.Status; import org.apache.geode.management.internal.MBeanJMXAdapter; import org.apache.geode.management.internal.cli.CliUtil; import org.apache.geode.management.internal.cli.LogWrapper; import org.apache.geode.management.internal.cli.functions.CliFunctionResult; import org.apache.geode.management.internal.cli.functions.FetchRegionAttributesFunction; import org.apache.geode.management.internal.cli.functions.FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult; import org.apache.geode.management.internal.cli.functions.RegionAlterFunction; import org.apache.geode.management.internal.cli.functions.RegionCreateFunction; import org.apache.geode.management.internal.cli.functions.RegionDestroyFunction; import org.apache.geode.management.internal.cli.functions.RegionFunctionArgs; import org.apache.geode.management.internal.cli.i18n.CliStrings; import org.apache.geode.management.internal.cli.result.ResultBuilder; import org.apache.geode.management.internal.cli.result.TabularResultData; import org.apache.geode.management.internal.cli.util.RegionPath; import org.apache.geode.management.internal.configuration.domain.XmlEntity; import org.apache.geode.management.internal.security.ResourceOperation; import org.apache.geode.security.ResourcePermission.Operation; import org.apache.geode.security.ResourcePermission.Resource; /** * @since GemFire 7.0 */ public class CreateAlterDestroyRegionCommands implements GfshCommand { public static final Set<RegionShortcut> PERSISTENT_OVERFLOW_SHORTCUTS = new TreeSet<>(); private SecurityService securityService = IntegratedSecurityService.getSecurityService(); static { PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_PERSISTENT); PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT); PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_OVERFLOW); PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_REDUNDANT_OVERFLOW); PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_PERSISTENT_OVERFLOW); PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW); PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.REPLICATE_PERSISTENT); PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.REPLICATE_OVERFLOW); PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.REPLICATE_PERSISTENT_OVERFLOW); PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.LOCAL_PERSISTENT); PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.LOCAL_OVERFLOW); PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.LOCAL_PERSISTENT_OVERFLOW); } /** * TODO: method createRegion is too complex to analyze */ @CliCommand(value = CliStrings.CREATE_REGION, help = CliStrings.CREATE_REGION__HELP) @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION) @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE) public Result createRegion( @CliOption(key = CliStrings.CREATE_REGION__REGION, mandatory = true, help = CliStrings.CREATE_REGION__REGION__HELP) String regionPath, @CliOption(key = CliStrings.CREATE_REGION__REGIONSHORTCUT, help = CliStrings.CREATE_REGION__REGIONSHORTCUT__HELP) RegionShortcut regionShortcut, @CliOption(key = CliStrings.CREATE_REGION__USEATTRIBUTESFROM, optionContext = ConverterHint.REGION_PATH, help = CliStrings.CREATE_REGION__USEATTRIBUTESFROM__HELP) String useAttributesFrom, @CliOption(key = CliStrings.CREATE_REGION__GROUP, optionContext = ConverterHint.MEMBERGROUP, help = CliStrings.CREATE_REGION__GROUP__HELP) String[] groups, @CliOption(key = CliStrings.CREATE_REGION__SKIPIFEXISTS, unspecifiedDefaultValue = "true", specifiedDefaultValue = "true", help = CliStrings.CREATE_REGION__SKIPIFEXISTS__HELP) boolean skipIfExists, // the following should all be in alphabetical order according to // their key string @CliOption(key = CliStrings.CREATE_REGION__ASYNCEVENTQUEUEID, help = CliStrings.CREATE_REGION__ASYNCEVENTQUEUEID__HELP) String[] asyncEventQueueIds, @CliOption(key = CliStrings.CREATE_REGION__CACHELISTENER, help = CliStrings.CREATE_REGION__CACHELISTENER__HELP) String[] cacheListener, @CliOption(key = CliStrings.CREATE_REGION__CACHELOADER, help = CliStrings.CREATE_REGION__CACHELOADER__HELP) String cacheLoader, @CliOption(key = CliStrings.CREATE_REGION__CACHEWRITER, help = CliStrings.CREATE_REGION__CACHEWRITER__HELP) String cacheWriter, @CliOption(key = CliStrings.CREATE_REGION__COLOCATEDWITH, optionContext = ConverterHint.REGION_PATH, help = CliStrings.CREATE_REGION__COLOCATEDWITH__HELP) String prColocatedWith, @CliOption(key = CliStrings.CREATE_REGION__COMPRESSOR, help = CliStrings.CREATE_REGION__COMPRESSOR__HELP) String compressor, @CliOption(key = CliStrings.CREATE_REGION__CONCURRENCYLEVEL, help = CliStrings.CREATE_REGION__CONCURRENCYLEVEL__HELP) Integer concurrencyLevel, @CliOption(key = CliStrings.CREATE_REGION__DISKSTORE, help = CliStrings.CREATE_REGION__DISKSTORE__HELP) String diskStore, @CliOption(key = CliStrings.CREATE_REGION__ENABLEASYNCCONFLATION, help = CliStrings.CREATE_REGION__ENABLEASYNCCONFLATION__HELP) Boolean enableAsyncConflation, @CliOption(key = CliStrings.CREATE_REGION__CLONINGENABLED, help = CliStrings.CREATE_REGION__CLONINGENABLED__HELP) Boolean cloningEnabled, @CliOption(key = CliStrings.CREATE_REGION__CONCURRENCYCHECKSENABLED, help = CliStrings.CREATE_REGION__CONCURRENCYCHECKSENABLED__HELP) Boolean concurrencyChecksEnabled, @CliOption(key = CliStrings.CREATE_REGION__MULTICASTENABLED, help = CliStrings.CREATE_REGION__MULTICASTENABLED__HELP) Boolean mcastEnabled, @CliOption(key = CliStrings.CREATE_REGION__STATISTICSENABLED, help = CliStrings.CREATE_REGION__STATISTICSENABLED__HELP) Boolean statisticsEnabled, @CliOption(key = CliStrings.CREATE_REGION__ENABLESUBSCRIPTIONCONFLATION, help = CliStrings.CREATE_REGION__ENABLESUBSCRIPTIONCONFLATION__HELP) Boolean enableSubscriptionConflation, @CliOption(key = CliStrings.CREATE_REGION__DISKSYNCHRONOUS, help = CliStrings.CREATE_REGION__DISKSYNCHRONOUS__HELP) Boolean diskSynchronous, @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIME, help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIME__HELP) Integer entryExpirationIdleTime, @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIMEACTION, help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIMEACTION__HELP) String entryExpirationIdleTimeAction, @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTIMETOLIVE, help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTIMETOLIVE__HELP) Integer entryExpirationTTL, @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTTLACTION, help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTTLACTION__HELP) String entryExpirationTTLAction, @CliOption(key = CliStrings.CREATE_REGION__GATEWAYSENDERID, help = CliStrings.CREATE_REGION__GATEWAYSENDERID__HELP) String[] gatewaySenderIds, @CliOption(key = CliStrings.CREATE_REGION__KEYCONSTRAINT, help = CliStrings.CREATE_REGION__KEYCONSTRAINT__HELP) String keyConstraint, @CliOption(key = CliStrings.CREATE_REGION__LOCALMAXMEMORY, help = CliStrings.CREATE_REGION__LOCALMAXMEMORY__HELP) Integer prLocalMaxMemory, @CliOption(key = CliStrings.CREATE_REGION__OFF_HEAP, specifiedDefaultValue = "true", help = CliStrings.CREATE_REGION__OFF_HEAP__HELP) Boolean offHeap, @CliOption(key = CliStrings.CREATE_REGION__PARTITION_RESOLVER, help = CliStrings.CREATE_REGION__PARTITION_RESOLVER__HELP) String partitionResolver, @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIME, help = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIME__HELP) Integer regionExpirationIdleTime, @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIMEACTION, help = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIMEACTION__HELP) String regionExpirationIdleTimeAction, @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTL, help = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTL__HELP) Integer regionExpirationTTL, @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTLACTION, help = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTLACTION__HELP) String regionExpirationTTLAction, @CliOption(key = CliStrings.CREATE_REGION__RECOVERYDELAY, help = CliStrings.CREATE_REGION__RECOVERYDELAY__HELP) Long prRecoveryDelay, @CliOption(key = CliStrings.CREATE_REGION__REDUNDANTCOPIES, help = CliStrings.CREATE_REGION__REDUNDANTCOPIES__HELP) Integer prRedundantCopies, @CliOption(key = CliStrings.CREATE_REGION__STARTUPRECOVERYDDELAY, help = CliStrings.CREATE_REGION__STARTUPRECOVERYDDELAY__HELP) Long prStartupRecoveryDelay, @CliOption(key = CliStrings.CREATE_REGION__TOTALMAXMEMORY, help = CliStrings.CREATE_REGION__TOTALMAXMEMORY__HELP) Long prTotalMaxMemory, @CliOption(key = CliStrings.CREATE_REGION__TOTALNUMBUCKETS, help = CliStrings.CREATE_REGION__TOTALNUMBUCKETS__HELP) Integer prTotalNumBuckets, @CliOption(key = CliStrings.CREATE_REGION__VALUECONSTRAINT, help = CliStrings.CREATE_REGION__VALUECONSTRAINT__HELP) String valueConstraint // NOTICE: keep the region attributes params in alphabetical order ) { Result result; AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>(); try { InternalCache cache = getCache(); if (regionShortcut != null && useAttributesFrom != null) { throw new IllegalArgumentException( CliStrings.CREATE_REGION__MSG__ONLY_ONE_OF_REGIONSHORTCUT_AND_USEATTRIBUESFROM_CAN_BE_SPECIFIED); } else if (regionShortcut == null && useAttributesFrom == null) { throw new IllegalArgumentException( CliStrings.CREATE_REGION__MSG__ONE_OF_REGIONSHORTCUT_AND_USEATTRIBUESFROM_IS_REQUIRED); } validateRegionPathAndParent(cache, regionPath); validateGroups(cache, groups); RegionFunctionArgs.ExpirationAttrs entryIdle = null; if (entryExpirationIdleTime != null) { entryIdle = new RegionFunctionArgs.ExpirationAttrs( RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_IDLE, entryExpirationIdleTime, entryExpirationIdleTimeAction); } RegionFunctionArgs.ExpirationAttrs entryTTL = null; if (entryExpirationTTL != null) { entryTTL = new RegionFunctionArgs.ExpirationAttrs( RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_TTL, entryExpirationTTL, entryExpirationTTLAction); } RegionFunctionArgs.ExpirationAttrs regionIdle = null; if (regionExpirationIdleTime != null) { regionIdle = new RegionFunctionArgs.ExpirationAttrs( RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_IDLE, regionExpirationIdleTime, regionExpirationIdleTimeAction); } RegionFunctionArgs.ExpirationAttrs regionTTL = null; if (regionExpirationTTL != null) { regionTTL = new RegionFunctionArgs.ExpirationAttrs( RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_TTL, regionExpirationTTL, regionExpirationTTLAction); } RegionFunctionArgs regionFunctionArgs; if (useAttributesFrom != null) { if (!regionExists(cache, useAttributesFrom)) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND, new Object[] {CliStrings.CREATE_REGION__USEATTRIBUTESFROM, useAttributesFrom})); } FetchRegionAttributesFunctionResult<Object, Object> regionAttributesResult = getRegionAttributes(cache, useAttributesFrom); RegionAttributes<?, ?> regionAttributes = regionAttributesResult.getRegionAttributes(); // give preference to user specified plugins than the ones retrieved from other region String[] cacheListenerClasses = cacheListener != null && cacheListener.length != 0 ? cacheListener : regionAttributesResult.getCacheListenerClasses(); String cacheLoaderClass = cacheLoader != null ? cacheLoader : regionAttributesResult.getCacheLoaderClass(); String cacheWriterClass = cacheWriter != null ? cacheWriter : regionAttributesResult.getCacheWriterClass(); regionFunctionArgs = new RegionFunctionArgs(regionPath, useAttributesFrom, skipIfExists, keyConstraint, valueConstraint, statisticsEnabled, entryIdle, entryTTL, regionIdle, regionTTL, diskStore, diskSynchronous, enableAsyncConflation, enableSubscriptionConflation, cacheListenerClasses, cacheLoaderClass, cacheWriterClass, asyncEventQueueIds, gatewaySenderIds, concurrencyChecksEnabled, cloningEnabled, concurrencyLevel, prColocatedWith, prLocalMaxMemory, prRecoveryDelay, prRedundantCopies, prStartupRecoveryDelay, prTotalMaxMemory, prTotalNumBuckets, offHeap, mcastEnabled, regionAttributes, partitionResolver); if (regionAttributes.getPartitionAttributes() == null && regionFunctionArgs.hasPartitionAttributes()) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__OPTION_0_CAN_BE_USED_ONLY_FOR_PARTITIONEDREGION, regionFunctionArgs.getPartitionArgs().getUserSpecifiedPartitionAttributes()) + " " + CliStrings.format(CliStrings.CREATE_REGION__MSG__0_IS_NOT_A_PARITIONEDREGION, useAttributesFrom)); } } else { regionFunctionArgs = new RegionFunctionArgs(regionPath, regionShortcut, useAttributesFrom, skipIfExists, keyConstraint, valueConstraint, statisticsEnabled, entryIdle, entryTTL, regionIdle, regionTTL, diskStore, diskSynchronous, enableAsyncConflation, enableSubscriptionConflation, cacheListener, cacheLoader, cacheWriter, asyncEventQueueIds, gatewaySenderIds, concurrencyChecksEnabled, cloningEnabled, concurrencyLevel, prColocatedWith, prLocalMaxMemory, prRecoveryDelay, prRedundantCopies, prStartupRecoveryDelay, prTotalMaxMemory, prTotalNumBuckets, null, compressor, offHeap, mcastEnabled, partitionResolver); if (!regionShortcut.name().startsWith("PARTITION") && regionFunctionArgs.hasPartitionAttributes()) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__OPTION_0_CAN_BE_USED_ONLY_FOR_PARTITIONEDREGION, regionFunctionArgs.getPartitionArgs().getUserSpecifiedPartitionAttributes()) + " " + CliStrings.format(CliStrings.CREATE_REGION__MSG__0_IS_NOT_A_PARITIONEDREGION, useAttributesFrom)); } } validateRegionFunctionArgs(cache, regionFunctionArgs); Set<DistributedMember> membersToCreateRegionOn; if (groups != null && groups.length != 0) { membersToCreateRegionOn = CliUtil.getDistributedMembersByGroup(cache, groups); // have only normal members from the group for (Iterator<DistributedMember> it = membersToCreateRegionOn.iterator(); it.hasNext();) { DistributedMember distributedMember = it.next(); if (((InternalDistributedMember) distributedMember) .getVmKind() == DistributionManager.LOCATOR_DM_TYPE) { it.remove(); } } } else { membersToCreateRegionOn = CliUtil.getAllNormalMembers(cache); } if (membersToCreateRegionOn.isEmpty()) { return ResultBuilder.createUserErrorResult(CliStrings.NO_CACHING_MEMBERS_FOUND_MESSAGE); } ResultCollector<?, ?> resultCollector = CliUtil.executeFunction(RegionCreateFunction.INSTANCE, regionFunctionArgs, membersToCreateRegionOn); @SuppressWarnings("unchecked") List<CliFunctionResult> regionCreateResults = (List<CliFunctionResult>) resultCollector.getResult(); TabularResultData tabularResultData = ResultBuilder.createTabularResultData(); final String errorPrefix = "ERROR: "; for (CliFunctionResult regionCreateResult : regionCreateResults) { boolean success = regionCreateResult.isSuccessful(); tabularResultData.accumulate("Member", regionCreateResult.getMemberIdOrName()); tabularResultData.accumulate("Status", (success ? "" : errorPrefix) + regionCreateResult.getMessage()); if (success) { xmlEntity.set(regionCreateResult.getXmlEntity()); } } result = ResultBuilder.buildResult(tabularResultData); verifyDistributedRegionMbean(cache, regionPath); } catch (IllegalArgumentException | IllegalStateException e) { LogWrapper.getInstance().info(e.getMessage()); result = ResultBuilder.createUserErrorResult(e.getMessage()); } catch (RuntimeException e) { LogWrapper.getInstance().info(e.getMessage(), e); result = ResultBuilder.createGemFireErrorResult(e.getMessage()); } if (xmlEntity.get() != null) { persistClusterConfiguration(result, () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups)); } return result; } public boolean verifyDistributedRegionMbean(InternalCache cache, String regionName) { int federationInterval = cache.getInternalDistributedSystem().getConfig().getJmxManagerUpdateRate(); long timeEnd = System.currentTimeMillis() + federationInterval + 50; for (; System.currentTimeMillis() <= timeEnd;) { try { DistributedRegionMXBean bean = ManagementService.getManagementService(cache).getDistributedRegionMXBean(regionName); if (bean == null) { bean = ManagementService.getManagementService(cache) .getDistributedRegionMXBean(Region.SEPARATOR + regionName); } if (bean != null) { return true; } else { Thread.sleep(2); } } catch (Exception ignored) { } } return false; } @CliCommand(value = CliStrings.ALTER_REGION, help = CliStrings.ALTER_REGION__HELP) @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION) public Result alterRegion( @CliOption(key = CliStrings.ALTER_REGION__REGION, mandatory = true, help = CliStrings.ALTER_REGION__REGION__HELP) String regionPath, @CliOption(key = CliStrings.ALTER_REGION__GROUP, optionContext = ConverterHint.MEMBERGROUP, help = CliStrings.ALTER_REGION__GROUP__HELP) String[] groups, @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME, specifiedDefaultValue = "-1", help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME__HELP) Integer entryExpirationIdleTime, @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIMEACTION, specifiedDefaultValue = "INVALIDATE", help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIMEACTION__HELP) String entryExpirationIdleTimeAction, @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTIMETOLIVE, specifiedDefaultValue = "-1", help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTIMETOLIVE__HELP) Integer entryExpirationTTL, @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION, specifiedDefaultValue = "INVALIDATE", help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION__HELP) String entryExpirationTTLAction, @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIME, specifiedDefaultValue = "-1", help = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIME__HELP) Integer regionExpirationIdleTime, @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIMEACTION, specifiedDefaultValue = "INVALIDATE", help = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIMEACTION__HELP) String regionExpirationIdleTimeAction, @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTL, specifiedDefaultValue = "-1", help = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTL__HELP) Integer regionExpirationTTL, @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTLACTION, specifiedDefaultValue = "INVALIDATE", help = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTLACTION__HELP) String regionExpirationTTLAction, @CliOption(key = CliStrings.ALTER_REGION__CACHELISTENER, specifiedDefaultValue = "", help = CliStrings.ALTER_REGION__CACHELISTENER__HELP) String[] cacheListeners, @CliOption(key = CliStrings.ALTER_REGION__CACHELOADER, specifiedDefaultValue = "", help = CliStrings.ALTER_REGION__CACHELOADER__HELP) String cacheLoader, @CliOption(key = CliStrings.ALTER_REGION__CACHEWRITER, specifiedDefaultValue = "", help = CliStrings.ALTER_REGION__CACHEWRITER__HELP) String cacheWriter, @CliOption(key = CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID, specifiedDefaultValue = "", help = CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID__HELP) String[] asyncEventQueueIds, @CliOption(key = CliStrings.ALTER_REGION__GATEWAYSENDERID, specifiedDefaultValue = "", help = CliStrings.ALTER_REGION__GATEWAYSENDERID__HELP) String[] gatewaySenderIds, @CliOption(key = CliStrings.ALTER_REGION__CLONINGENABLED, specifiedDefaultValue = "false", help = CliStrings.ALTER_REGION__CLONINGENABLED__HELP) Boolean cloningEnabled, @CliOption(key = CliStrings.ALTER_REGION__EVICTIONMAX, specifiedDefaultValue = "0", help = CliStrings.ALTER_REGION__EVICTIONMAX__HELP) Integer evictionMax) { Result result; AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>(); this.securityService.authorizeRegionManage(regionPath); try { InternalCache cache = getCache(); if (groups != null) { validateGroups(cache, groups); } RegionFunctionArgs.ExpirationAttrs entryIdle = null; if (entryExpirationIdleTime != null || entryExpirationIdleTimeAction != null) { if (entryExpirationIdleTime != null && entryExpirationIdleTime == -1) { entryExpirationIdleTime = ExpirationAttributes.DEFAULT.getTimeout(); } if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(entryExpirationIdleTimeAction)) { entryExpirationIdleTimeAction = ExpirationAttributes.DEFAULT.getAction().toString(); } entryIdle = new RegionFunctionArgs.ExpirationAttrs( RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_IDLE, entryExpirationIdleTime, entryExpirationIdleTimeAction); } RegionFunctionArgs.ExpirationAttrs entryTTL = null; if (entryExpirationTTL != null || entryExpirationTTLAction != null) { if (entryExpirationTTL != null && entryExpirationTTL == -1) { entryExpirationTTL = ExpirationAttributes.DEFAULT.getTimeout(); } if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(entryExpirationTTLAction)) { entryExpirationTTLAction = ExpirationAttributes.DEFAULT.getAction().toString(); } entryTTL = new RegionFunctionArgs.ExpirationAttrs( RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_TTL, entryExpirationTTL, entryExpirationTTLAction); } RegionFunctionArgs.ExpirationAttrs regionIdle = null; if (regionExpirationIdleTime != null || regionExpirationIdleTimeAction != null) { if (regionExpirationIdleTime != null && regionExpirationIdleTime == -1) { regionExpirationIdleTime = ExpirationAttributes.DEFAULT.getTimeout(); } if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(regionExpirationIdleTimeAction)) { regionExpirationIdleTimeAction = ExpirationAttributes.DEFAULT.getAction().toString(); } regionIdle = new RegionFunctionArgs.ExpirationAttrs( RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_IDLE, regionExpirationIdleTime, regionExpirationIdleTimeAction); } RegionFunctionArgs.ExpirationAttrs regionTTL = null; if (regionExpirationTTL != null || regionExpirationTTLAction != null) { if (regionExpirationTTL != null && regionExpirationTTL == -1) { regionExpirationTTL = ExpirationAttributes.DEFAULT.getTimeout(); } if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(regionExpirationTTLAction)) { regionExpirationTTLAction = ExpirationAttributes.DEFAULT.getAction().toString(); } regionTTL = new RegionFunctionArgs.ExpirationAttrs( RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_TTL, regionExpirationTTL, regionExpirationTTLAction); } cacheLoader = convertDefaultValue(cacheLoader, StringUtils.EMPTY); cacheWriter = convertDefaultValue(cacheWriter, StringUtils.EMPTY); RegionFunctionArgs regionFunctionArgs; regionFunctionArgs = new RegionFunctionArgs(regionPath, null, null, false, null, null, null, entryIdle, entryTTL, regionIdle, regionTTL, null, null, null, null, cacheListeners, cacheLoader, cacheWriter, asyncEventQueueIds, gatewaySenderIds, null, cloningEnabled, null, null, null, null, null, null, null, null, evictionMax, null, null, null, null); Set<String> cacheListenersSet = regionFunctionArgs.getCacheListeners(); if (cacheListenersSet != null && !cacheListenersSet.isEmpty()) { for (String cacheListener : cacheListenersSet) { if (!isClassNameValid(cacheListener)) { throw new IllegalArgumentException(CliStrings.format( CliStrings.ALTER_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELISTENER_0_IS_INVALID, new Object[] {cacheListener})); } } } if (cacheLoader != null && !isClassNameValid(cacheLoader)) { throw new IllegalArgumentException(CliStrings.format( CliStrings.ALTER_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELOADER_0_IS_INVALID, new Object[] {cacheLoader})); } if (cacheWriter != null && !isClassNameValid(cacheWriter)) { throw new IllegalArgumentException(CliStrings.format( CliStrings.ALTER_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHEWRITER_0_IS_INVALID, new Object[] {cacheWriter})); } if (evictionMax != null && evictionMax < 0) { throw new IllegalArgumentException(CliStrings.format( CliStrings.ALTER_REGION__MSG__SPECIFY_POSITIVE_INT_FOR_EVICTIONMAX_0_IS_NOT_VALID, new Object[] {evictionMax})); } Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null); if (targetMembers.isEmpty()) { return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE); } ResultCollector<?, ?> resultCollector = CliUtil.executeFunction(new RegionAlterFunction(), regionFunctionArgs, targetMembers); List<CliFunctionResult> regionAlterResults = (List<CliFunctionResult>) resultCollector.getResult(); TabularResultData tabularResultData = ResultBuilder.createTabularResultData(); final String errorPrefix = "ERROR: "; for (CliFunctionResult regionAlterResult : regionAlterResults) { boolean success = regionAlterResult.isSuccessful(); tabularResultData.accumulate("Member", regionAlterResult.getMemberIdOrName()); if (success) { tabularResultData.accumulate("Status", regionAlterResult.getMessage()); xmlEntity.set(regionAlterResult.getXmlEntity()); } else { tabularResultData.accumulate("Status", errorPrefix + regionAlterResult.getMessage()); tabularResultData.setStatus(Status.ERROR); } } result = ResultBuilder.buildResult(tabularResultData); } catch (IllegalArgumentException | IllegalStateException e) { LogWrapper.getInstance().info(e.getMessage()); result = ResultBuilder.createUserErrorResult(e.getMessage()); } catch (RuntimeException e) { LogWrapper.getInstance().info(e.getMessage(), e); result = ResultBuilder.createGemFireErrorResult(e.getMessage()); } if (xmlEntity.get() != null) { persistClusterConfiguration(result, () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups)); } return result; } private static boolean regionExists(InternalCache cache, String regionPath) { boolean regionFound = false; if (regionPath != null && !Region.SEPARATOR.equals(regionPath)) { ManagementService managementService = ManagementService.getExistingManagementService(cache); DistributedSystemMXBean dsMBean = managementService.getDistributedSystemMXBean(); String[] allRegionPaths = dsMBean.listAllRegionPaths(); for (String allRegionPath : allRegionPaths) { if (allRegionPath.equals(regionPath)) { regionFound = true; break; } } } return regionFound; } private void validateRegionPathAndParent(InternalCache cache, String regionPath) { if (StringUtils.isEmpty(regionPath)) { throw new IllegalArgumentException(CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH); } // If a region path indicates a sub-region, check whether the parent region exists RegionPath regionPathData = new RegionPath(regionPath); String parentRegionPath = regionPathData.getParent(); if (parentRegionPath != null && !Region.SEPARATOR.equals(parentRegionPath)) { if (!regionExists(cache, parentRegionPath)) { throw new IllegalArgumentException( CliStrings.format(CliStrings.CREATE_REGION__MSG__PARENT_REGION_FOR_0_DOESNOT_EXIST, new Object[] {regionPath})); } } } private void validateGroups(InternalCache cache, String[] groups) { if (groups != null && groups.length != 0) { Set<String> existingGroups = new HashSet<>(); Set<DistributedMember> members = CliUtil.getAllNormalMembers(cache); for (DistributedMember distributedMember : members) { List<String> memberGroups = distributedMember.getGroups(); existingGroups.addAll(memberGroups); } List<String> groupsList = new ArrayList<>(Arrays.asList(groups)); groupsList.removeAll(existingGroups); if (!groupsList.isEmpty()) { throw new IllegalArgumentException( CliStrings.format(CliStrings.CREATE_REGION__MSG__GROUPS_0_ARE_INVALID, new Object[] {String.valueOf(groupsList)})); } } } private void validateRegionFunctionArgs(InternalCache cache, RegionFunctionArgs regionFunctionArgs) { if (regionFunctionArgs.getRegionPath() == null) { throw new IllegalArgumentException(CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH); } ManagementService managementService = ManagementService.getExistingManagementService(cache); DistributedSystemMXBean dsMBean = managementService.getDistributedSystemMXBean(); String useAttributesFrom = regionFunctionArgs.getUseAttributesFrom(); if (useAttributesFrom != null && !useAttributesFrom.isEmpty() && regionExists(cache, useAttributesFrom)) { if (!regionExists(cache, useAttributesFrom)) { // check already done in createRegion !!! throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND, new Object[] {CliStrings.CREATE_REGION__USEATTRIBUTESFROM, useAttributesFrom})); } if (!regionFunctionArgs.isSetUseAttributesFrom() || regionFunctionArgs.getRegionAttributes() == null) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__COULD_NOT_RETRIEVE_REGION_ATTRS_FOR_PATH_0_VERIFY_REGION_EXISTS, useAttributesFrom)); } } if (regionFunctionArgs.hasPartitionAttributes()) { RegionFunctionArgs.PartitionArgs partitionArgs = regionFunctionArgs.getPartitionArgs(); String colocatedWith = partitionArgs.getPrColocatedWith(); if (colocatedWith != null && !colocatedWith.isEmpty()) { String[] listAllRegionPaths = dsMBean.listAllRegionPaths(); String foundRegionPath = null; for (String regionPath : listAllRegionPaths) { if (regionPath.equals(colocatedWith)) { foundRegionPath = regionPath; break; } } if (foundRegionPath == null) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND, new Object[] {CliStrings.CREATE_REGION__COLOCATEDWITH, colocatedWith})); } ManagementService mgmtService = ManagementService.getExistingManagementService(cache); DistributedRegionMXBean distributedRegionMXBean = mgmtService.getDistributedRegionMXBean(foundRegionPath); String regionType = distributedRegionMXBean.getRegionType(); if (!(DataPolicy.PARTITION.toString().equals(regionType) || DataPolicy.PERSISTENT_PARTITION.toString().equals(regionType))) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__COLOCATEDWITH_REGION_0_IS_NOT_PARTITIONEDREGION, new Object[] {colocatedWith})); } } if (partitionArgs.isSetPRLocalMaxMemory()) { int prLocalMaxMemory = partitionArgs.getPrLocalMaxMemory(); if (prLocalMaxMemory < 0) { throw new IllegalArgumentException( LocalizedStrings.AttributesFactory_PARTITIONATTRIBUTES_LOCALMAXMEMORY_MUST_NOT_BE_NEGATIVE .toLocalizedString()); } } if (partitionArgs.isSetPRTotalMaxMemory()) { long prTotalMaxMemory = partitionArgs.getPrTotalMaxMemory(); if (prTotalMaxMemory <= 0) { throw new IllegalArgumentException( LocalizedStrings.AttributesFactory_TOTAL_SIZE_OF_PARTITION_REGION_MUST_BE_0 .toLocalizedString()); } } if (partitionArgs.isSetPRRedundantCopies()) { int prRedundantCopies = partitionArgs.getPrRedundantCopies(); switch (prRedundantCopies) { case 0: case 1: case 2: case 3: break; default: throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__REDUNDANT_COPIES_SHOULD_BE_ONE_OF_0123, new Object[] {prRedundantCopies})); } } } String keyConstraint = regionFunctionArgs.getKeyConstraint(); if (keyConstraint != null && !isClassNameValid(keyConstraint)) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_KEYCONSTRAINT_0_IS_INVALID, new Object[] {keyConstraint})); } String valueConstraint = regionFunctionArgs.getValueConstraint(); if (valueConstraint != null && !isClassNameValid(valueConstraint)) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_VALUECONSTRAINT_0_IS_INVALID, new Object[] {valueConstraint})); } Set<String> cacheListeners = regionFunctionArgs.getCacheListeners(); if (cacheListeners != null && !cacheListeners.isEmpty()) { for (String cacheListener : cacheListeners) { if (!isClassNameValid(cacheListener)) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELISTENER_0_IS_INVALID, new Object[] {cacheListener})); } } } String cacheLoader = regionFunctionArgs.getCacheLoader(); if (cacheLoader != null && !isClassNameValid(cacheLoader)) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELOADER_0_IS_INVALID, new Object[] {cacheLoader})); } String cacheWriter = regionFunctionArgs.getCacheWriter(); if (cacheWriter != null && !isClassNameValid(cacheWriter)) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHEWRITER_0_IS_INVALID, new Object[] {cacheWriter})); } Set<String> gatewaySenderIds = regionFunctionArgs.getGatewaySenderIds(); if (gatewaySenderIds != null && !gatewaySenderIds.isEmpty()) { String[] gatewaySenders = dsMBean.listGatewaySenders(); if (gatewaySenders.length == 0) { throw new IllegalArgumentException( CliStrings.CREATE_REGION__MSG__NO_GATEWAYSENDERS_IN_THE_SYSTEM); } else { List<String> gatewaySendersList = new ArrayList<>(Arrays.asList(gatewaySenders)); gatewaySenderIds = new HashSet<>(gatewaySenderIds); gatewaySenderIds.removeAll(gatewaySendersList); if (!gatewaySenderIds.isEmpty()) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_GATEWAYSENDER_ID_UNKNOWN_0, new Object[] {gatewaySenderIds})); } } } if (regionFunctionArgs.isSetConcurrencyLevel()) { int concurrencyLevel = regionFunctionArgs.getConcurrencyLevel(); if (concurrencyLevel < 0) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_POSITIVE_INT_FOR_CONCURRENCYLEVEL_0_IS_NOT_VALID, new Object[] {concurrencyLevel})); } } String diskStore = regionFunctionArgs.getDiskStore(); if (diskStore != null) { RegionShortcut regionShortcut = regionFunctionArgs.getRegionShortcut(); if (regionShortcut != null && !PERSISTENT_OVERFLOW_SHORTCUTS.contains(regionShortcut)) { String subMessage = LocalizedStrings.DiskStore_IS_USED_IN_NONPERSISTENT_REGION.toLocalizedString(); String message = subMessage + ". " + CliStrings.format(CliStrings.CREATE_REGION__MSG__USE_ONE_OF_THESE_SHORTCUTS_0, new Object[] {String.valueOf(PERSISTENT_OVERFLOW_SHORTCUTS)}); throw new IllegalArgumentException(message); } RegionAttributes<?, ?> regionAttributes = regionFunctionArgs.getRegionAttributes(); if (regionAttributes != null && !regionAttributes.getDataPolicy().withPersistence()) { String subMessage = LocalizedStrings.DiskStore_IS_USED_IN_NONPERSISTENT_REGION.toLocalizedString(); String message = subMessage + ". " + CliStrings.format( CliStrings.CREATE_REGION__MSG__USE_ATTRIBUTES_FROM_REGION_0_IS_NOT_WITH_PERSISTENCE, new Object[] {String.valueOf(regionFunctionArgs.getUseAttributesFrom())}); throw new IllegalArgumentException(message); } if (!diskStoreExists(cache, diskStore)) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_DISKSTORE_UNKNOWN_DISKSTORE_0, new Object[] {diskStore})); } } RegionFunctionArgs.ExpirationAttrs entryExpirationIdleTime = regionFunctionArgs.getEntryExpirationIdleTime(); RegionFunctionArgs.ExpirationAttrs entryExpirationTTL = regionFunctionArgs.getEntryExpirationTTL(); RegionFunctionArgs.ExpirationAttrs regionExpirationIdleTime = regionFunctionArgs.getRegionExpirationIdleTime(); RegionFunctionArgs.ExpirationAttrs regionExpirationTTL = regionFunctionArgs.getRegionExpirationTTL(); if ((!regionFunctionArgs.isSetStatisticsEnabled() || !regionFunctionArgs.isStatisticsEnabled()) && (entryExpirationIdleTime != null || entryExpirationTTL != null || regionExpirationIdleTime != null || regionExpirationTTL != null)) { String message = LocalizedStrings.AttributesFactory_STATISTICS_MUST_BE_ENABLED_FOR_EXPIRATION .toLocalizedString(); throw new IllegalArgumentException(message + "."); } boolean compressorFailure = false; if (regionFunctionArgs.isSetCompressor()) { String compressorClassName = regionFunctionArgs.getCompressor(); Object compressor = null; try { Class<?> compressorClass = ClassPathLoader.getLatest().forName(compressorClassName); compressor = compressorClass.newInstance(); } catch (InstantiationException | ClassNotFoundException | IllegalAccessException e) { compressorFailure = true; } if (compressorFailure || !(compressor instanceof Compressor)) { throw new IllegalArgumentException( CliStrings.format(CliStrings.CREATE_REGION__MSG__INVALID_COMPRESSOR, new Object[] {regionFunctionArgs.getCompressor()})); } } if (regionFunctionArgs.hasPartitionAttributes()) { if (regionFunctionArgs.isPartitionResolverSet()) { String partitionResolverClassName = regionFunctionArgs.getPartitionResolver(); try { Class<PartitionResolver> resolverClass = (Class<PartitionResolver>) ClassPathLoader .getLatest().forName(partitionResolverClassName); PartitionResolver partitionResolver = resolverClass.newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { throw new IllegalArgumentException( CliStrings.format(CliStrings.CREATE_REGION__MSG__INVALID_PARTITION_RESOLVER, new Object[] {regionFunctionArgs.getCompressor()}), e); } } } } private boolean diskStoreExists(InternalCache cache, String diskStoreName) { ManagementService managementService = ManagementService.getExistingManagementService(cache); DistributedSystemMXBean dsMXBean = managementService.getDistributedSystemMXBean(); Map<String, String[]> diskstore = dsMXBean.listMemberDiskstore(); Set<Entry<String, String[]>> entrySet = diskstore.entrySet(); for (Entry<String, String[]> entry : entrySet) { String[] value = entry.getValue(); if (CliUtil.contains(value, diskStoreName)) { return true; } } return false; } private static <K, V> FetchRegionAttributesFunctionResult<K, V> getRegionAttributes( InternalCache cache, String regionPath) { if (!isClusterWideSameConfig(cache, regionPath)) { throw new IllegalStateException(CliStrings.format( CliStrings.CREATE_REGION__MSG__USE_ATTRIBUTES_FORM_REGIONS_EXISTS_BUT_DIFFERENT_SCOPE_OR_DATAPOLICY_USE_DESCRIBE_REGION_FOR_0, regionPath)); } FetchRegionAttributesFunctionResult<K, V> attributes = null; // First check whether the region exists on a this manager, if yes then no // need to use FetchRegionAttributesFunction to fetch RegionAttributes try { attributes = FetchRegionAttributesFunction.getRegionAttributes(regionPath); } catch (IllegalArgumentException e) { /* region doesn't exist on the manager */ } if (attributes == null) { // find first member which has the region Set<DistributedMember> regionAssociatedMembers = CliUtil.getRegionAssociatedMembers(regionPath, cache, false); if (regionAssociatedMembers != null && !regionAssociatedMembers.isEmpty()) { DistributedMember distributedMember = regionAssociatedMembers.iterator().next(); ResultCollector<?, ?> resultCollector = CliUtil .executeFunction(FetchRegionAttributesFunction.INSTANCE, regionPath, distributedMember); List<?> resultsList = (List<?>) resultCollector.getResult(); if (resultsList != null && !resultsList.isEmpty()) { for (Object object : resultsList) { if (object instanceof IllegalArgumentException) { throw (IllegalArgumentException) object; } else if (object instanceof Throwable) { Throwable th = (Throwable) object; LogWrapper.getInstance().info(CliUtil.stackTraceAsString((th))); throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__COULD_NOT_RETRIEVE_REGION_ATTRS_FOR_PATH_0_REASON_1, new Object[] {regionPath, th.getMessage()})); } else { // has to be RegionAttributes @SuppressWarnings("unchecked") // to avoid warning :( FetchRegionAttributesFunctionResult<K, V> regAttr = ((FetchRegionAttributesFunctionResult<K, V>) object); if (attributes == null) { attributes = regAttr; break; } // attributes null check } // not IllegalArgumentException or other throwable } // iterate over list - there should be only one result in the list } // result list is not null or mpty } // regionAssociatedMembers is not-empty } // attributes are null because do not exist on local member return attributes; } private static boolean isClusterWideSameConfig(InternalCache cache, String regionPath) { ManagementService managementService = ManagementService.getExistingManagementService(cache); DistributedSystemMXBean dsMXBean = managementService.getDistributedSystemMXBean(); Set<DistributedMember> allMembers = CliUtil.getAllNormalMembers(cache); RegionAttributesData regionAttributesToValidateAgainst = null; for (DistributedMember distributedMember : allMembers) { ObjectName regionObjectName; try { regionObjectName = dsMXBean .fetchRegionObjectName(CliUtil.getMemberNameOrId(distributedMember), regionPath); RegionMXBean regionMBean = managementService.getMBeanInstance(regionObjectName, RegionMXBean.class); RegionAttributesData regionAttributes = regionMBean.listRegionAttributes(); if (regionAttributesToValidateAgainst == null) { regionAttributesToValidateAgainst = regionAttributes; } else if (!(regionAttributesToValidateAgainst.getScope() .equals(regionAttributes.getScope()) || regionAttributesToValidateAgainst.getDataPolicy() .equals(regionAttributes.getDataPolicy()))) { return false; } } catch (Exception e) { // ignore } } return true; } private boolean isClassNameValid(String fqcn) { if (fqcn.isEmpty()) { return true; } String regex = "([\\p{L}_$][\\p{L}\\p{N}_$]*\\.)*[\\p{L}_$][\\p{L}\\p{N}_$]*"; return Pattern.matches(regex, fqcn); } @CliCommand(value = {CliStrings.DESTROY_REGION}, help = CliStrings.DESTROY_REGION__HELP) @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION) @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE) public Result destroyRegion( @CliOption(key = CliStrings.DESTROY_REGION__REGION, optionContext = ConverterHint.REGION_PATH, mandatory = true, help = CliStrings.DESTROY_REGION__REGION__HELP) String regionPath) { if (regionPath == null) { return ResultBuilder .createInfoResult(CliStrings.DESTROY_REGION__MSG__SPECIFY_REGIONPATH_TO_DESTROY); } if (StringUtils.isBlank(regionPath) || regionPath.equals(Region.SEPARATOR)) { return ResultBuilder.createInfoResult(CliStrings.format( CliStrings.DESTROY_REGION__MSG__REGIONPATH_0_NOT_VALID, new Object[] {regionPath})); } Result result; AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>(); try { InternalCache cache = getCache(); ManagementService managementService = ManagementService.getExistingManagementService(cache); String regionPathToUse = regionPath; if (!regionPathToUse.startsWith(Region.SEPARATOR)) { regionPathToUse = Region.SEPARATOR + regionPathToUse; } Set<DistributedMember> regionMembersList = findMembersForRegion(cache, managementService, regionPathToUse); if (regionMembersList.size() == 0) { return ResultBuilder.createUserErrorResult( CliStrings.format(CliStrings.DESTROY_REGION__MSG__COULDNOT_FIND_REGIONPATH_0_IN_GEODE, new Object[] {regionPath, "jmx-manager-update-rate milliseconds"})); } CliFunctionResult destroyRegionResult; ResultCollector<?, ?> resultCollector = CliUtil.executeFunction(RegionDestroyFunction.INSTANCE, regionPath, regionMembersList); List<CliFunctionResult> resultsList = (List<CliFunctionResult>) resultCollector.getResult(); String message = CliStrings.format(CliStrings.DESTROY_REGION__MSG__REGION_0_1_DESTROYED, new Object[] {regionPath, ""}); // Only if there is an error is this set to false boolean isRegionDestroyed = true; for (CliFunctionResult aResultsList : resultsList) { destroyRegionResult = aResultsList; if (destroyRegionResult.isSuccessful()) { xmlEntity.set(destroyRegionResult.getXmlEntity()); } else if (destroyRegionResult.getThrowable() != null) { Throwable t = destroyRegionResult.getThrowable(); LogWrapper.getInstance().info(t.getMessage(), t); message = CliStrings.format( CliStrings.DESTROY_REGION__MSG__ERROR_OCCURRED_WHILE_DESTROYING_0_REASON_1, new Object[] {regionPath, t.getMessage()}); isRegionDestroyed = false; } else { message = CliStrings.format( CliStrings.DESTROY_REGION__MSG__UNKNOWN_RESULT_WHILE_DESTROYING_REGION_0_REASON_1, new Object[] {regionPath, destroyRegionResult.getMessage()}); isRegionDestroyed = false; } } if (isRegionDestroyed) { result = ResultBuilder.createInfoResult(message); } else { result = ResultBuilder.createUserErrorResult(message); } } catch (IllegalStateException e) { result = ResultBuilder.createUserErrorResult(CliStrings.format( CliStrings.DESTROY_REGION__MSG__ERROR_WHILE_DESTROYING_REGION_0_REASON_1, new Object[] {regionPath, e.getMessage()})); } catch (Exception e) { result = ResultBuilder.createGemFireErrorResult(CliStrings.format( CliStrings.DESTROY_REGION__MSG__ERROR_WHILE_DESTROYING_REGION_0_REASON_1, new Object[] {regionPath, e.getMessage()})); } if (xmlEntity.get() != null) { persistClusterConfiguration(result, () -> getSharedConfiguration().deleteXmlEntity(xmlEntity.get(), null)); } return result; } private Set<DistributedMember> findMembersForRegion(InternalCache cache, ManagementService managementService, String regionPath) { Set<DistributedMember> membersList = new HashSet<>(); Set<String> regionMemberIds = new HashSet<>(); MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer; // needs to be escaped with quotes if it contains a hyphen if (regionPath.contains("-")) { regionPath = "\"" + regionPath + "\""; } String queryExp = MessageFormat.format(MBeanJMXAdapter.OBJECTNAME__REGION_MXBEAN, regionPath, "*"); try { ObjectName queryExpON = new ObjectName(queryExp); Set<ObjectName> queryNames = mbeanServer.queryNames(null, queryExpON); if (queryNames == null || queryNames.isEmpty()) { return membersList; // protects against null pointer exception below } boolean addedOneRemote = false; for (ObjectName regionMBeanObjectName : queryNames) { try { RegionMXBean regionMXBean = managementService.getMBeanInstance(regionMBeanObjectName, RegionMXBean.class); if (regionMXBean != null) { RegionAttributesData regionAttributes = regionMXBean.listRegionAttributes(); String scope = regionAttributes.getScope(); // For Scope.LOCAL regions we need to identify each hosting member, but for // other scopes we just need a single member as the region destroy will be // propagated. if (Scope.LOCAL.equals(Scope.fromString(scope))) { regionMemberIds.add(regionMXBean.getMember()); } else { if (!addedOneRemote) { regionMemberIds.add(regionMXBean.getMember()); addedOneRemote = true; } } } } catch (ClassCastException e) { LogWriter logger = cache.getLogger(); if (logger.finerEnabled()) { logger.finer(regionMBeanObjectName + " is not a " + RegionMXBean.class.getSimpleName(), e); } } } if (!regionMemberIds.isEmpty()) { membersList = getMembersByIds(cache, regionMemberIds); } } catch (MalformedObjectNameException | NullPointerException e) { LogWrapper.getInstance().info(e.getMessage(), e); } return membersList; } private Set<DistributedMember> getMembersByIds(InternalCache cache, Set<String> memberIds) { Set<DistributedMember> foundMembers = Collections.emptySet(); if (memberIds != null && !memberIds.isEmpty()) { foundMembers = new HashSet<>(); Set<DistributedMember> allNormalMembers = CliUtil.getAllNormalMembers(cache); for (String memberId : memberIds) { for (DistributedMember distributedMember : allNormalMembers) { if (memberId.equals(distributedMember.getId()) || memberId.equals(distributedMember.getName())) { foundMembers.add(distributedMember); } } } } return foundMembers; } @CliAvailabilityIndicator({CliStrings.ALTER_REGION, CliStrings.CREATE_REGION, CliStrings.DESTROY_REGION}) public boolean isRegionCommandAvailable() { boolean isAvailable = true; // always available on server if (CliUtil.isGfshVM()) { // in gfsh check if connected //TODO: make this better isAvailable = getGfsh() != null && getGfsh().isConnectedAndReady(); } return isAvailable; } }
geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommands.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.management.internal.cli.commands; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Pattern; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import org.apache.commons.lang.StringUtils; import org.springframework.shell.core.annotation.CliCommand; import org.springframework.shell.core.annotation.CliOption; import org.apache.geode.LogWriter; import org.apache.geode.cache.DataPolicy; import org.apache.geode.cache.ExpirationAttributes; import org.apache.geode.cache.PartitionResolver; import org.apache.geode.cache.Region; import org.apache.geode.cache.RegionAttributes; import org.apache.geode.cache.RegionShortcut; import org.apache.geode.cache.Scope; import org.apache.geode.cache.execute.ResultCollector; import org.apache.geode.compression.Compressor; import org.apache.geode.distributed.DistributedMember; import org.apache.geode.distributed.internal.DistributionManager; import org.apache.geode.distributed.internal.membership.InternalDistributedMember; import org.apache.geode.internal.ClassPathLoader; import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.internal.i18n.LocalizedStrings; import org.apache.geode.internal.security.IntegratedSecurityService; import org.apache.geode.internal.security.SecurityService; import org.apache.geode.management.DistributedRegionMXBean; import org.apache.geode.management.DistributedSystemMXBean; import org.apache.geode.management.ManagementService; import org.apache.geode.management.RegionAttributesData; import org.apache.geode.management.RegionMXBean; import org.apache.geode.management.cli.CliMetaData; import org.apache.geode.management.cli.ConverterHint; import org.apache.geode.management.cli.Result; import org.apache.geode.management.cli.Result.Status; import org.apache.geode.management.internal.MBeanJMXAdapter; import org.apache.geode.management.internal.cli.CliUtil; import org.apache.geode.management.internal.cli.LogWrapper; import org.apache.geode.management.internal.cli.functions.CliFunctionResult; import org.apache.geode.management.internal.cli.functions.FetchRegionAttributesFunction; import org.apache.geode.management.internal.cli.functions.FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult; import org.apache.geode.management.internal.cli.functions.RegionAlterFunction; import org.apache.geode.management.internal.cli.functions.RegionCreateFunction; import org.apache.geode.management.internal.cli.functions.RegionDestroyFunction; import org.apache.geode.management.internal.cli.functions.RegionFunctionArgs; import org.apache.geode.management.internal.cli.i18n.CliStrings; import org.apache.geode.management.internal.cli.result.ResultBuilder; import org.apache.geode.management.internal.cli.result.TabularResultData; import org.apache.geode.management.internal.cli.util.RegionPath; import org.apache.geode.management.internal.configuration.domain.XmlEntity; import org.apache.geode.management.internal.security.ResourceOperation; import org.apache.geode.security.ResourcePermission.Operation; import org.apache.geode.security.ResourcePermission.Resource; /** * @since GemFire 7.0 */ public class CreateAlterDestroyRegionCommands implements GfshCommand { public static final Set<RegionShortcut> PERSISTENT_OVERFLOW_SHORTCUTS = new TreeSet<>(); private SecurityService securityService = IntegratedSecurityService.getSecurityService(); static { PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_PERSISTENT); PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT); PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_OVERFLOW); PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_REDUNDANT_OVERFLOW); PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_PERSISTENT_OVERFLOW); PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW); PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.REPLICATE_PERSISTENT); PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.REPLICATE_OVERFLOW); PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.REPLICATE_PERSISTENT_OVERFLOW); PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.LOCAL_PERSISTENT); PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.LOCAL_OVERFLOW); PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.LOCAL_PERSISTENT_OVERFLOW); } /** * TODO: method createRegion is too complex to analyze */ @CliCommand(value = CliStrings.CREATE_REGION, help = CliStrings.CREATE_REGION__HELP) @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION) @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE) public Result createRegion( @CliOption(key = CliStrings.CREATE_REGION__REGION, mandatory = true, help = CliStrings.CREATE_REGION__REGION__HELP) String regionPath, @CliOption(key = CliStrings.CREATE_REGION__REGIONSHORTCUT, help = CliStrings.CREATE_REGION__REGIONSHORTCUT__HELP) RegionShortcut regionShortcut, @CliOption(key = CliStrings.CREATE_REGION__USEATTRIBUTESFROM, optionContext = ConverterHint.REGION_PATH, help = CliStrings.CREATE_REGION__USEATTRIBUTESFROM__HELP) String useAttributesFrom, @CliOption(key = CliStrings.CREATE_REGION__GROUP, optionContext = ConverterHint.MEMBERGROUP, help = CliStrings.CREATE_REGION__GROUP__HELP) String[] groups, @CliOption(key = CliStrings.CREATE_REGION__SKIPIFEXISTS, unspecifiedDefaultValue = "true", specifiedDefaultValue = "true", help = CliStrings.CREATE_REGION__SKIPIFEXISTS__HELP) boolean skipIfExists, // the following should all be in alphabetical order according to // their key string @CliOption(key = CliStrings.CREATE_REGION__ASYNCEVENTQUEUEID, help = CliStrings.CREATE_REGION__ASYNCEVENTQUEUEID__HELP) String[] asyncEventQueueIds, @CliOption(key = CliStrings.CREATE_REGION__CACHELISTENER, help = CliStrings.CREATE_REGION__CACHELISTENER__HELP) String[] cacheListener, @CliOption(key = CliStrings.CREATE_REGION__CACHELOADER, help = CliStrings.CREATE_REGION__CACHELOADER__HELP) String cacheLoader, @CliOption(key = CliStrings.CREATE_REGION__CACHEWRITER, help = CliStrings.CREATE_REGION__CACHEWRITER__HELP) String cacheWriter, @CliOption(key = CliStrings.CREATE_REGION__COLOCATEDWITH, optionContext = ConverterHint.REGION_PATH, help = CliStrings.CREATE_REGION__COLOCATEDWITH__HELP) String prColocatedWith, @CliOption(key = CliStrings.CREATE_REGION__COMPRESSOR, help = CliStrings.CREATE_REGION__COMPRESSOR__HELP) String compressor, @CliOption(key = CliStrings.CREATE_REGION__CONCURRENCYLEVEL, help = CliStrings.CREATE_REGION__CONCURRENCYLEVEL__HELP) Integer concurrencyLevel, @CliOption(key = CliStrings.CREATE_REGION__DISKSTORE, help = CliStrings.CREATE_REGION__DISKSTORE__HELP) String diskStore, @CliOption(key = CliStrings.CREATE_REGION__ENABLEASYNCCONFLATION, help = CliStrings.CREATE_REGION__ENABLEASYNCCONFLATION__HELP) Boolean enableAsyncConflation, @CliOption(key = CliStrings.CREATE_REGION__CLONINGENABLED, help = CliStrings.CREATE_REGION__CLONINGENABLED__HELP) Boolean cloningEnabled, @CliOption(key = CliStrings.CREATE_REGION__CONCURRENCYCHECKSENABLED, help = CliStrings.CREATE_REGION__CONCURRENCYCHECKSENABLED__HELP) Boolean concurrencyChecksEnabled, @CliOption(key = CliStrings.CREATE_REGION__MULTICASTENABLED, help = CliStrings.CREATE_REGION__MULTICASTENABLED__HELP) Boolean mcastEnabled, @CliOption(key = CliStrings.CREATE_REGION__STATISTICSENABLED, help = CliStrings.CREATE_REGION__STATISTICSENABLED__HELP) Boolean statisticsEnabled, @CliOption(key = CliStrings.CREATE_REGION__ENABLESUBSCRIPTIONCONFLATION, help = CliStrings.CREATE_REGION__ENABLESUBSCRIPTIONCONFLATION__HELP) Boolean enableSubscriptionConflation, @CliOption(key = CliStrings.CREATE_REGION__DISKSYNCHRONOUS, help = CliStrings.CREATE_REGION__DISKSYNCHRONOUS__HELP) Boolean diskSynchronous, @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIME, help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIME__HELP) Integer entryExpirationIdleTime, @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIMEACTION, help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIMEACTION__HELP) String entryExpirationIdleTimeAction, @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTIMETOLIVE, help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTIMETOLIVE__HELP) Integer entryExpirationTTL, @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTTLACTION, help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTTLACTION__HELP) String entryExpirationTTLAction, @CliOption(key = CliStrings.CREATE_REGION__GATEWAYSENDERID, help = CliStrings.CREATE_REGION__GATEWAYSENDERID__HELP) String[] gatewaySenderIds, @CliOption(key = CliStrings.CREATE_REGION__KEYCONSTRAINT, help = CliStrings.CREATE_REGION__KEYCONSTRAINT__HELP) String keyConstraint, @CliOption(key = CliStrings.CREATE_REGION__LOCALMAXMEMORY, help = CliStrings.CREATE_REGION__LOCALMAXMEMORY__HELP) Integer prLocalMaxMemory, @CliOption(key = CliStrings.CREATE_REGION__OFF_HEAP, specifiedDefaultValue = "true", help = CliStrings.CREATE_REGION__OFF_HEAP__HELP) Boolean offHeap, @CliOption(key = CliStrings.CREATE_REGION__PARTITION_RESOLVER, help = CliStrings.CREATE_REGION__PARTITION_RESOLVER__HELP) String partitionResolver, @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIME, help = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIME__HELP) Integer regionExpirationIdleTime, @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIMEACTION, help = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIMEACTION__HELP) String regionExpirationIdleTimeAction, @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTL, help = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTL__HELP) Integer regionExpirationTTL, @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTLACTION, help = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTLACTION__HELP) String regionExpirationTTLAction, @CliOption(key = CliStrings.CREATE_REGION__RECOVERYDELAY, help = CliStrings.CREATE_REGION__RECOVERYDELAY__HELP) Long prRecoveryDelay, @CliOption(key = CliStrings.CREATE_REGION__REDUNDANTCOPIES, help = CliStrings.CREATE_REGION__REDUNDANTCOPIES__HELP) Integer prRedundantCopies, @CliOption(key = CliStrings.CREATE_REGION__STARTUPRECOVERYDDELAY, help = CliStrings.CREATE_REGION__STARTUPRECOVERYDDELAY__HELP) Long prStartupRecoveryDelay, @CliOption(key = CliStrings.CREATE_REGION__TOTALMAXMEMORY, help = CliStrings.CREATE_REGION__TOTALMAXMEMORY__HELP) Long prTotalMaxMemory, @CliOption(key = CliStrings.CREATE_REGION__TOTALNUMBUCKETS, help = CliStrings.CREATE_REGION__TOTALNUMBUCKETS__HELP) Integer prTotalNumBuckets, @CliOption(key = CliStrings.CREATE_REGION__VALUECONSTRAINT, help = CliStrings.CREATE_REGION__VALUECONSTRAINT__HELP) String valueConstraint // NOTICE: keep the region attributes params in alphabetical order ) { Result result; AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>(); try { InternalCache cache = getCache(); if (regionShortcut != null && useAttributesFrom != null) { throw new IllegalArgumentException( CliStrings.CREATE_REGION__MSG__ONLY_ONE_OF_REGIONSHORTCUT_AND_USEATTRIBUESFROM_CAN_BE_SPECIFIED); } else if (regionShortcut == null && useAttributesFrom == null) { throw new IllegalArgumentException( CliStrings.CREATE_REGION__MSG__ONE_OF_REGIONSHORTCUT_AND_USEATTRIBUESFROM_IS_REQUIRED); } validateRegionPathAndParent(cache, regionPath); validateGroups(cache, groups); RegionFunctionArgs.ExpirationAttrs entryIdle = null; if (entryExpirationIdleTime != null) { entryIdle = new RegionFunctionArgs.ExpirationAttrs( RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_IDLE, entryExpirationIdleTime, entryExpirationIdleTimeAction); } RegionFunctionArgs.ExpirationAttrs entryTTL = null; if (entryExpirationTTL != null) { entryTTL = new RegionFunctionArgs.ExpirationAttrs( RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_TTL, entryExpirationTTL, entryExpirationTTLAction); } RegionFunctionArgs.ExpirationAttrs regionIdle = null; if (regionExpirationIdleTime != null) { regionIdle = new RegionFunctionArgs.ExpirationAttrs( RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_IDLE, regionExpirationIdleTime, regionExpirationIdleTimeAction); } RegionFunctionArgs.ExpirationAttrs regionTTL = null; if (regionExpirationTTL != null) { regionTTL = new RegionFunctionArgs.ExpirationAttrs( RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_TTL, regionExpirationTTL, regionExpirationTTLAction); } RegionFunctionArgs regionFunctionArgs; if (useAttributesFrom != null) { if (!regionExists(cache, useAttributesFrom)) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND, new Object[] {CliStrings.CREATE_REGION__USEATTRIBUTESFROM, useAttributesFrom})); } FetchRegionAttributesFunctionResult<Object, Object> regionAttributesResult = getRegionAttributes(cache, useAttributesFrom); RegionAttributes<?, ?> regionAttributes = regionAttributesResult.getRegionAttributes(); // give preference to user specified plugins than the ones retrieved from other region String[] cacheListenerClasses = cacheListener != null && cacheListener.length != 0 ? cacheListener : regionAttributesResult.getCacheListenerClasses(); String cacheLoaderClass = cacheLoader != null ? cacheLoader : regionAttributesResult.getCacheLoaderClass(); String cacheWriterClass = cacheWriter != null ? cacheWriter : regionAttributesResult.getCacheWriterClass(); regionFunctionArgs = new RegionFunctionArgs(regionPath, useAttributesFrom, skipIfExists, keyConstraint, valueConstraint, statisticsEnabled, entryIdle, entryTTL, regionIdle, regionTTL, diskStore, diskSynchronous, enableAsyncConflation, enableSubscriptionConflation, cacheListenerClasses, cacheLoaderClass, cacheWriterClass, asyncEventQueueIds, gatewaySenderIds, concurrencyChecksEnabled, cloningEnabled, concurrencyLevel, prColocatedWith, prLocalMaxMemory, prRecoveryDelay, prRedundantCopies, prStartupRecoveryDelay, prTotalMaxMemory, prTotalNumBuckets, offHeap, mcastEnabled, regionAttributes, partitionResolver); if (regionAttributes.getPartitionAttributes() == null && regionFunctionArgs.hasPartitionAttributes()) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__OPTION_0_CAN_BE_USED_ONLY_FOR_PARTITIONEDREGION, regionFunctionArgs.getPartitionArgs().getUserSpecifiedPartitionAttributes()) + " " + CliStrings.format(CliStrings.CREATE_REGION__MSG__0_IS_NOT_A_PARITIONEDREGION, useAttributesFrom)); } } else { regionFunctionArgs = new RegionFunctionArgs(regionPath, regionShortcut, useAttributesFrom, skipIfExists, keyConstraint, valueConstraint, statisticsEnabled, entryIdle, entryTTL, regionIdle, regionTTL, diskStore, diskSynchronous, enableAsyncConflation, enableSubscriptionConflation, cacheListener, cacheLoader, cacheWriter, asyncEventQueueIds, gatewaySenderIds, concurrencyChecksEnabled, cloningEnabled, concurrencyLevel, prColocatedWith, prLocalMaxMemory, prRecoveryDelay, prRedundantCopies, prStartupRecoveryDelay, prTotalMaxMemory, prTotalNumBuckets, null, compressor, offHeap, mcastEnabled, partitionResolver); if (!regionShortcut.name().startsWith("PARTITION") && regionFunctionArgs.hasPartitionAttributes()) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__OPTION_0_CAN_BE_USED_ONLY_FOR_PARTITIONEDREGION, regionFunctionArgs.getPartitionArgs().getUserSpecifiedPartitionAttributes()) + " " + CliStrings.format(CliStrings.CREATE_REGION__MSG__0_IS_NOT_A_PARITIONEDREGION, useAttributesFrom)); } } validateRegionFunctionArgs(cache, regionFunctionArgs); Set<DistributedMember> membersToCreateRegionOn; if (groups != null && groups.length != 0) { membersToCreateRegionOn = CliUtil.getDistributedMembersByGroup(cache, groups); // have only normal members from the group for (Iterator<DistributedMember> it = membersToCreateRegionOn.iterator(); it.hasNext();) { DistributedMember distributedMember = it.next(); if (((InternalDistributedMember) distributedMember) .getVmKind() == DistributionManager.LOCATOR_DM_TYPE) { it.remove(); } } } else { membersToCreateRegionOn = CliUtil.getAllNormalMembers(cache); } if (membersToCreateRegionOn.isEmpty()) { return ResultBuilder.createUserErrorResult(CliStrings.NO_CACHING_MEMBERS_FOUND_MESSAGE); } ResultCollector<?, ?> resultCollector = CliUtil.executeFunction(RegionCreateFunction.INSTANCE, regionFunctionArgs, membersToCreateRegionOn); @SuppressWarnings("unchecked") List<CliFunctionResult> regionCreateResults = (List<CliFunctionResult>) resultCollector.getResult(); TabularResultData tabularResultData = ResultBuilder.createTabularResultData(); final String errorPrefix = "ERROR: "; for (CliFunctionResult regionCreateResult : regionCreateResults) { boolean success = regionCreateResult.isSuccessful(); tabularResultData.accumulate("Member", regionCreateResult.getMemberIdOrName()); tabularResultData.accumulate("Status", (success ? "" : errorPrefix) + regionCreateResult.getMessage()); if (success) { xmlEntity.set(regionCreateResult.getXmlEntity()); } } result = ResultBuilder.buildResult(tabularResultData); verifyDistributedRegionMbean(cache, regionPath); } catch (IllegalArgumentException | IllegalStateException e) { LogWrapper.getInstance().info(e.getMessage()); result = ResultBuilder.createUserErrorResult(e.getMessage()); } catch (RuntimeException e) { LogWrapper.getInstance().info(e.getMessage(), e); result = ResultBuilder.createGemFireErrorResult(e.getMessage()); } if (xmlEntity.get() != null) { persistClusterConfiguration(result, () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups)); } return result; } public boolean verifyDistributedRegionMbean(InternalCache cache, String regionName) { int federationInterval = cache.getInternalDistributedSystem().getConfig().getJmxManagerUpdateRate(); long timeEnd = System.currentTimeMillis() + federationInterval + 50; for (; System.currentTimeMillis() <= timeEnd;) { try { DistributedRegionMXBean bean = ManagementService.getManagementService(cache).getDistributedRegionMXBean(regionName); if (bean == null) { bean = ManagementService.getManagementService(cache) .getDistributedRegionMXBean(Region.SEPARATOR + regionName); } if (bean != null) { return true; } else { Thread.sleep(2); } } catch (Exception ignored) { } } return false; } @CliCommand(value = CliStrings.ALTER_REGION, help = CliStrings.ALTER_REGION__HELP) @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION) public Result alterRegion( @CliOption(key = CliStrings.ALTER_REGION__REGION, mandatory = true, help = CliStrings.ALTER_REGION__REGION__HELP) String regionPath, @CliOption(key = CliStrings.ALTER_REGION__GROUP, optionContext = ConverterHint.MEMBERGROUP, help = CliStrings.ALTER_REGION__GROUP__HELP) String[] groups, @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME, specifiedDefaultValue = "-1", help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME__HELP) Integer entryExpirationIdleTime, @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIMEACTION, specifiedDefaultValue = "INVALIDATE", help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIMEACTION__HELP) String entryExpirationIdleTimeAction, @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTIMETOLIVE, specifiedDefaultValue = "-1", help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTIMETOLIVE__HELP) Integer entryExpirationTTL, @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION, specifiedDefaultValue = "INVALIDATE", help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION__HELP) String entryExpirationTTLAction, @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIME, specifiedDefaultValue = "-1", help = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIME__HELP) Integer regionExpirationIdleTime, @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIMEACTION, specifiedDefaultValue = "INVALIDATE", help = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIMEACTION__HELP) String regionExpirationIdleTimeAction, @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTL, specifiedDefaultValue = "-1", help = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTL__HELP) Integer regionExpirationTTL, @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTLACTION, specifiedDefaultValue = "INVALIDATE", help = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTLACTION__HELP) String regionExpirationTTLAction, @CliOption(key = CliStrings.ALTER_REGION__CACHELISTENER, specifiedDefaultValue = "", help = CliStrings.ALTER_REGION__CACHELISTENER__HELP) String[] cacheListeners, @CliOption(key = CliStrings.ALTER_REGION__CACHELOADER, specifiedDefaultValue = "", help = CliStrings.ALTER_REGION__CACHELOADER__HELP) String cacheLoader, @CliOption(key = CliStrings.ALTER_REGION__CACHEWRITER, specifiedDefaultValue = "", help = CliStrings.ALTER_REGION__CACHEWRITER__HELP) String cacheWriter, @CliOption(key = CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID, specifiedDefaultValue = "", help = CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID__HELP) String[] asyncEventQueueIds, @CliOption(key = CliStrings.ALTER_REGION__GATEWAYSENDERID, specifiedDefaultValue = "", help = CliStrings.ALTER_REGION__GATEWAYSENDERID__HELP) String[] gatewaySenderIds, @CliOption(key = CliStrings.ALTER_REGION__CLONINGENABLED, specifiedDefaultValue = "false", help = CliStrings.ALTER_REGION__CLONINGENABLED__HELP) Boolean cloningEnabled, @CliOption(key = CliStrings.ALTER_REGION__EVICTIONMAX, specifiedDefaultValue = "0", help = CliStrings.ALTER_REGION__EVICTIONMAX__HELP) Integer evictionMax) { Result result; AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>(); this.securityService.authorizeRegionManage(regionPath); try { InternalCache cache = getCache(); if (groups != null) { validateGroups(cache, groups); } RegionFunctionArgs.ExpirationAttrs entryIdle = null; if (entryExpirationIdleTime != null || entryExpirationIdleTimeAction != null) { if (entryExpirationIdleTime != null && entryExpirationIdleTime == -1) { entryExpirationIdleTime = ExpirationAttributes.DEFAULT.getTimeout(); } if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(entryExpirationIdleTimeAction)) { entryExpirationIdleTimeAction = ExpirationAttributes.DEFAULT.getAction().toString(); } entryIdle = new RegionFunctionArgs.ExpirationAttrs( RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_IDLE, entryExpirationIdleTime, entryExpirationIdleTimeAction); } RegionFunctionArgs.ExpirationAttrs entryTTL = null; if (entryExpirationTTL != null || entryExpirationTTLAction != null) { if (entryExpirationTTL != null && entryExpirationTTL == -1) { entryExpirationTTL = ExpirationAttributes.DEFAULT.getTimeout(); } if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(entryExpirationTTLAction)) { entryExpirationTTLAction = ExpirationAttributes.DEFAULT.getAction().toString(); } entryTTL = new RegionFunctionArgs.ExpirationAttrs( RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_TTL, entryExpirationTTL, entryExpirationTTLAction); } RegionFunctionArgs.ExpirationAttrs regionIdle = null; if (regionExpirationIdleTime != null || regionExpirationIdleTimeAction != null) { if (regionExpirationIdleTime != null && regionExpirationIdleTime == -1) { regionExpirationIdleTime = ExpirationAttributes.DEFAULT.getTimeout(); } if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(regionExpirationIdleTimeAction)) { regionExpirationIdleTimeAction = ExpirationAttributes.DEFAULT.getAction().toString(); } regionIdle = new RegionFunctionArgs.ExpirationAttrs( RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_IDLE, regionExpirationIdleTime, regionExpirationIdleTimeAction); } RegionFunctionArgs.ExpirationAttrs regionTTL = null; if (regionExpirationTTL != null || regionExpirationTTLAction != null) { if (regionExpirationTTL != null && regionExpirationTTL == -1) { regionExpirationTTL = ExpirationAttributes.DEFAULT.getTimeout(); } if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(regionExpirationTTLAction)) { regionExpirationTTLAction = ExpirationAttributes.DEFAULT.getAction().toString(); } regionTTL = new RegionFunctionArgs.ExpirationAttrs( RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_TTL, regionExpirationTTL, regionExpirationTTLAction); } cacheLoader = convertDefaultValue(cacheLoader, StringUtils.EMPTY); cacheWriter = convertDefaultValue(cacheWriter, StringUtils.EMPTY); RegionFunctionArgs regionFunctionArgs; regionFunctionArgs = new RegionFunctionArgs(regionPath, null, null, false, null, null, null, entryIdle, entryTTL, regionIdle, regionTTL, null, null, null, null, cacheListeners, cacheLoader, cacheWriter, asyncEventQueueIds, gatewaySenderIds, null, cloningEnabled, null, null, null, null, null, null, null, null, evictionMax, null, null, null, null); Set<String> cacheListenersSet = regionFunctionArgs.getCacheListeners(); if (cacheListenersSet != null && !cacheListenersSet.isEmpty()) { for (String cacheListener : cacheListenersSet) { if (!isClassNameValid(cacheListener)) { throw new IllegalArgumentException(CliStrings.format( CliStrings.ALTER_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELISTENER_0_IS_INVALID, new Object[] {cacheListener})); } } } if (cacheLoader != null && !isClassNameValid(cacheLoader)) { throw new IllegalArgumentException(CliStrings.format( CliStrings.ALTER_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELOADER_0_IS_INVALID, new Object[] {cacheLoader})); } if (cacheWriter != null && !isClassNameValid(cacheWriter)) { throw new IllegalArgumentException(CliStrings.format( CliStrings.ALTER_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHEWRITER_0_IS_INVALID, new Object[] {cacheWriter})); } if (evictionMax != null && evictionMax < 0) { throw new IllegalArgumentException(CliStrings.format( CliStrings.ALTER_REGION__MSG__SPECIFY_POSITIVE_INT_FOR_EVICTIONMAX_0_IS_NOT_VALID, new Object[] {evictionMax})); } Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null); if (targetMembers.isEmpty()) { return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE); } ResultCollector<?, ?> resultCollector = CliUtil.executeFunction(new RegionAlterFunction(), regionFunctionArgs, targetMembers); List<CliFunctionResult> regionAlterResults = (List<CliFunctionResult>) resultCollector.getResult(); TabularResultData tabularResultData = ResultBuilder.createTabularResultData(); final String errorPrefix = "ERROR: "; for (CliFunctionResult regionAlterResult : regionAlterResults) { boolean success = regionAlterResult.isSuccessful(); tabularResultData.accumulate("Member", regionAlterResult.getMemberIdOrName()); if (success) { tabularResultData.accumulate("Status", regionAlterResult.getMessage()); xmlEntity.set(regionAlterResult.getXmlEntity()); } else { tabularResultData.accumulate("Status", errorPrefix + regionAlterResult.getMessage()); tabularResultData.setStatus(Status.ERROR); } } result = ResultBuilder.buildResult(tabularResultData); } catch (IllegalArgumentException | IllegalStateException e) { LogWrapper.getInstance().info(e.getMessage()); result = ResultBuilder.createUserErrorResult(e.getMessage()); } catch (RuntimeException e) { LogWrapper.getInstance().info(e.getMessage(), e); result = ResultBuilder.createGemFireErrorResult(e.getMessage()); } if (xmlEntity.get() != null) { persistClusterConfiguration(result, () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups)); } return result; } private static boolean regionExists(InternalCache cache, String regionPath) { boolean regionFound = false; if (regionPath != null && !Region.SEPARATOR.equals(regionPath)) { ManagementService managementService = ManagementService.getExistingManagementService(cache); DistributedSystemMXBean dsMBean = managementService.getDistributedSystemMXBean(); String[] allRegionPaths = dsMBean.listAllRegionPaths(); for (String allRegionPath : allRegionPaths) { if (allRegionPath.equals(regionPath)) { regionFound = true; break; } } } return regionFound; } private void validateRegionPathAndParent(InternalCache cache, String regionPath) { if (StringUtils.isEmpty(regionPath)) { throw new IllegalArgumentException(CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH); } // If a region path indicates a sub-region, check whether the parent region exists RegionPath regionPathData = new RegionPath(regionPath); String parentRegionPath = regionPathData.getParent(); if (parentRegionPath != null && !Region.SEPARATOR.equals(parentRegionPath)) { if (!regionExists(cache, parentRegionPath)) { throw new IllegalArgumentException( CliStrings.format(CliStrings.CREATE_REGION__MSG__PARENT_REGION_FOR_0_DOESNOT_EXIST, new Object[] {regionPath})); } } } private void validateGroups(InternalCache cache, String[] groups) { if (groups != null && groups.length != 0) { Set<String> existingGroups = new HashSet<>(); Set<DistributedMember> members = CliUtil.getAllNormalMembers(cache); for (DistributedMember distributedMember : members) { List<String> memberGroups = distributedMember.getGroups(); existingGroups.addAll(memberGroups); } List<String> groupsList = new ArrayList<>(Arrays.asList(groups)); groupsList.removeAll(existingGroups); if (!groupsList.isEmpty()) { throw new IllegalArgumentException( CliStrings.format(CliStrings.CREATE_REGION__MSG__GROUPS_0_ARE_INVALID, new Object[] {String.valueOf(groupsList)})); } } } private void validateRegionFunctionArgs(InternalCache cache, RegionFunctionArgs regionFunctionArgs) { if (regionFunctionArgs.getRegionPath() == null) { throw new IllegalArgumentException(CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH); } ManagementService managementService = ManagementService.getExistingManagementService(cache); DistributedSystemMXBean dsMBean = managementService.getDistributedSystemMXBean(); String useAttributesFrom = regionFunctionArgs.getUseAttributesFrom(); if (useAttributesFrom != null && !useAttributesFrom.isEmpty() && regionExists(cache, useAttributesFrom)) { if (!regionExists(cache, useAttributesFrom)) { // check already done in createRegion !!! throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND, new Object[] {CliStrings.CREATE_REGION__USEATTRIBUTESFROM, useAttributesFrom})); } if (!regionFunctionArgs.isSetUseAttributesFrom() || regionFunctionArgs.getRegionAttributes() == null) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__COULD_NOT_RETRIEVE_REGION_ATTRS_FOR_PATH_0_VERIFY_REGION_EXISTS, useAttributesFrom)); } } if (regionFunctionArgs.hasPartitionAttributes()) { RegionFunctionArgs.PartitionArgs partitionArgs = regionFunctionArgs.getPartitionArgs(); String colocatedWith = partitionArgs.getPrColocatedWith(); if (colocatedWith != null && !colocatedWith.isEmpty()) { String[] listAllRegionPaths = dsMBean.listAllRegionPaths(); String foundRegionPath = null; for (String regionPath : listAllRegionPaths) { if (regionPath.equals(colocatedWith)) { foundRegionPath = regionPath; break; } } if (foundRegionPath == null) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND, new Object[] {CliStrings.CREATE_REGION__COLOCATEDWITH, colocatedWith})); } ManagementService mgmtService = ManagementService.getExistingManagementService(cache); DistributedRegionMXBean distributedRegionMXBean = mgmtService.getDistributedRegionMXBean(foundRegionPath); String regionType = distributedRegionMXBean.getRegionType(); if (!(DataPolicy.PARTITION.toString().equals(regionType) || DataPolicy.PERSISTENT_PARTITION.toString().equals(regionType))) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__COLOCATEDWITH_REGION_0_IS_NOT_PARTITIONEDREGION, new Object[] {colocatedWith})); } } if (partitionArgs.isSetPRLocalMaxMemory()) { int prLocalMaxMemory = partitionArgs.getPrLocalMaxMemory(); if (prLocalMaxMemory < 0) { throw new IllegalArgumentException( LocalizedStrings.AttributesFactory_PARTITIONATTRIBUTES_LOCALMAXMEMORY_MUST_NOT_BE_NEGATIVE .toLocalizedString()); } } if (partitionArgs.isSetPRTotalMaxMemory()) { long prTotalMaxMemory = partitionArgs.getPrTotalMaxMemory(); if (prTotalMaxMemory <= 0) { throw new IllegalArgumentException( LocalizedStrings.AttributesFactory_TOTAL_SIZE_OF_PARTITION_REGION_MUST_BE_0 .toLocalizedString()); } } if (partitionArgs.isSetPRRedundantCopies()) { int prRedundantCopies = partitionArgs.getPrRedundantCopies(); switch (prRedundantCopies) { case 0: case 1: case 2: case 3: break; default: throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__REDUNDANT_COPIES_SHOULD_BE_ONE_OF_0123, new Object[] {prRedundantCopies})); } } } String keyConstraint = regionFunctionArgs.getKeyConstraint(); if (keyConstraint != null && !isClassNameValid(keyConstraint)) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_KEYCONSTRAINT_0_IS_INVALID, new Object[] {keyConstraint})); } String valueConstraint = regionFunctionArgs.getValueConstraint(); if (valueConstraint != null && !isClassNameValid(valueConstraint)) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_VALUECONSTRAINT_0_IS_INVALID, new Object[] {valueConstraint})); } Set<String> cacheListeners = regionFunctionArgs.getCacheListeners(); if (cacheListeners != null && !cacheListeners.isEmpty()) { for (String cacheListener : cacheListeners) { if (!isClassNameValid(cacheListener)) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELISTENER_0_IS_INVALID, new Object[] {cacheListener})); } } } String cacheLoader = regionFunctionArgs.getCacheLoader(); if (cacheLoader != null && !isClassNameValid(cacheLoader)) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELOADER_0_IS_INVALID, new Object[] {cacheLoader})); } String cacheWriter = regionFunctionArgs.getCacheWriter(); if (cacheWriter != null && !isClassNameValid(cacheWriter)) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHEWRITER_0_IS_INVALID, new Object[] {cacheWriter})); } Set<String> gatewaySenderIds = regionFunctionArgs.getGatewaySenderIds(); if (gatewaySenderIds != null && !gatewaySenderIds.isEmpty()) { String[] gatewaySenders = dsMBean.listGatewaySenders(); if (gatewaySenders.length == 0) { throw new IllegalArgumentException( CliStrings.CREATE_REGION__MSG__NO_GATEWAYSENDERS_IN_THE_SYSTEM); } else { List<String> gatewaySendersList = new ArrayList<>(Arrays.asList(gatewaySenders)); gatewaySenderIds = new HashSet<>(gatewaySenderIds); gatewaySenderIds.removeAll(gatewaySendersList); if (!gatewaySenderIds.isEmpty()) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_GATEWAYSENDER_ID_UNKNOWN_0, new Object[] {gatewaySenderIds})); } } } if (regionFunctionArgs.isSetConcurrencyLevel()) { int concurrencyLevel = regionFunctionArgs.getConcurrencyLevel(); if (concurrencyLevel < 0) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_POSITIVE_INT_FOR_CONCURRENCYLEVEL_0_IS_NOT_VALID, new Object[] {concurrencyLevel})); } } String diskStore = regionFunctionArgs.getDiskStore(); if (diskStore != null) { RegionShortcut regionShortcut = regionFunctionArgs.getRegionShortcut(); if (regionShortcut != null && !PERSISTENT_OVERFLOW_SHORTCUTS.contains(regionShortcut)) { String subMessage = LocalizedStrings.DiskStore_IS_USED_IN_NONPERSISTENT_REGION.toLocalizedString(); String message = subMessage + ". " + CliStrings.format(CliStrings.CREATE_REGION__MSG__USE_ONE_OF_THESE_SHORTCUTS_0, new Object[] {String.valueOf(PERSISTENT_OVERFLOW_SHORTCUTS)}); throw new IllegalArgumentException(message); } RegionAttributes<?, ?> regionAttributes = regionFunctionArgs.getRegionAttributes(); if (regionAttributes != null && !regionAttributes.getDataPolicy().withPersistence()) { String subMessage = LocalizedStrings.DiskStore_IS_USED_IN_NONPERSISTENT_REGION.toLocalizedString(); String message = subMessage + ". " + CliStrings.format( CliStrings.CREATE_REGION__MSG__USE_ATTRIBUTES_FROM_REGION_0_IS_NOT_WITH_PERSISTENCE, new Object[] {String.valueOf(regionFunctionArgs.getUseAttributesFrom())}); throw new IllegalArgumentException(message); } if (!diskStoreExists(cache, diskStore)) { throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_DISKSTORE_UNKNOWN_DISKSTORE_0, new Object[] {diskStore})); } } RegionFunctionArgs.ExpirationAttrs entryExpirationIdleTime = regionFunctionArgs.getEntryExpirationIdleTime(); RegionFunctionArgs.ExpirationAttrs entryExpirationTTL = regionFunctionArgs.getEntryExpirationTTL(); RegionFunctionArgs.ExpirationAttrs regionExpirationIdleTime = regionFunctionArgs.getRegionExpirationIdleTime(); RegionFunctionArgs.ExpirationAttrs regionExpirationTTL = regionFunctionArgs.getRegionExpirationTTL(); if ((!regionFunctionArgs.isSetStatisticsEnabled() || !regionFunctionArgs.isStatisticsEnabled()) && (entryExpirationIdleTime != null || entryExpirationTTL != null || regionExpirationIdleTime != null || regionExpirationTTL != null)) { String message = LocalizedStrings.AttributesFactory_STATISTICS_MUST_BE_ENABLED_FOR_EXPIRATION .toLocalizedString(); throw new IllegalArgumentException(message + "."); } boolean compressorFailure = false; if (regionFunctionArgs.isSetCompressor()) { String compressorClassName = regionFunctionArgs.getCompressor(); Object compressor = null; try { Class<?> compressorClass = ClassPathLoader.getLatest().forName(compressorClassName); compressor = compressorClass.newInstance(); } catch (InstantiationException | ClassNotFoundException | IllegalAccessException e) { compressorFailure = true; } if (compressorFailure || !(compressor instanceof Compressor)) { throw new IllegalArgumentException( CliStrings.format(CliStrings.CREATE_REGION__MSG__INVALID_COMPRESSOR, new Object[] {regionFunctionArgs.getCompressor()})); } } if (regionFunctionArgs.hasPartitionAttributes()) { if (regionFunctionArgs.isPartitionResolverSet()) { String partitionResolverClassName = regionFunctionArgs.getPartitionResolver(); try { Class<PartitionResolver> resolverClass = (Class<PartitionResolver>) ClassPathLoader .getLatest().forName(partitionResolverClassName); PartitionResolver partitionResolver = resolverClass.newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { throw new IllegalArgumentException( CliStrings.format(CliStrings.CREATE_REGION__MSG__INVALID_PARTITION_RESOLVER, new Object[] {regionFunctionArgs.getCompressor()}), e); } } } } private boolean diskStoreExists(InternalCache cache, String diskStoreName) { ManagementService managementService = ManagementService.getExistingManagementService(cache); DistributedSystemMXBean dsMXBean = managementService.getDistributedSystemMXBean(); Map<String, String[]> diskstore = dsMXBean.listMemberDiskstore(); Set<Entry<String, String[]>> entrySet = diskstore.entrySet(); for (Entry<String, String[]> entry : entrySet) { String[] value = entry.getValue(); if (CliUtil.contains(value, diskStoreName)) { return true; } } return false; } private static <K, V> FetchRegionAttributesFunctionResult<K, V> getRegionAttributes( InternalCache cache, String regionPath) { if (!isClusterWideSameConfig(cache, regionPath)) { throw new IllegalStateException(CliStrings.format( CliStrings.CREATE_REGION__MSG__USE_ATTRIBUTES_FORM_REGIONS_EXISTS_BUT_DIFFERENT_SCOPE_OR_DATAPOLICY_USE_DESCRIBE_REGION_FOR_0, regionPath)); } FetchRegionAttributesFunctionResult<K, V> attributes = null; // First check whether the region exists on a this manager, if yes then no // need to use FetchRegionAttributesFunction to fetch RegionAttributes try { attributes = FetchRegionAttributesFunction.getRegionAttributes(regionPath); } catch (IllegalArgumentException e) { /* region doesn't exist on the manager */ } if (attributes == null) { // find first member which has the region Set<DistributedMember> regionAssociatedMembers = CliUtil.getRegionAssociatedMembers(regionPath, cache, false); if (regionAssociatedMembers != null && !regionAssociatedMembers.isEmpty()) { DistributedMember distributedMember = regionAssociatedMembers.iterator().next(); ResultCollector<?, ?> resultCollector = CliUtil .executeFunction(FetchRegionAttributesFunction.INSTANCE, regionPath, distributedMember); List<?> resultsList = (List<?>) resultCollector.getResult(); if (resultsList != null && !resultsList.isEmpty()) { for (Object object : resultsList) { if (object instanceof IllegalArgumentException) { throw (IllegalArgumentException) object; } else if (object instanceof Throwable) { Throwable th = (Throwable) object; LogWrapper.getInstance().info(CliUtil.stackTraceAsString((th))); throw new IllegalArgumentException(CliStrings.format( CliStrings.CREATE_REGION__MSG__COULD_NOT_RETRIEVE_REGION_ATTRS_FOR_PATH_0_REASON_1, new Object[] {regionPath, th.getMessage()})); } else { // has to be RegionAttributes @SuppressWarnings("unchecked") // to avoid warning :( FetchRegionAttributesFunctionResult<K, V> regAttr = ((FetchRegionAttributesFunctionResult<K, V>) object); if (attributes == null) { attributes = regAttr; break; } // attributes null check } // not IllegalArgumentException or other throwable } // iterate over list - there should be only one result in the list } // result list is not null or mpty } // regionAssociatedMembers is not-empty } // attributes are null because do not exist on local member return attributes; } private static boolean isClusterWideSameConfig(InternalCache cache, String regionPath) { ManagementService managementService = ManagementService.getExistingManagementService(cache); DistributedSystemMXBean dsMXBean = managementService.getDistributedSystemMXBean(); Set<DistributedMember> allMembers = CliUtil.getAllNormalMembers(cache); RegionAttributesData regionAttributesToValidateAgainst = null; for (DistributedMember distributedMember : allMembers) { ObjectName regionObjectName; try { regionObjectName = dsMXBean .fetchRegionObjectName(CliUtil.getMemberNameOrId(distributedMember), regionPath); RegionMXBean regionMBean = managementService.getMBeanInstance(regionObjectName, RegionMXBean.class); RegionAttributesData regionAttributes = regionMBean.listRegionAttributes(); if (regionAttributesToValidateAgainst == null) { regionAttributesToValidateAgainst = regionAttributes; } else if (!(regionAttributesToValidateAgainst.getScope() .equals(regionAttributes.getScope()) || regionAttributesToValidateAgainst.getDataPolicy() .equals(regionAttributes.getDataPolicy()))) { return false; } } catch (Exception e) { // ignore } } return true; } private boolean isClassNameValid(String fqcn) { if (fqcn.isEmpty()) { return true; } String regex = "([\\p{L}_$][\\p{L}\\p{N}_$]*\\.)*[\\p{L}_$][\\p{L}\\p{N}_$]*"; return Pattern.matches(regex, fqcn); } @CliCommand(value = {CliStrings.DESTROY_REGION}, help = CliStrings.DESTROY_REGION__HELP) @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION) @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE) public Result destroyRegion( @CliOption(key = CliStrings.DESTROY_REGION__REGION, optionContext = ConverterHint.REGION_PATH, mandatory = true, help = CliStrings.DESTROY_REGION__REGION__HELP) String regionPath) { if (regionPath == null) { return ResultBuilder .createInfoResult(CliStrings.DESTROY_REGION__MSG__SPECIFY_REGIONPATH_TO_DESTROY); } if (StringUtils.isBlank(regionPath) || regionPath.equals(Region.SEPARATOR)) { return ResultBuilder.createInfoResult(CliStrings.format( CliStrings.DESTROY_REGION__MSG__REGIONPATH_0_NOT_VALID, new Object[] {regionPath})); } Result result; AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>(); try { InternalCache cache = getCache(); ManagementService managementService = ManagementService.getExistingManagementService(cache); String regionPathToUse = regionPath; if (!regionPathToUse.startsWith(Region.SEPARATOR)) { regionPathToUse = Region.SEPARATOR + regionPathToUse; } Set<DistributedMember> regionMembersList = findMembersForRegion(cache, managementService, regionPathToUse); if (regionMembersList.size() == 0) { return ResultBuilder.createUserErrorResult( CliStrings.format(CliStrings.DESTROY_REGION__MSG__COULDNOT_FIND_REGIONPATH_0_IN_GEODE, new Object[] {regionPath, "jmx-manager-update-rate milliseconds"})); } CliFunctionResult destroyRegionResult; ResultCollector<?, ?> resultCollector = CliUtil.executeFunction(RegionDestroyFunction.INSTANCE, regionPath, regionMembersList); List<CliFunctionResult> resultsList = (List<CliFunctionResult>) resultCollector.getResult(); String message = CliStrings.format(CliStrings.DESTROY_REGION__MSG__REGION_0_1_DESTROYED, new Object[] {regionPath, ""}); // Only if there is an error is this set to false boolean isRegionDestroyed = true; for (CliFunctionResult aResultsList : resultsList) { destroyRegionResult = aResultsList; if (destroyRegionResult.isSuccessful()) { xmlEntity.set(destroyRegionResult.getXmlEntity()); } else if (destroyRegionResult.getThrowable() != null) { Throwable t = destroyRegionResult.getThrowable(); LogWrapper.getInstance().info(t.getMessage(), t); message = CliStrings.format( CliStrings.DESTROY_REGION__MSG__ERROR_OCCURRED_WHILE_DESTROYING_0_REASON_1, new Object[] {regionPath, t.getMessage()}); isRegionDestroyed = false; } else { message = CliStrings.format( CliStrings.DESTROY_REGION__MSG__UNKNOWN_RESULT_WHILE_DESTROYING_REGION_0_REASON_1, new Object[] {regionPath, destroyRegionResult.getMessage()}); isRegionDestroyed = false; } } if (isRegionDestroyed) { result = ResultBuilder.createInfoResult(message); } else { result = ResultBuilder.createUserErrorResult(message); } } catch (IllegalStateException e) { result = ResultBuilder.createUserErrorResult(CliStrings.format( CliStrings.DESTROY_REGION__MSG__ERROR_WHILE_DESTROYING_REGION_0_REASON_1, new Object[] {regionPath, e.getMessage()})); } catch (Exception e) { result = ResultBuilder.createGemFireErrorResult(CliStrings.format( CliStrings.DESTROY_REGION__MSG__ERROR_WHILE_DESTROYING_REGION_0_REASON_1, new Object[] {regionPath, e.getMessage()})); } if (xmlEntity.get() != null) { persistClusterConfiguration(result, () -> getSharedConfiguration().deleteXmlEntity(xmlEntity.get(), null)); } return result; } private Set<DistributedMember> findMembersForRegion(InternalCache cache, ManagementService managementService, String regionPath) { Set<DistributedMember> membersList = new HashSet<>(); Set<String> regionMemberIds = new HashSet<>(); MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer; // needs to be escaped with quotes if it contains a hyphen if (regionPath.contains("-")) { regionPath = "\"" + regionPath + "\""; } String queryExp = MessageFormat.format(MBeanJMXAdapter.OBJECTNAME__REGION_MXBEAN, regionPath, "*"); try { ObjectName queryExpON = new ObjectName(queryExp); Set<ObjectName> queryNames = mbeanServer.queryNames(null, queryExpON); if (queryNames == null || queryNames.isEmpty()) { return membersList; // protects against null pointer exception below } boolean addedOneRemote = false; for (ObjectName regionMBeanObjectName : queryNames) { try { RegionMXBean regionMXBean = managementService.getMBeanInstance(regionMBeanObjectName, RegionMXBean.class); if (regionMXBean != null) { RegionAttributesData regionAttributes = regionMXBean.listRegionAttributes(); String scope = regionAttributes.getScope(); // For Scope.LOCAL regions we need to identify each hosting member, but for // other scopes we just need a single member as the region destroy will be // propagated. if (Scope.LOCAL.equals(Scope.fromString(scope))) { regionMemberIds.add(regionMXBean.getMember()); } else { if (!addedOneRemote) { regionMemberIds.add(regionMXBean.getMember()); addedOneRemote = true; } } } } catch (ClassCastException e) { LogWriter logger = cache.getLogger(); if (logger.finerEnabled()) { logger.finer(regionMBeanObjectName + " is not a " + RegionMXBean.class.getSimpleName(), e); } } } if (!regionMemberIds.isEmpty()) { membersList = getMembersByIds(cache, regionMemberIds); } } catch (MalformedObjectNameException | NullPointerException e) { LogWrapper.getInstance().info(e.getMessage(), e); } return membersList; } private Set<DistributedMember> getMembersByIds(InternalCache cache, Set<String> memberIds) { Set<DistributedMember> foundMembers = Collections.emptySet(); if (memberIds != null && !memberIds.isEmpty()) { foundMembers = new HashSet<>(); Set<DistributedMember> allNormalMembers = CliUtil.getAllNormalMembers(cache); for (String memberId : memberIds) { for (DistributedMember distributedMember : allNormalMembers) { if (memberId.equals(distributedMember.getId()) || memberId.equals(distributedMember.getName())) { foundMembers.add(distributedMember); } } } } return foundMembers; } @CliAvailabilityIndicator({CliStrings.ALTER_REGION, CliStrings.CREATE_REGION, CliStrings.DESTROY_REGION}) public boolean isRegionCommandAvailable() { boolean isAvailable = true; // always available on server if (CliUtil.isGfshVM()) { // in gfsh check if connected //TODO: make this better isAvailable = getGfsh() != null && getGfsh().isConnectedAndReady(); } return isAvailable; } }
GEODE-3092: fix specifiedDefaultValue for cacheLoader and cacheWriter - add imports (cherry picked from commit c6d88f7)
geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommands.java
GEODE-3092: fix specifiedDefaultValue for cacheLoader and cacheWriter - add imports
<ide><path>eode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommands.java <ide> import javax.management.ObjectName; <ide> <ide> import org.apache.commons.lang.StringUtils; <add>import org.springframework.shell.core.annotation.CliAvailabilityIndicator; <ide> import org.springframework.shell.core.annotation.CliCommand; <ide> import org.springframework.shell.core.annotation.CliOption; <ide>
Java
apache-2.0
620c7203cc55f3b5ad87b54df4e4c5dc26fb9c43
0
xfournet/intellij-community,signed/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,xfournet/intellij-community,da1z/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,samthor/intellij-community,xfournet/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,signed/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,jexp/idea2,michaelgallacher/intellij-community,retomerz/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,izonder/intellij-community,signed/intellij-community,ernestp/consulo,semonte/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,amith01994/intellij-community,signed/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,robovm/robovm-studio,xfournet/intellij-community,youdonghai/intellij-community,caot/intellij-community,slisson/intellij-community,asedunov/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,asedunov/intellij-community,diorcety/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,da1z/intellij-community,tmpgit/intellij-community,holmes/intellij-community,jagguli/intellij-community,amith01994/intellij-community,hurricup/intellij-community,allotria/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,caot/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,petteyg/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,holmes/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,ernestp/consulo,da1z/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,consulo/consulo,retomerz/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,kool79/intellij-community,kdwink/intellij-community,joewalnes/idea-community,caot/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,allotria/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,joewalnes/idea-community,caot/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,ibinti/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,joewalnes/idea-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,consulo/consulo,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,slisson/intellij-community,da1z/intellij-community,slisson/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,dslomov/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,kool79/intellij-community,FHannes/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,jexp/idea2,dslomov/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,jexp/idea2,semonte/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,ryano144/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,caot/intellij-community,adedayo/intellij-community,FHannes/intellij-community,adedayo/intellij-community,da1z/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,allotria/intellij-community,caot/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,jagguli/intellij-community,fitermay/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,semonte/intellij-community,clumsy/intellij-community,dslomov/intellij-community,ibinti/intellij-community,petteyg/intellij-community,petteyg/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,Distrotech/intellij-community,allotria/intellij-community,kool79/intellij-community,signed/intellij-community,samthor/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,holmes/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,signed/intellij-community,adedayo/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,diorcety/intellij-community,allotria/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,kool79/intellij-community,clumsy/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,slisson/intellij-community,ryano144/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,vladmm/intellij-community,holmes/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,slisson/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,ernestp/consulo,fnouama/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,allotria/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,izonder/intellij-community,petteyg/intellij-community,adedayo/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,consulo/consulo,muntasirsyed/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,consulo/consulo,signed/intellij-community,hurricup/intellij-community,supersven/intellij-community,hurricup/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,fitermay/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,jagguli/intellij-community,robovm/robovm-studio,asedunov/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,blademainer/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,vvv1559/intellij-community,jexp/idea2,caot/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,kool79/intellij-community,ibinti/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,jexp/idea2,fnouama/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,retomerz/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,signed/intellij-community,caot/intellij-community,asedunov/intellij-community,caot/intellij-community,blademainer/intellij-community,diorcety/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,joewalnes/idea-community,diorcety/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,consulo/consulo,joewalnes/idea-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,signed/intellij-community,samthor/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,ernestp/consulo,akosyakov/intellij-community,tmpgit/intellij-community,signed/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,amith01994/intellij-community,caot/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,vladmm/intellij-community,holmes/intellij-community,caot/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,ernestp/consulo,jexp/idea2,pwoodworth/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,nicolargo/intellij-community,kool79/intellij-community,supersven/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,apixandru/intellij-community,da1z/intellij-community,allotria/intellij-community,xfournet/intellij-community,dslomov/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,joewalnes/idea-community,vladmm/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,robovm/robovm-studio,hurricup/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,semonte/intellij-community,da1z/intellij-community,caot/intellij-community,kdwink/intellij-community,supersven/intellij-community,da1z/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,holmes/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,supersven/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,semonte/intellij-community,gnuhub/intellij-community,da1z/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,izonder/intellij-community,da1z/intellij-community,amith01994/intellij-community,jagguli/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,kool79/intellij-community,hurricup/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,izonder/intellij-community,asedunov/intellij-community,jexp/idea2,SerCeMan/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,samthor/intellij-community,holmes/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,robovm/robovm-studio,kdwink/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,kdwink/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,ernestp/consulo,tmpgit/intellij-community,FHannes/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,holmes/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,samthor/intellij-community,fnouama/intellij-community,holmes/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,fnouama/intellij-community,kool79/intellij-community,nicolargo/intellij-community,slisson/intellij-community,robovm/robovm-studio,kool79/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,jexp/idea2,fengbaicanhe/intellij-community,dslomov/intellij-community,izonder/intellij-community,allotria/intellij-community,consulo/consulo,allotria/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,amith01994/intellij-community,joewalnes/idea-community,asedunov/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,vladmm/intellij-community,robovm/robovm-studio,semonte/intellij-community,slisson/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,FHannes/intellij-community,apixandru/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,blademainer/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,joewalnes/idea-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,asedunov/intellij-community,semonte/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,supersven/intellij-community,xfournet/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,retomerz/intellij-community,clumsy/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,joewalnes/idea-community,ol-loginov/intellij-community,samthor/intellij-community,samthor/intellij-community,samthor/intellij-community,robovm/robovm-studio,adedayo/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community
/* * Copyright (c) 2005 JetBrains s.r.o. All Rights Reserved. */ package com.intellij.util.io; import com.intellij.openapi.Forceable; import com.intellij.openapi.diagnostic.Logger; import org.jetbrains.annotations.NonNls; import java.io.*; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; /** * @author max */ public class MappedFile implements Forceable { private static final Logger LOG = Logger.getInstance("#com.intellij.util.io.MappedFile"); private MappedBufferWrapper myHolder; private final File myFile; private long myRealSize; private long mySize; private long myPosition; private boolean myIsDirty = false; @NonNls private static final String UTF_8_CHARSET_NAME = "UTF-8"; @NonNls private static final String RW = "rw"; private byte[] buffer = new byte[8]; public MappedFile(File file, int initialSize) throws IOException { myFile = file; if (!file.exists() || file.length() == 0) { writeLength(0); } myPosition = 0; map(); mySize = readLength(); if (mySize == 0) { resize(initialSize); } } private long readLength() { File lengthFile = getLengthFile(); DataInputStream stream = null; try { stream = new DataInputStream(new FileInputStream(lengthFile)); return stream.readLong(); } catch (IOException e) { writeLength(myRealSize); return myRealSize; } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { LOG.error(e); } } } } private File getLengthFile() { return new File(myFile.getPath() + ".len"); } private void writeLength(final long len) { File lengthFile = getLengthFile(); DataOutputStream stream = null; try { stream = new DataOutputStream(new FileOutputStream(lengthFile)); stream.writeLong(len); } catch (FileNotFoundException e) { LOG.error(e); } catch (IOException e) { LOG.error(e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { LOG.error(e); } } } } private void map() throws IOException { myHolder = new ReadWriteMappedBufferWrapper(myFile); myRealSize = myFile.length(); if (LOG.isDebugEnabled()) { LOG.assertTrue(myPosition >= 0L && myPosition < myRealSize, "myPosition=" + myPosition + ", myRealSize=" + myRealSize); } myHolder.buf().position((int)myPosition); } public short getShort(int index) throws IOException { seek(index); return readShort(); } public short readShort() throws IOException { get(buffer, 0, 2); int ch1 = buffer[0] & 0xff; int ch2 = buffer[1] & 0xff; return (short)((ch1 << 8) + ch2); } public void putShort(int index, short value) throws IOException { seek(index); writeShort(value); } public void writeShort(int value) throws IOException { buffer[0] = (byte)((value >>> 8) & 0xFF); buffer[1] = (byte)(value & 0xFF); put(buffer, 0, 2); } public int getInt(int index) throws IOException { seek(index); return readInt(); } public long getLong(final int index) throws IOException { seek(index); return readLong(); } public void putInt(int index, int value) throws IOException { seek(index); writeInt(value); } public void putLong(final int index, final long value) throws IOException { seek(index); writeLong(value); } public byte get(int index) throws IOException { seek(index); return readByte(); } public void put(int index, byte value) throws IOException { seek(index); writeByte(value); } public void get(int index, byte[] dst, int offset, int length) throws IOException { seek(index); get(dst, offset, length); } public void get(final byte[] dst, final int offset, final int length) throws IOException { if (myPosition + length > mySize) { throw new EOFException(); } buf().get(dst, offset, length); myPosition += length; } public void put(int index, byte[] src, int offset, int length) throws IOException { seek(index); put(src, offset, length); } public void seek(long pos) throws IOException { ensureSize(pos); buf().position((int)pos); myPosition = pos; if (pos > mySize) { mySize = pos; } } private ByteBuffer buf() { if (!isMapped()) { try { map(); } catch (IOException e) { LOG.error(e); // TODO: rethrow? } } return myHolder.buf(); } private void ensureSize(final long pos) throws IOException { while (pos >= myRealSize) { expand(); } } private void expand() throws IOException { resize((int)((myRealSize + 1) * 13) >> 3); } public void put(final byte[] src, final int offset, final int length) throws IOException { ensureSize(myPosition + length); myIsDirty = true; buf().put(src, offset, length); myPosition += length; if (myPosition > mySize) { mySize = myPosition; } } public void flush() { if (myIsDirty) { writeLength(mySize); final ByteBuffer buf = buf(); if (buf instanceof MappedByteBuffer) { ((MappedByteBuffer)buf).force(); } myIsDirty = false; } } public void force() { flush(); } public boolean isDirty() { return myIsDirty; } public void close() { writeLength(mySize); unmap(); } public void resize(int size) throws IOException { final int current = (int)myRealSize; if (current == size) return; unmap(); RandomAccessFile raf = new RandomAccessFile(myFile, RW); try { raf.setLength(size); } finally { raf.close(); } map(); } public final long length() { return mySize; } public long getFilePointer() { return myPosition; } public int readInt() throws IOException { get(buffer, 0, 4); int ch1 = buffer[0] & 0xff; int ch2 = buffer[1] & 0xff; int ch3 = buffer[2] & 0xff; int ch4 = buffer[3] & 0xff; return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + ch4); } public long readLong() throws IOException { get(buffer, 0, 8); long ch1 = buffer[0] & 0xff; long ch2 = buffer[1] & 0xff; long ch3 = buffer[2] & 0xff; long ch4 = buffer[3] & 0xff; long ch5 = buffer[4] & 0xff; long ch6 = buffer[5] & 0xff; long ch7 = buffer[6] & 0xff; long ch8 = buffer[7] & 0xff; return (ch1 << 56) + (ch2 << 48) + (ch3 << 40) + (ch4 << 32) + (ch5 << 24) + (ch6 << 16) + (ch7 << 8) + ch8; } public void writeInt(int value) throws IOException { buffer[0] = (byte)((value >>> 24) & 0xFF); buffer[1] = (byte)((value >>> 16) & 0xFF); buffer[2] = (byte)((value >>> 8) & 0xFF); buffer[3] = (byte)(value & 0xFF); put(buffer, 0, 4); } public void writeLong(long value) throws IOException { buffer[0] = (byte)((value >>> 56) & 0xFF); buffer[1] = (byte)((value >>> 48) & 0xFF); buffer[2] = (byte)((value >>> 40) & 0xFF); buffer[3] = (byte)((value >>> 32) & 0xFF); buffer[4] = (byte)((value >>> 24) & 0xFF); buffer[5] = (byte)((value >>> 16) & 0xFF); buffer[6] = (byte)((value >>> 8) & 0xFF); buffer[7] = (byte)(value & 0xFF); put(buffer, 0, 8); } public String readUTF() throws IOException { try { int len = readInt(); byte[] bytes = new byte[ len ]; get(bytes, 0, len); return new String(bytes, UTF_8_CHARSET_NAME); } catch (UnsupportedEncodingException e) { // Can't be return ""; } } public void writeUTF(String value) throws IOException { try { final byte[] bytes = value.getBytes(UTF_8_CHARSET_NAME); writeInt(bytes.length); put(bytes, 0, bytes.length); } catch (UnsupportedEncodingException e) { // Can't be } } public int readUnsignedShort() throws IOException { get(buffer, 0, 2); int ch1 = buffer[0] & 0xff; int ch2 = buffer[1] & 0xff; return (ch1 << 8) + ch2; } public char readChar() throws IOException { return (char)readUnsignedShort(); } public void writeChar(char value) throws IOException { writeShort(value); } public byte readByte() throws IOException { get(buffer, 0, 1); return buffer[0]; } public void writeByte(byte value) throws IOException { buffer[0] = value; put(buffer, 0, 1); } private void unmap() { if (myHolder != null) { /* flush(); TODO: Don't commit... */ myHolder.unmap(); } } public boolean isMapped() { return myHolder.isMapped(); } }
util/src/com/intellij/util/io/MappedFile.java
/* * Copyright (c) 2005 JetBrains s.r.o. All Rights Reserved. */ package com.intellij.util.io; import com.intellij.openapi.Forceable; import com.intellij.openapi.diagnostic.Logger; import org.jetbrains.annotations.NonNls; import java.io.*; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; /** * @author max */ public class MappedFile implements Forceable { private static final Logger LOG = Logger.getInstance("#com.intellij.util.io.MappedFile"); private MappedBufferWrapper myHolder; private final File myFile; private long myRealSize; private long mySize; private long myPosition; private boolean myIsDirty = false; @NonNls private static final String UTF_8_CHARSET_NAME = "UTF-8"; @NonNls private static final String RW = "rw"; private byte[] buffer = new byte[8]; public MappedFile(File file, int initialSize) throws IOException { myFile = file; if (!file.exists()) { writeLength(0); } myPosition = 0; map(); mySize = readLength(); if (mySize == 0) { resize(initialSize); } } private long readLength() { File lengthFile = getLengthFile(); DataInputStream stream = null; try { stream = new DataInputStream(new FileInputStream(lengthFile)); return stream.readLong(); } catch (IOException e) { writeLength(myRealSize); return myRealSize; } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { LOG.error(e); } } } } private File getLengthFile() { return new File(myFile.getPath() + ".len"); } private void writeLength(final long len) { File lengthFile = getLengthFile(); DataOutputStream stream = null; try { stream = new DataOutputStream(new FileOutputStream(lengthFile)); stream.writeLong(len); } catch (FileNotFoundException e) { LOG.error(e); } catch (IOException e) { LOG.error(e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { LOG.error(e); } } } } private void map() throws IOException { myHolder = new ReadWriteMappedBufferWrapper(myFile); myRealSize = myFile.length(); if (LOG.isDebugEnabled()) { LOG.assertTrue(myPosition >= 0L && myPosition < myRealSize, "myPosition=" + myPosition + ", myRealSize=" + myRealSize); } myHolder.buf().position((int)myPosition); } public short getShort(int index) throws IOException { seek(index); return readShort(); } public short readShort() throws IOException { get(buffer, 0, 2); int ch1 = buffer[0] & 0xff; int ch2 = buffer[1] & 0xff; return (short)((ch1 << 8) + ch2); } public void putShort(int index, short value) throws IOException { seek(index); writeShort(value); } public void writeShort(int value) throws IOException { buffer[0] = (byte)((value >>> 8) & 0xFF); buffer[1] = (byte)(value & 0xFF); put(buffer, 0, 2); } public int getInt(int index) throws IOException { seek(index); return readInt(); } public long getLong(final int index) throws IOException { seek(index); return readLong(); } public void putInt(int index, int value) throws IOException { seek(index); writeInt(value); } public void putLong(final int index, final long value) throws IOException { seek(index); writeLong(value); } public byte get(int index) throws IOException { seek(index); return readByte(); } public void put(int index, byte value) throws IOException { seek(index); writeByte(value); } public void get(int index, byte[] dst, int offset, int length) throws IOException { seek(index); get(dst, offset, length); } public void get(final byte[] dst, final int offset, final int length) throws IOException { if (myPosition + length > mySize) { throw new EOFException(); } buf().get(dst, offset, length); myPosition += length; } public void put(int index, byte[] src, int offset, int length) throws IOException { seek(index); put(src, offset, length); } public void seek(long pos) throws IOException { ensureSize(pos); buf().position((int)pos); myPosition = pos; if (pos > mySize) { mySize = pos; } } private ByteBuffer buf() { if (!isMapped()) { try { map(); } catch (IOException e) { LOG.error(e); // TODO: rethrow? } } return myHolder.buf(); } private void ensureSize(final long pos) throws IOException { while (pos >= myRealSize) { expand(); } } private void expand() throws IOException { resize((int)((myRealSize + 1) * 13) >> 3); } public void put(final byte[] src, final int offset, final int length) throws IOException { ensureSize(myPosition + length); myIsDirty = true; buf().put(src, offset, length); myPosition += length; if (myPosition > mySize) { mySize = myPosition; } } public void flush() { if (myIsDirty) { writeLength(mySize); final ByteBuffer buf = buf(); if (buf instanceof MappedByteBuffer) { ((MappedByteBuffer)buf).force(); } myIsDirty = false; } } public void force() { flush(); } public boolean isDirty() { return myIsDirty; } public void close() { writeLength(mySize); unmap(); } public void resize(int size) throws IOException { final int current = (int)myRealSize; if (current == size) return; unmap(); RandomAccessFile raf = new RandomAccessFile(myFile, RW); try { raf.setLength(size); } finally { raf.close(); } map(); } public final long length() { return mySize; } public long getFilePointer() { return myPosition; } public int readInt() throws IOException { get(buffer, 0, 4); int ch1 = buffer[0] & 0xff; int ch2 = buffer[1] & 0xff; int ch3 = buffer[2] & 0xff; int ch4 = buffer[3] & 0xff; return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + ch4); } public long readLong() throws IOException { get(buffer, 0, 8); long ch1 = buffer[0] & 0xff; long ch2 = buffer[1] & 0xff; long ch3 = buffer[2] & 0xff; long ch4 = buffer[3] & 0xff; long ch5 = buffer[4] & 0xff; long ch6 = buffer[5] & 0xff; long ch7 = buffer[6] & 0xff; long ch8 = buffer[7] & 0xff; return (ch1 << 56) + (ch2 << 48) + (ch3 << 40) + (ch4 << 32) + (ch5 << 24) + (ch6 << 16) + (ch7 << 8) + ch8; } public void writeInt(int value) throws IOException { buffer[0] = (byte)((value >>> 24) & 0xFF); buffer[1] = (byte)((value >>> 16) & 0xFF); buffer[2] = (byte)((value >>> 8) & 0xFF); buffer[3] = (byte)(value & 0xFF); put(buffer, 0, 4); } public void writeLong(long value) throws IOException { buffer[0] = (byte)((value >>> 56) & 0xFF); buffer[1] = (byte)((value >>> 48) & 0xFF); buffer[2] = (byte)((value >>> 40) & 0xFF); buffer[3] = (byte)((value >>> 32) & 0xFF); buffer[4] = (byte)((value >>> 24) & 0xFF); buffer[5] = (byte)((value >>> 16) & 0xFF); buffer[6] = (byte)((value >>> 8) & 0xFF); buffer[7] = (byte)(value & 0xFF); put(buffer, 0, 8); } public String readUTF() throws IOException { try { int len = readInt(); byte[] bytes = new byte[ len ]; get(bytes, 0, len); return new String(bytes, UTF_8_CHARSET_NAME); } catch (UnsupportedEncodingException e) { // Can't be return ""; } } public void writeUTF(String value) throws IOException { try { final byte[] bytes = value.getBytes(UTF_8_CHARSET_NAME); writeInt(bytes.length); put(bytes, 0, bytes.length); } catch (UnsupportedEncodingException e) { // Can't be } } public int readUnsignedShort() throws IOException { get(buffer, 0, 2); int ch1 = buffer[0] & 0xff; int ch2 = buffer[1] & 0xff; return (ch1 << 8) + ch2; } public char readChar() throws IOException { return (char)readUnsignedShort(); } public void writeChar(char value) throws IOException { writeShort(value); } public byte readByte() throws IOException { get(buffer, 0, 1); return buffer[0]; } public void writeByte(byte value) throws IOException { buffer[0] = value; put(buffer, 0, 1); } private void unmap() { if (myHolder != null) { /* flush(); TODO: Don't commit... */ myHolder.unmap(); } } public boolean isMapped() { return myHolder.isMapped(); } }
[max]
util/src/com/intellij/util/io/MappedFile.java
[max]
<ide><path>til/src/com/intellij/util/io/MappedFile.java <ide> <ide> public MappedFile(File file, int initialSize) throws IOException { <ide> myFile = file; <del> if (!file.exists()) { <add> if (!file.exists() || file.length() == 0) { <ide> writeLength(0); <ide> } <ide>
Java
apache-2.0
1ef2dcafec8fcdea93e5896f9d80e3835602ad72
0
akirakw/asakusafw,asakusafw/asakusafw,akirakw/asakusafw,ashigeru/asakusafw,ashigeru/asakusafw,asakusafw/asakusafw
/** * Copyright 2011-2017 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asakusafw.directio.hive.parquet; import java.io.IOException; import java.lang.reflect.Constructor; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import com.asakusafw.directio.hive.serde.DataModelDescriptor; import com.asakusafw.directio.hive.serde.DataModelDriver; import com.asakusafw.directio.hive.serde.DataModelMapping; import com.asakusafw.runtime.directio.Counter; import com.asakusafw.runtime.io.ModelInput; import parquet.column.page.PageReadStore; import parquet.hadoop.ParquetFileReader; import parquet.hadoop.metadata.BlockMetaData; import parquet.hadoop.metadata.ColumnChunkMetaData; import parquet.hadoop.metadata.FileMetaData; import parquet.hadoop.metadata.ParquetMetadata; import parquet.io.ColumnIOFactory; import parquet.io.MessageColumnIO; import parquet.io.RecordReader; /** * An implementation of {@link ModelInput} for reading Parquet files. * @param <T> the data model type * @since 0.7.0 */ public class ParquetFileInput<T> implements ModelInput<T> { static final Log LOG = LogFactory.getLog(ParquetFileInput.class); private static final Constructor<ParquetFileReader> FILE_READER_NEWER_CTOR; static { LOG.debug("loading newer ParquetFileReader.<init>"); Constructor<ParquetFileReader> ctor = null; try { ctor = ParquetFileReader.class.getConstructor( Configuration.class, FileMetaData.class, Path.class, List.class, List.class); } catch (ReflectiveOperationException e) { LOG.debug("cannot load newer ParquetFileReader.<init>", e); } FILE_READER_NEWER_CTOR = ctor; } private final DataModelDescriptor descriptor; private final DataModelMapping mappingConfiguration; private final Configuration hadoopConfiguration; private final Path path; private final long offset; private final long fragmentSize; private final Counter counter; private long rowRest = -1; private ParquetFileReader fileReader; private DataModelMaterializer materializer; private RecordReader<Object> currentRecordReader; private MessageColumnIO columnIo; private double averageBytesPerRecord; private double lastBytes; /** * Creates a new instance. * @param descriptor the target data model descriptor * @param mappingConfiguration the {@link DataModelDriver} configuration * @param hadoopConfiguration the hadoop configuration * @param path the path to the target file * @param offset starting stream offset * @param fragmentSize suggested fragment bytes count * @param counter the current counter */ public ParquetFileInput( DataModelDescriptor descriptor, DataModelMapping mappingConfiguration, Configuration hadoopConfiguration, Path path, long offset, long fragmentSize, Counter counter) { this.descriptor = descriptor; this.mappingConfiguration = mappingConfiguration; this.hadoopConfiguration = hadoopConfiguration; this.path = path; this.offset = offset; this.fragmentSize = fragmentSize; this.counter = counter; } @Override public boolean readTo(T model) throws IOException { RecordReader<Object> reader = prepareReader(model); if (reader == null) { return false; } rowRest--; reader.read(); advanceCounter(); return true; } private void advanceCounter() { double last = lastBytes; double next = last + averageBytesPerRecord; long delta = (long) (next - last); if (delta >= 0L) { counter.add(delta); } lastBytes = next; } private RecordReader<Object> prepareReader(T model) throws IOException { while (rowRest <= 0) { PageReadStore next = fetchRowGroup(); if (next == null) { return null; } currentRecordReader = createRecordReader(next); } assert currentRecordReader != null; assert materializer != null; materializer.setNextRecord(model); return currentRecordReader; } private PageReadStore fetchRowGroup() throws IOException { if (fileReader == null) { if (LOG.isInfoEnabled()) { LOG.info(MessageFormat.format( Messages.getString("ParquetFileInput.infoLoadMetadata"), //$NON-NLS-1$ descriptor.getDataModelClass().getSimpleName(), path)); } ParquetMetadata footer = ParquetFileReader.readFooter(hadoopConfiguration, path); List<BlockMetaData> blocks = filterBlocks(footer.getBlocks()); if (blocks.isEmpty()) { return null; } long totalRecords = computeTotalRecords(blocks); this.averageBytesPerRecord = (double) fragmentSize / totalRecords; if (LOG.isInfoEnabled()) { LOG.info(MessageFormat.format( Messages.getString("ParquetFileInput.infoLoadContents"), //$NON-NLS-1$ descriptor.getDataModelClass().getSimpleName(), path, offset, fragmentSize)); } this.fileReader = createFileReader(footer, blocks); this.materializer = new DataModelMaterializer( descriptor, footer.getFileMetaData().getSchema(), mappingConfiguration); this.columnIo = new ColumnIOFactory().getColumnIO( materializer.getMaterializeSchema(), footer.getFileMetaData().getSchema()); } return fileReader.readNextRowGroup(); } private ParquetFileReader createFileReader(ParquetMetadata meta, List<BlockMetaData> blocks) throws IOException { FileMetaData fileMetaData = meta.getFileMetaData(); if (FILE_READER_NEWER_CTOR != null) { try { return FILE_READER_NEWER_CTOR.newInstance( hadoopConfiguration, fileMetaData, path, blocks, fileMetaData.getSchema().getColumns()); } catch (ReflectiveOperationException | IllegalArgumentException | SecurityException e) { LOG.debug("failed ParquetFileReader.<init>", e); } } return new ParquetFileReader( hadoopConfiguration, path, blocks, fileMetaData.getSchema().getColumns()); } private static long computeTotalRecords(List<BlockMetaData> blocks) { long result = 0L; for (BlockMetaData block : blocks) { result += block.getTotalByteSize(); } return result; } private List<BlockMetaData> filterBlocks(List<BlockMetaData> blocks) { if (fragmentSize < 0L) { return blocks; } if (LOG.isDebugEnabled()) { LOG.debug(MessageFormat.format( "Detecting target parquet blocks: {0} ({1}+{2})", //$NON-NLS-1$ path, this.offset, this.fragmentSize)); } List<BlockMetaData> results = new ArrayList<>(); for (BlockMetaData block : blocks) { List<ColumnChunkMetaData> columns = block.getColumns(); if (columns.isEmpty()) { return Collections.emptyList(); } long begin = Long.MAX_VALUE; long end = -1L; for (ColumnChunkMetaData column : block.getColumns()) { long off = column.getFirstDataPageOffset(); long len = column.getTotalSize(); begin = Math.min(begin, off); end = Math.max(end, off + len); } assert begin >= 0L; assert end >= 0L; if (this.offset <= begin && end <= this.offset + this.fragmentSize && block.getRowCount() != 0) { if (LOG.isDebugEnabled()) { LOG.debug(MessageFormat.format( "Detected a target parquet block: {0} ({1}+{2})", //$NON-NLS-1$ path, begin, end - begin)); } results.add(block); } else { if (LOG.isDebugEnabled()) { LOG.debug(MessageFormat.format( "Filter parquet block: {0} ({1}+{2})", //$NON-NLS-1$ path, begin, end - begin)); } } } return results; } private RecordReader<Object> createRecordReader(PageReadStore store) { assert materializer != null; this.currentRecordReader = columnIo.getRecordReader(store, materializer); this.rowRest = store.getRowCount(); return currentRecordReader; } @Override public void close() throws IOException { if (fileReader != null) { fileReader.close(); } } }
hive-project/asakusa-hive-core/src/main/java/com/asakusafw/directio/hive/parquet/ParquetFileInput.java
/** * Copyright 2011-2017 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asakusafw.directio.hive.parquet; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import com.asakusafw.directio.hive.serde.DataModelDescriptor; import com.asakusafw.directio.hive.serde.DataModelDriver; import com.asakusafw.directio.hive.serde.DataModelMapping; import com.asakusafw.runtime.directio.Counter; import com.asakusafw.runtime.io.ModelInput; import parquet.column.page.PageReadStore; import parquet.hadoop.ParquetFileReader; import parquet.hadoop.metadata.BlockMetaData; import parquet.hadoop.metadata.ColumnChunkMetaData; import parquet.hadoop.metadata.ParquetMetadata; import parquet.io.ColumnIOFactory; import parquet.io.MessageColumnIO; import parquet.io.RecordReader; /** * An implementation of {@link ModelInput} for reading Parquet files. * @param <T> the data model type * @since 0.7.0 */ public class ParquetFileInput<T> implements ModelInput<T> { static final Log LOG = LogFactory.getLog(ParquetFileInput.class); private final DataModelDescriptor descriptor; private final DataModelMapping mappingConfiguration; private final Configuration hadoopConfiguration; private final Path path; private final long offset; private final long fragmentSize; private final Counter counter; private long rowRest = -1; private ParquetFileReader fileReader; private DataModelMaterializer materializer; private RecordReader<Object> currentRecordReader; private MessageColumnIO columnIo; private double averageBytesPerRecord; private double lastBytes; /** * Creates a new instance. * @param descriptor the target data model descriptor * @param mappingConfiguration the {@link DataModelDriver} configuration * @param hadoopConfiguration the hadoop configuration * @param path the path to the target file * @param offset starting stream offset * @param fragmentSize suggested fragment bytes count * @param counter the current counter */ public ParquetFileInput( DataModelDescriptor descriptor, DataModelMapping mappingConfiguration, Configuration hadoopConfiguration, Path path, long offset, long fragmentSize, Counter counter) { this.descriptor = descriptor; this.mappingConfiguration = mappingConfiguration; this.hadoopConfiguration = hadoopConfiguration; this.path = path; this.offset = offset; this.fragmentSize = fragmentSize; this.counter = counter; } @Override public boolean readTo(T model) throws IOException { RecordReader<Object> reader = prepareReader(model); if (reader == null) { return false; } rowRest--; reader.read(); advanceCounter(); return true; } private void advanceCounter() { double last = lastBytes; double next = last + averageBytesPerRecord; long delta = (long) (next - last); if (delta >= 0L) { counter.add(delta); } lastBytes = next; } private RecordReader<Object> prepareReader(T model) throws IOException { while (rowRest <= 0) { PageReadStore next = fetchRowGroup(); if (next == null) { return null; } currentRecordReader = createRecordReader(next); } assert currentRecordReader != null; assert materializer != null; materializer.setNextRecord(model); return currentRecordReader; } private PageReadStore fetchRowGroup() throws IOException { if (fileReader == null) { if (LOG.isInfoEnabled()) { LOG.info(MessageFormat.format( Messages.getString("ParquetFileInput.infoLoadMetadata"), //$NON-NLS-1$ descriptor.getDataModelClass().getSimpleName(), path)); } ParquetMetadata footer = ParquetFileReader.readFooter(hadoopConfiguration, path); List<BlockMetaData> blocks = filterBlocks(footer.getBlocks()); if (blocks.isEmpty()) { return null; } long totalRecords = computeTotalRecords(blocks); this.averageBytesPerRecord = (double) fragmentSize / totalRecords; if (LOG.isInfoEnabled()) { LOG.info(MessageFormat.format( Messages.getString("ParquetFileInput.infoLoadContents"), //$NON-NLS-1$ descriptor.getDataModelClass().getSimpleName(), path, offset, fragmentSize)); } this.fileReader = new ParquetFileReader( hadoopConfiguration, path, blocks, footer.getFileMetaData().getSchema().getColumns()); this.materializer = new DataModelMaterializer( descriptor, footer.getFileMetaData().getSchema(), mappingConfiguration); this.columnIo = new ColumnIOFactory().getColumnIO( materializer.getMaterializeSchema(), footer.getFileMetaData().getSchema()); } return fileReader.readNextRowGroup(); } private long computeTotalRecords(List<BlockMetaData> blocks) { long result = 0L; for (BlockMetaData block : blocks) { result += block.getTotalByteSize(); } return result; } private List<BlockMetaData> filterBlocks(List<BlockMetaData> blocks) { if (fragmentSize < 0L) { return blocks; } if (LOG.isDebugEnabled()) { LOG.debug(MessageFormat.format( "Detecting target parquet blocks: {0} ({1}+{2})", //$NON-NLS-1$ path, this.offset, this.fragmentSize)); } List<BlockMetaData> results = new ArrayList<>(); for (BlockMetaData block : blocks) { List<ColumnChunkMetaData> columns = block.getColumns(); if (columns.isEmpty()) { return Collections.emptyList(); } long begin = Long.MAX_VALUE; long end = -1L; for (ColumnChunkMetaData column : block.getColumns()) { long off = column.getFirstDataPageOffset(); long len = column.getTotalSize(); begin = Math.min(begin, off); end = Math.max(end, off + len); } assert begin >= 0L; assert end >= 0L; if (this.offset <= begin && end <= this.offset + this.fragmentSize && block.getRowCount() != 0) { if (LOG.isDebugEnabled()) { LOG.debug(MessageFormat.format( "Detected a target parquet block: {0} ({1}+{2})", //$NON-NLS-1$ path, begin, end - begin)); } results.add(block); } else { if (LOG.isDebugEnabled()) { LOG.debug(MessageFormat.format( "Filter parquet block: {0} ({1}+{2})", //$NON-NLS-1$ path, begin, end - begin)); } } } return results; } private RecordReader<Object> createRecordReader(PageReadStore store) { assert materializer != null; this.currentRecordReader = columnIo.getRecordReader(store, materializer); this.rowRest = store.getRowCount(); return currentRecordReader; } @Override public void close() throws IOException { if (fileReader != null) { fileReader.close(); } } }
Revise for PARQUET-251.
hive-project/asakusa-hive-core/src/main/java/com/asakusafw/directio/hive/parquet/ParquetFileInput.java
Revise for PARQUET-251.
<ide><path>ive-project/asakusa-hive-core/src/main/java/com/asakusafw/directio/hive/parquet/ParquetFileInput.java <ide> package com.asakusafw.directio.hive.parquet; <ide> <ide> import java.io.IOException; <add>import java.lang.reflect.Constructor; <ide> import java.text.MessageFormat; <ide> import java.util.ArrayList; <ide> import java.util.Collections; <ide> import parquet.hadoop.ParquetFileReader; <ide> import parquet.hadoop.metadata.BlockMetaData; <ide> import parquet.hadoop.metadata.ColumnChunkMetaData; <add>import parquet.hadoop.metadata.FileMetaData; <ide> import parquet.hadoop.metadata.ParquetMetadata; <ide> import parquet.io.ColumnIOFactory; <ide> import parquet.io.MessageColumnIO; <ide> public class ParquetFileInput<T> implements ModelInput<T> { <ide> <ide> static final Log LOG = LogFactory.getLog(ParquetFileInput.class); <add> <add> private static final Constructor<ParquetFileReader> FILE_READER_NEWER_CTOR; <add> static { <add> LOG.debug("loading newer ParquetFileReader.<init>"); <add> Constructor<ParquetFileReader> ctor = null; <add> try { <add> ctor = ParquetFileReader.class.getConstructor( <add> Configuration.class, <add> FileMetaData.class, <add> Path.class, <add> List.class, <add> List.class); <add> } catch (ReflectiveOperationException e) { <add> LOG.debug("cannot load newer ParquetFileReader.<init>", e); <add> } <add> FILE_READER_NEWER_CTOR = ctor; <add> } <ide> <ide> private final DataModelDescriptor descriptor; <ide> <ide> offset, <ide> fragmentSize)); <ide> } <del> this.fileReader = new ParquetFileReader( <del> hadoopConfiguration, <del> path, <del> blocks, <del> footer.getFileMetaData().getSchema().getColumns()); <add> this.fileReader = createFileReader(footer, blocks); <ide> this.materializer = new DataModelMaterializer( <ide> descriptor, <ide> footer.getFileMetaData().getSchema(), <ide> return fileReader.readNextRowGroup(); <ide> } <ide> <del> private long computeTotalRecords(List<BlockMetaData> blocks) { <add> private ParquetFileReader createFileReader(ParquetMetadata meta, List<BlockMetaData> blocks) throws IOException { <add> FileMetaData fileMetaData = meta.getFileMetaData(); <add> if (FILE_READER_NEWER_CTOR != null) { <add> try { <add> return FILE_READER_NEWER_CTOR.newInstance( <add> hadoopConfiguration, <add> fileMetaData, <add> path, <add> blocks, <add> fileMetaData.getSchema().getColumns()); <add> } catch (ReflectiveOperationException | IllegalArgumentException | SecurityException e) { <add> LOG.debug("failed ParquetFileReader.<init>", e); <add> } <add> } <add> return new ParquetFileReader( <add> hadoopConfiguration, <add> path, <add> blocks, <add> fileMetaData.getSchema().getColumns()); <add> } <add> <add> private static long computeTotalRecords(List<BlockMetaData> blocks) { <ide> long result = 0L; <ide> for (BlockMetaData block : blocks) { <ide> result += block.getTotalByteSize();
Java
apache-2.0
edaab5124ef8cb1ea2dbedaffd66f30416d1a604
0
salguarnieri/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,ibinti/intellij-community,ibinti/intellij-community,semonte/intellij-community,ibinti/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,da1z/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,signed/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,retomerz/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,fitermay/intellij-community,signed/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,xfournet/intellij-community,hurricup/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,retomerz/intellij-community,da1z/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,da1z/intellij-community,apixandru/intellij-community,allotria/intellij-community,FHannes/intellij-community,retomerz/intellij-community,signed/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,semonte/intellij-community,hurricup/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,da1z/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,semonte/intellij-community,hurricup/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,signed/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,asedunov/intellij-community,FHannes/intellij-community,apixandru/intellij-community,retomerz/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,signed/intellij-community,signed/intellij-community,retomerz/intellij-community,signed/intellij-community,xfournet/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,fitermay/intellij-community,xfournet/intellij-community,apixandru/intellij-community,da1z/intellij-community,da1z/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,allotria/intellij-community,da1z/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,retomerz/intellij-community,da1z/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,apixandru/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,allotria/intellij-community,allotria/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,signed/intellij-community,ibinti/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,apixandru/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,semonte/intellij-community,apixandru/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,xfournet/intellij-community,semonte/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,allotria/intellij-community,FHannes/intellij-community,FHannes/intellij-community,signed/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,semonte/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,asedunov/intellij-community,hurricup/intellij-community,apixandru/intellij-community,signed/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,signed/intellij-community,FHannes/intellij-community,allotria/intellij-community,allotria/intellij-community,fitermay/intellij-community,asedunov/intellij-community,hurricup/intellij-community,fitermay/intellij-community,hurricup/intellij-community,semonte/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.impl.source; import com.intellij.openapi.util.SimpleModificationTracker; import com.intellij.psi.*; import com.intellij.psi.augment.PsiAugmentProvider; import com.intellij.psi.impl.PsiClassImplUtil; import com.intellij.psi.impl.PsiImplUtil; import com.intellij.psi.impl.light.LightMethod; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.util.ArrayUtil; import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; import java.util.Map; import static com.intellij.psi.util.PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT; public class ClassInnerStuffCache { private final PsiExtensibleClass myClass; private final SimpleModificationTracker myTracker; public ClassInnerStuffCache(@NotNull PsiExtensibleClass aClass) { myClass = aClass; myTracker = new SimpleModificationTracker(); } @NotNull public PsiMethod[] getConstructors() { return CachedValuesManager.getCachedValue(myClass, new CachedValueProvider<PsiMethod[]>() { @Nullable @Override public Result<PsiMethod[]> compute() { return Result.create(PsiImplUtil.getConstructors(myClass), OUT_OF_CODE_BLOCK_MODIFICATION_COUNT, myTracker); } }); } @NotNull public PsiField[] getFields() { return CachedValuesManager.getCachedValue(myClass, new CachedValueProvider<PsiField[]>() { @Nullable @Override public Result<PsiField[]> compute() { return Result.create(getAllFields(), OUT_OF_CODE_BLOCK_MODIFICATION_COUNT, myTracker); } }); } @NotNull public PsiMethod[] getMethods() { return CachedValuesManager.getCachedValue(myClass, new CachedValueProvider<PsiMethod[]>() { @Nullable @Override public Result<PsiMethod[]> compute() { return Result.create(getAllMethods(), OUT_OF_CODE_BLOCK_MODIFICATION_COUNT, myTracker); } }); } @NotNull public PsiClass[] getInnerClasses() { return CachedValuesManager.getCachedValue(myClass, new CachedValueProvider<PsiClass[]>() { @Nullable @Override public Result<PsiClass[]> compute() { return Result.create(getAllInnerClasses(), OUT_OF_CODE_BLOCK_MODIFICATION_COUNT, myTracker); } }); } @Nullable public PsiField findFieldByName(String name, boolean checkBases) { if (checkBases) { return PsiClassImplUtil.findFieldByName(myClass, name, true); } return CachedValuesManager.getCachedValue(myClass, new CachedValueProvider<Map<String, PsiField>>() { @Nullable @Override public Result<Map<String, PsiField>> compute() { return Result.create(getFieldsMap(), OUT_OF_CODE_BLOCK_MODIFICATION_COUNT, myTracker); } }).get(name); } @NotNull public PsiMethod[] findMethodsByName(String name, boolean checkBases) { if (checkBases) { return PsiClassImplUtil.findMethodsByName(myClass, name, true); } PsiMethod[] methods = CachedValuesManager.getCachedValue(myClass, new CachedValueProvider<Map<String, PsiMethod[]>>() { @Nullable @Override public Result<Map<String, PsiMethod[]>> compute() { return Result.create(getMethodsMap(), OUT_OF_CODE_BLOCK_MODIFICATION_COUNT, myTracker); } }).get(name); return methods == null ? PsiMethod.EMPTY_ARRAY : methods; } @Nullable public PsiClass findInnerClassByName(final String name, final boolean checkBases) { if (checkBases) { return PsiClassImplUtil.findInnerByName(myClass, name, true); } else { return CachedValuesManager.getCachedValue(myClass, new CachedValueProvider<Map<String, PsiClass>>() { @Nullable @Override public Result<Map<String, PsiClass>> compute() { return Result.create(getInnerClassesMap(), OUT_OF_CODE_BLOCK_MODIFICATION_COUNT, myTracker); } }).get(name); } } @Nullable public PsiMethod getValuesMethod() { return !myClass.isEnum() || myClass.getName() == null ? null : CachedValuesManager.getCachedValue(myClass, new CachedValueProvider<PsiMethod>() { @Nullable @Override public Result<PsiMethod> compute() { String text = "public static " + myClass.getName() + "[] values() { }"; return new Result<PsiMethod>(getSyntheticMethod(text), OUT_OF_CODE_BLOCK_MODIFICATION_COUNT, myTracker); } }); } @Nullable public PsiMethod getValueOfMethod() { return !myClass.isEnum() || myClass.getName() == null ? null : CachedValuesManager.getCachedValue(myClass, new CachedValueProvider<PsiMethod>() { @Nullable @Override public Result<PsiMethod> compute() { String text = "public static " + myClass.getName() + " valueOf(java.lang.String name) throws java.lang.IllegalArgumentException { }"; return new Result<PsiMethod>(getSyntheticMethod(text), OUT_OF_CODE_BLOCK_MODIFICATION_COUNT, myTracker); } }); } @NotNull private PsiField[] getAllFields() { List<PsiField> own = myClass.getOwnFields(); List<PsiField> ext = PsiAugmentProvider.collectAugments(myClass, PsiField.class); return ArrayUtil.mergeCollections(own, ext, PsiField.ARRAY_FACTORY); } @NotNull private PsiMethod[] getAllMethods() { List<PsiMethod> own = myClass.getOwnMethods(); List<PsiMethod> ext = PsiAugmentProvider.collectAugments(myClass, PsiMethod.class); return ArrayUtil.mergeCollections(own, ext, PsiMethod.ARRAY_FACTORY); } @NotNull private PsiClass[] getAllInnerClasses() { List<PsiClass> own = myClass.getOwnInnerClasses(); List<PsiClass> ext = PsiAugmentProvider.collectAugments(myClass, PsiClass.class); return ArrayUtil.mergeCollections(own, ext, PsiClass.ARRAY_FACTORY); } @NotNull private Map<String, PsiField> getFieldsMap() { PsiField[] fields = getFields(); if (fields.length == 0) return Collections.emptyMap(); Map<String, PsiField> cachedFields = new THashMap<String, PsiField>(); for (PsiField field : fields) { String name = field.getName(); if (!(field instanceof ExternallyDefinedPsiElement) || !cachedFields.containsKey(name)) { cachedFields.put(name, field); } } return cachedFields; } @NotNull private Map<String, PsiMethod[]> getMethodsMap() { PsiMethod[] methods = getMethods(); if (methods.length == 0) return Collections.emptyMap(); Map<String, List<PsiMethod>> collectedMethods = ContainerUtil.newHashMap(); for (PsiMethod method : methods) { List<PsiMethod> list = collectedMethods.get(method.getName()); if (list == null) { collectedMethods.put(method.getName(), list = ContainerUtil.newSmartList()); } list.add(method); } Map<String, PsiMethod[]> cachedMethods = ContainerUtil.newTroveMap(); for (Map.Entry<String, List<PsiMethod>> entry : collectedMethods.entrySet()) { List<PsiMethod> list = entry.getValue(); cachedMethods.put(entry.getKey(), list.toArray(new PsiMethod[list.size()])); } return cachedMethods; } @NotNull private Map<String, PsiClass> getInnerClassesMap() { PsiClass[] classes = getInnerClasses(); if (classes.length == 0) return Collections.emptyMap(); Map<String, PsiClass> cachedInners = new THashMap<String, PsiClass>(); for (PsiClass psiClass : classes) { String name = psiClass.getName(); if (!(psiClass instanceof ExternallyDefinedPsiElement) || !cachedInners.containsKey(name)) { cachedInners.put(name, psiClass); } } return cachedInners; } private PsiMethod getSyntheticMethod(String text) { PsiElementFactory factory = JavaPsiFacade.getInstance(myClass.getProject()).getElementFactory(); PsiMethod method = factory.createMethodFromText(text, myClass); return new LightMethod(myClass.getManager(), method, myClass) { @Override public int getTextOffset() { return myClass.getTextOffset(); } }; } public void dropCaches() { myTracker.incModificationCount(); } }
java/java-psi-impl/src/com/intellij/psi/impl/source/ClassInnerStuffCache.java
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.impl.source; import com.intellij.openapi.util.SimpleModificationTracker; import com.intellij.psi.*; import com.intellij.psi.augment.PsiAugmentProvider; import com.intellij.psi.impl.PsiClassImplUtil; import com.intellij.psi.impl.PsiImplUtil; import com.intellij.psi.impl.light.LightMethod; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.util.ArrayUtil; import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; import java.util.Map; import static com.intellij.psi.util.PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT; public class ClassInnerStuffCache { private final PsiExtensibleClass myClass; private final SimpleModificationTracker myTracker; public ClassInnerStuffCache(@NotNull PsiExtensibleClass aClass) { myClass = aClass; myTracker = new SimpleModificationTracker(); } @NotNull public PsiMethod[] getConstructors() { return CachedValuesManager.getCachedValue(myClass, new CachedValueProvider<PsiMethod[]>() { @Nullable @Override public Result<PsiMethod[]> compute() { return Result.create(PsiImplUtil.getConstructors(myClass), OUT_OF_CODE_BLOCK_MODIFICATION_COUNT, myTracker); } }); } @NotNull public PsiField[] getFields() { return CachedValuesManager.getCachedValue(myClass, new CachedValueProvider<PsiField[]>() { @Nullable @Override public Result<PsiField[]> compute() { return Result.create(getAllFields(), OUT_OF_CODE_BLOCK_MODIFICATION_COUNT, myTracker); } }); } @NotNull public PsiMethod[] getMethods() { return CachedValuesManager.getCachedValue(myClass, new CachedValueProvider<PsiMethod[]>() { @Nullable @Override public Result<PsiMethod[]> compute() { return Result.create(getAllMethods(), OUT_OF_CODE_BLOCK_MODIFICATION_COUNT, myTracker); } }); } @NotNull public PsiClass[] getInnerClasses() { return CachedValuesManager.getCachedValue(myClass, new CachedValueProvider<PsiClass[]>() { @Nullable @Override public Result<PsiClass[]> compute() { return Result.create(getAllInnerClasses(), OUT_OF_CODE_BLOCK_MODIFICATION_COUNT, myTracker); } }); } @Nullable public PsiField findFieldByName(String name, boolean checkBases) { if (checkBases) { return PsiClassImplUtil.findFieldByName(myClass, name, true); } return CachedValuesManager.getCachedValue(myClass, new CachedValueProvider<Map<String, PsiField>>() { @Nullable @Override public Result<Map<String, PsiField>> compute() { return Result.create(getFieldsMap(), OUT_OF_CODE_BLOCK_MODIFICATION_COUNT, myTracker); } }).get(name); } @NotNull public PsiMethod[] findMethodsByName(String name, boolean checkBases) { if (checkBases) { return PsiClassImplUtil.findMethodsByName(myClass, name, true); } PsiMethod[] methods = CachedValuesManager.getCachedValue(myClass, new CachedValueProvider<Map<String, PsiMethod[]>>() { @Nullable @Override public Result<Map<String, PsiMethod[]>> compute() { return Result.create(getMethodsMap(), OUT_OF_CODE_BLOCK_MODIFICATION_COUNT, myTracker); } }).get(name); return methods == null ? PsiMethod.EMPTY_ARRAY : methods; } @Nullable public PsiClass findInnerClassByName(final String name, final boolean checkBases) { if (checkBases) { return PsiClassImplUtil.findInnerByName(myClass, name, true); } else { return CachedValuesManager.getCachedValue(myClass, new CachedValueProvider<Map<String, PsiClass>>() { @Nullable @Override public Result<Map<String, PsiClass>> compute() { return Result.create(getInnerClassesMap(), OUT_OF_CODE_BLOCK_MODIFICATION_COUNT, myTracker); } }).get(name); } } @Nullable public PsiMethod getValuesMethod() { return !myClass.isEnum() || myClass.getName() == null ? null : CachedValuesManager.getCachedValue(myClass, new CachedValueProvider<PsiMethod>() { @Nullable @Override public Result<PsiMethod> compute() { String text = "public static " + myClass.getName() + "[] values() { }"; return new Result<PsiMethod>(getSyntheticMethod(text), OUT_OF_CODE_BLOCK_MODIFICATION_COUNT, myTracker); } }); } @Nullable public PsiMethod getValueOfMethod() { return !myClass.isEnum() || myClass.getName() == null ? null : CachedValuesManager.getCachedValue(myClass, new CachedValueProvider<PsiMethod>() { @Nullable @Override public Result<PsiMethod> compute() { String text = "public static " + myClass.getName() + " valueOf(java.lang.String name) throws java.lang.IllegalArgumentException { }"; return new Result<PsiMethod>(getSyntheticMethod(text), OUT_OF_CODE_BLOCK_MODIFICATION_COUNT, myTracker); } }); } @NotNull private PsiField[] getAllFields() { List<PsiField> own = myClass.getOwnFields(); List<PsiField> ext = PsiAugmentProvider.collectAugments(myClass, PsiField.class); return ArrayUtil.mergeCollections(own, ext, PsiField.ARRAY_FACTORY); } @NotNull private PsiMethod[] getAllMethods() { List<PsiMethod> own = myClass.getOwnMethods(); List<PsiMethod> ext = PsiAugmentProvider.collectAugments(myClass, PsiMethod.class); return ArrayUtil.mergeCollections(own, ext, PsiMethod.ARRAY_FACTORY); } @NotNull private PsiClass[] getAllInnerClasses() { List<PsiClass> own = myClass.getOwnInnerClasses(); List<PsiClass> ext = PsiAugmentProvider.collectAugments(myClass, PsiClass.class); return ArrayUtil.mergeCollections(own, ext, PsiClass.ARRAY_FACTORY); } @NotNull private Map<String, PsiField> getFieldsMap() { PsiField[] fields = getFields(); if (fields.length == 0) return Collections.emptyMap(); Map<String, PsiField> cachedFields = new THashMap<String, PsiField>(); for (PsiField field : fields) { String name = field.getName(); if (!(field instanceof ExternallyDefinedPsiElement) || !cachedFields.containsKey(name)) { cachedFields.put(name, field); } } return cachedFields; } @NotNull private Map<String, PsiMethod[]> getMethodsMap() { PsiMethod[] methods = getMethods(); if (methods.length == 0) return Collections.emptyMap(); Map<String, List<PsiMethod>> collectedMethods = ContainerUtil.newHashMap(); for (PsiMethod method : methods) { List<PsiMethod> list = collectedMethods.get(method.getName()); if (list == null) { collectedMethods.put(method.getName(), list = ContainerUtil.newSmartList()); } list.add(method); } Map<String, PsiMethod[]> cachedMethods = ContainerUtil.newTroveMap(); for (Map.Entry<String, List<PsiMethod>> entry : collectedMethods.entrySet()) { List<PsiMethod> list = entry.getValue(); cachedMethods.put(entry.getKey(), list.toArray(new PsiMethod[list.size()])); } return cachedMethods; } @NotNull private Map<String, PsiClass> getInnerClassesMap() { PsiClass[] classes = getInnerClasses(); if (classes.length == 0) return Collections.emptyMap(); Map<String, PsiClass> cachedInners = new THashMap<String, PsiClass>(); for (PsiClass psiClass : classes) { String name = psiClass.getName(); if (!(psiClass instanceof ExternallyDefinedPsiElement) || !cachedInners.containsKey(name)) { cachedInners.put(name, psiClass); } } return cachedInners; } private PsiMethod getSyntheticMethod(String text) { PsiElementFactory factory = JavaPsiFacade.getInstance(myClass.getProject()).getElementFactory(); LightMethod method = new LightMethod(myClass.getManager(), factory.createMethodFromText(text, myClass), myClass); method.setNavigationElement(myClass); return method; } public void dropCaches() { myTracker.incModificationCount(); } }
revert: [java] navigation to synthetic methods
java/java-psi-impl/src/com/intellij/psi/impl/source/ClassInnerStuffCache.java
revert: [java] navigation to synthetic methods
<ide><path>ava/java-psi-impl/src/com/intellij/psi/impl/source/ClassInnerStuffCache.java <ide> <ide> private PsiMethod getSyntheticMethod(String text) { <ide> PsiElementFactory factory = JavaPsiFacade.getInstance(myClass.getProject()).getElementFactory(); <del> LightMethod method = new LightMethod(myClass.getManager(), factory.createMethodFromText(text, myClass), myClass); <del> method.setNavigationElement(myClass); <del> return method; <add> PsiMethod method = factory.createMethodFromText(text, myClass); <add> return new LightMethod(myClass.getManager(), method, myClass) { <add> @Override <add> public int getTextOffset() { <add> return myClass.getTextOffset(); <add> } <add> }; <ide> } <ide> <ide> public void dropCaches() {
JavaScript
mit
a911da3c1e635a90d3869ce8f8ef1129b78417f2
0
tonysuaus/projectz,tonysuaus/projectz
$(document).ready(function() { Number.prototype.number_with_delimiter = function(delimiter) { var number = this + '', delimiter = delimiter || ','; var split = number.split('.'); split[0] = split[0].replace( /(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + delimiter ); return split.join('.'); }; $('.search').on('click', function() { $.post( '/grant_gateway/search', $('#search-form').serialize(), function(data) { var total_value = 0; $('.results').empty() for (var i = 0; i < data.length; i++) { $('.results').append("<a href='" + data[i].link + "' class='media-links'><div class='media'><div class='media-body'><h5 class='media-heading'>" + data[i].name + "</h5><i class='fa fa-arrow-circle-o-right'></i><br/><p>" + data[i].description + "</p></div></div></a>") if (data[i].amount > 0) { total_value += parseInt(data[i].amount) }; }; if (total_value > 0) { $('.total-value').empty() $('.total-value').append("$" + total_value.number_with_delimiter()) }; if (data.length == 0) { $('.results').append("<p class='no-results'>No Results Found</p>") }; }); }); });
app/assets/javascripts/form.js
$(document).ready(function() { $('.search').on('click', function() { $.post( '/grant_gateway/search', $('#search-form').serialize(), function(data) { var total_value = 0; $('.results').empty() for (var i = 0; i < data.length; i++) { $('.results').append("<a href='" + data[i].link + "' class='media-links'><div class='media'><div class='media-body'><h5 class='media-heading'>" + data[i].name + "</h5><i class='fa fa-arrow-circle-o-right'></i><br/><p>" + data[i].description + "</p></div></div></a>") if (data[i].amount > 0) { total_value += parseInt(data[i].amount) }; }; console.log(total_value) if (total_value > 0) { $('.total-value').empty() $('.total-value').append("$" + total_value) }; if (data.length == 0) { $('.results').append("<p class='no-results'>No Results Found</p>") }; }); }); });
Add delimiter to result value
app/assets/javascripts/form.js
Add delimiter to result value
<ide><path>pp/assets/javascripts/form.js <ide> $(document).ready(function() { <add> <add> Number.prototype.number_with_delimiter = function(delimiter) { <add> var number = this + '', delimiter = delimiter || ','; <add> var split = number.split('.'); <add> split[0] = split[0].replace( <add> /(\d)(?=(\d\d\d)+(?!\d))/g, <add> '$1' + delimiter <add> ); <add> return split.join('.'); <add> }; <ide> <ide> $('.search').on('click', function() { <ide> $.post( '/grant_gateway/search', $('#search-form').serialize(), function(data) { <ide> total_value += parseInt(data[i].amount) <ide> }; <ide> }; <del> console.log(total_value) <add> <ide> if (total_value > 0) { <ide> $('.total-value').empty() <del> $('.total-value').append("$" + total_value) <add> $('.total-value').append("$" + total_value.number_with_delimiter()) <ide> }; <ide> if (data.length == 0) { <ide> $('.results').append("<p class='no-results'>No Results Found</p>")
Java
mit
85e4edccf578142bef7a08e954fb8ddc1b4f111a
0
yegor256/takes,simonjenga/takes,yegor256/takes,simonjenga/takes
/* * The MIT License (MIT) * * Copyright (c) 2014-2019 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.takes.facets.fork; import lombok.EqualsAndHashCode; import org.cactoos.scalar.EqualsNullable; import org.cactoos.scalar.Ternary; import org.cactoos.text.Lowered; import org.takes.Response; import org.takes.Take; import org.takes.misc.Opt; import org.takes.rq.RqHeaders; /** * Fork by host name. * * <p>Use this class in combination with {@link TkFork}, * for example: * * <pre> Take take = new TkFork( * new FkHost("www.example.com", new TkText("home")), * new FkHost("doc.example.com", new TkText("doc is here")) * );</pre> * * <p>The class is immutable and thread-safe. * * @see TkFork * @since 0.32 */ @EqualsAndHashCode(callSuper = true) public final class FkHost extends FkWrap { /** * Ctor. * @param host Host * @param take Take to use */ public FkHost(final String host, final Take take) { super(FkHost.fork(host, take)); } /** * Make fork. * @param host Host * @param take Take to use * @return Fork */ private static Fork fork(final String host, final Take take) { return req -> { final String hst = new RqHeaders.Smart( new RqHeaders.Base(req) ).single("host"); return new Ternary<Opt<Response>>( new EqualsNullable( new Lowered(host), new Lowered(hst) ), new Opt.Single<>(take.act(req)), new Opt.Empty<>() ).value(); }; } }
src/main/java/org/takes/facets/fork/FkHost.java
/* * The MIT License (MIT) * * Copyright (c) 2014-2019 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.takes.facets.fork; import lombok.EqualsAndHashCode; import org.cactoos.Text; import org.cactoos.text.Lowered; import org.cactoos.text.UncheckedText; import org.takes.Request; import org.takes.Response; import org.takes.Take; import org.takes.misc.Opt; import org.takes.rq.RqHeaders; /** * Fork by host name. * * <p>Use this class in combination with {@link TkFork}, * for example: * * <pre> Take take = new TkFork( * new FkHost("www.example.com", new TkText("home")), * new FkHost("doc.example.com", new TkText("doc is here")) * );</pre> * * <p>The class is immutable and thread-safe. * * @see TkFork * @since 0.32 * @todo #998:30min Use {@link org.cactoos.scalar.Ternary} scalar here for * conditionally evaluated result. Please refere to * https://github.com/yegor256/cactoos/blob/master/src/main/java/org/cactoos/ * scalar/Ternary.java class for javadoc on how to use this scalar in an * elegant way. */ @EqualsAndHashCode(callSuper = true) public final class FkHost extends FkWrap { /** * Ctor. * @param host Host * @param take Take to use */ public FkHost(final String host, final Take take) { super(FkHost.fork(host, take)); } /** * Make fork. * @param host Host * @param take Take to use * @return Fork */ private static Fork fork(final String host, final Take take) { // @checkstyle AnonInnerLengthCheck (50 lines) return new Fork() { @Override public Opt<Response> route(final Request req) throws Exception { final String hst = new RqHeaders.Smart( new RqHeaders.Base(req) ).single("host"); final Opt<Response> rsp; final Text lowhost = new UncheckedText(new Lowered(host)); final Text lowhst = new UncheckedText(new Lowered(hst)); if (lowhost.asString().equals(lowhst.asString())) { rsp = new Opt.Single<>(take.act(req)); } else { rsp = new Opt.Empty<>(); } return rsp; } }; } }
(#1019) Simplified conditional statement with EO way
src/main/java/org/takes/facets/fork/FkHost.java
(#1019) Simplified conditional statement with EO way
<ide><path>rc/main/java/org/takes/facets/fork/FkHost.java <ide> package org.takes.facets.fork; <ide> <ide> import lombok.EqualsAndHashCode; <del>import org.cactoos.Text; <add>import org.cactoos.scalar.EqualsNullable; <add>import org.cactoos.scalar.Ternary; <ide> import org.cactoos.text.Lowered; <del>import org.cactoos.text.UncheckedText; <del>import org.takes.Request; <ide> import org.takes.Response; <ide> import org.takes.Take; <ide> import org.takes.misc.Opt; <ide> * <ide> * @see TkFork <ide> * @since 0.32 <del> * @todo #998:30min Use {@link org.cactoos.scalar.Ternary} scalar here for <del> * conditionally evaluated result. Please refere to <del> * https://github.com/yegor256/cactoos/blob/master/src/main/java/org/cactoos/ <del> * scalar/Ternary.java class for javadoc on how to use this scalar in an <del> * elegant way. <ide> */ <ide> @EqualsAndHashCode(callSuper = true) <ide> public final class FkHost extends FkWrap { <ide> * @return Fork <ide> */ <ide> private static Fork fork(final String host, final Take take) { <del> // @checkstyle AnonInnerLengthCheck (50 lines) <del> return new Fork() { <del> @Override <del> public Opt<Response> route(final Request req) throws Exception { <del> final String hst = new RqHeaders.Smart( <del> new RqHeaders.Base(req) <del> ).single("host"); <del> final Opt<Response> rsp; <del> final Text lowhost = new UncheckedText(new Lowered(host)); <del> final Text lowhst = new UncheckedText(new Lowered(hst)); <del> if (lowhost.asString().equals(lowhst.asString())) { <del> rsp = new Opt.Single<>(take.act(req)); <del> } else { <del> rsp = new Opt.Empty<>(); <del> } <del> return rsp; <del> } <add> return req -> { <add> final String hst = new RqHeaders.Smart( <add> new RqHeaders.Base(req) <add> ).single("host"); <add> return new Ternary<Opt<Response>>( <add> new EqualsNullable( <add> new Lowered(host), new Lowered(hst) <add> ), <add> new Opt.Single<>(take.act(req)), <add> new Opt.Empty<>() <add> ).value(); <ide> }; <ide> } <ide>
JavaScript
mit
ae2448619fec985fe9d72b26b9db6a328402a876
0
scopyleft/hubot-mood
// Description: // Records moods over time. // // Dependencies: // redis // // Configuration: // HUBOT_MOOD_REDIS_URL: url to redis storage backend // // Commands: // mood set "<sunny|cloudy|rainy|stormy>" // mood of <(nickname)|me> // mood today // mood yesterday // mood week of <(nickname)|me> // mood month of <(nickname)|me> // // Author: // n1k0 /*global module process*/ var MoodEngine = require('../lib') , dateUtil = require('../lib/date-util') , util = require('util') , Url = require('url') , Redis = require('redis') , format = util.format; function nickname(msg, match) { if (!match || match.toLowerCase().trim() === "me") { return msg.message.user && msg.message.user.name || "unknown"; } return match; } module.exports = function(robot) { var info = Url.parse(process.env.HUBOT_MOOD_REDIS_URL || 'redis://localhost:6379') , client = Redis.createClient(info.port, info.hostname) , engine = new MoodEngine(client); if (info.auth) { client.auth(info.auth.split(":")[1]); } client.on("error", function(err) { robot.logger.error(err); }); client.on("connect", function() { robot.logger.debug("Successfully connected to Redis from mood script"); }); engine.on("info", function(msg) { robot.logger.info(msg); }); robot.respond(/mood set (\w+)$/i, function(msg) { var user = nickname(msg) , mood = msg.match[1].toLowerCase(); engine.store({ user: user, mood: mood }, function(err, stored) { if (err) return msg.send(err); msg.send(format('Recorded entry: %s', stored)); }); }); robot.respond(/mood (today|yesterday)$/i, function(msg) { var day = msg.match[1].toLowerCase() , date = day === "today" ? dateUtil.today() : dateUtil.yesterday(); engine.query({ date: date }, function(err, moods) { if (err) return msg.send(err); if (!moods || !moods.length) { return msg.send(format('No mood entry for %s %s.', msg.match[1], day)); } moods.forEach(function(mood) { msg.send('- ' + mood.toString()); }); }); }); robot.respond(/mood (month|week) (of|for) (.*)$/i, function(msg) { var user = nickname(msg, msg.match[2]) , since = msg.match[1].toLowerCase() === "month" ? 30 : 7; engine.graph({ user: user, since: since }, function(err, graph) { if (err) return msg.send(err); msg.send(graph); }); }); robot.respond(/mood (of|for) (.*)$/i, function(msg) { var user = nickname(msg, msg.match[2]) , date = dateUtil.today(); engine.query({date: date, user: user}, function(err, moods) { if (err) return msg.send(err); if (!moods || !moods[0]) { return msg.send(format('%s has not set a mood today, yet', user)); } msg.send(moods[0].toString()); }); }); };
scripts/mood.js
// Description: // Records moods over time. // // Dependencies: // redis // // Configuration: // HUBOT_MOOD_REDIS_URL: url to redis storage backend // // Commands: // mood set "<sunny|cloudy|rainy|stormy>" // mood of <(nickname)|me> // mood today // mood yesterday // mood week of <(nickname)|me> // mood month of <(nickname)|me> // // Author: // n1k0 /*global module process*/ var MoodEngine = require('../lib') , dateUtil = require('../lib/date-util') , util = require('util') , Url = require('url') , Redis = require('redis') , format = util.format; module.exports = function(robot) { var info = Url.parse(process.env.HUBOT_MOOD_REDIS_URL || 'redis://localhost:6379') , client = Redis.createClient(info.port, info.hostname) , engine = new MoodEngine(client); if (info.auth) { client.auth(info.auth.split(":")[1]); } client.on("error", function(err) { robot.logger.error(err); }); client.on("connect", function() { robot.logger.debug("Successfully connected to Redis from mood script"); }); engine.on('info', function(msg) { robot.logger.info(msg); }); robot.respond(/mood set (\w+)$/i, function(msg) { var user = msg.message.user && msg.message.user.name || "anon" , mood = msg.match[1].toLowerCase(); engine.store({ user: user, mood: mood }, function(err, stored) { if (err) return msg.send(err); msg.send(format('Recorded entry: %s', stored)); }); }); robot.respond(/mood (today|yesterday)$/i, function(msg) { engine.query({ date: dateUtil.today() }, function(err, moods) { if (err) return msg.send(err); if (!moods || !moods.length) { return msg.send(format('No mood entry for %s.', msg.match[1])); } moods.forEach(function(mood) { msg.send('- ' + mood.toString()); }); }); }); robot.respond(/mood month (of|for) (.*)$/i, function(msg) { var user = msg.match[2]; if (user.toLowerCase().trim() === "me") { user = msg.message.user && msg.message.user.name; } engine.graph({ user: user, since: 30 }, function(err, graph) { if (err) return msg.send(err); msg.send(graph); }); }); robot.respond(/mood week (of|for) (.*)$/i, function(msg) { var user = msg.match[2]; if (user.toLowerCase().trim() === "me") { user = msg.message.user && msg.message.user.name; } engine.graph({ user: user, since: 7 }, function(err, graph) { if (err) return msg.send(err); msg.send(graph); }); }); robot.respond(/mood (of|for) (.*)$/i, function(msg) { var user = msg.match[2]; if (user.toLowerCase().trim() === "me") { user = msg.message.user && msg.message.user.name; } engine.query({date: dateUtil.today(), user: user}, function(err, moods) { if (err) return msg.send(err); if (!moods || !moods[0]) { return msg.send(format('%s has not set a mood, yet', user)); } msg.send(moods[0].toString()); }); }); };
refactored bot methods
scripts/mood.js
refactored bot methods
<ide><path>cripts/mood.js <ide> , Redis = require('redis') <ide> , format = util.format; <ide> <add>function nickname(msg, match) { <add> if (!match || match.toLowerCase().trim() === "me") { <add> return msg.message.user && msg.message.user.name || "unknown"; <add> } <add> return match; <add>} <add> <ide> module.exports = function(robot) { <ide> var info = Url.parse(process.env.HUBOT_MOOD_REDIS_URL || 'redis://localhost:6379') <ide> , client = Redis.createClient(info.port, info.hostname) <ide> robot.logger.debug("Successfully connected to Redis from mood script"); <ide> }); <ide> <del> engine.on('info', function(msg) { <add> engine.on("info", function(msg) { <ide> robot.logger.info(msg); <ide> }); <ide> <ide> robot.respond(/mood set (\w+)$/i, function(msg) { <del> var user = msg.message.user && msg.message.user.name || "anon" <del> , mood = msg.match[1].toLowerCase(); <add> var user = nickname(msg) <add> , mood = msg.match[1].toLowerCase(); <ide> engine.store({ user: user, mood: mood }, function(err, stored) { <ide> if (err) return msg.send(err); <ide> msg.send(format('Recorded entry: %s', stored)); <ide> }); <ide> <ide> robot.respond(/mood (today|yesterday)$/i, function(msg) { <del> engine.query({ date: dateUtil.today() }, function(err, moods) { <add> var day = msg.match[1].toLowerCase() <add> , date = day === "today" ? dateUtil.today() : dateUtil.yesterday(); <add> engine.query({ date: date }, function(err, moods) { <ide> if (err) return msg.send(err); <ide> if (!moods || !moods.length) { <del> return msg.send(format('No mood entry for %s.', msg.match[1])); <add> return msg.send(format('No mood entry for %s %s.', msg.match[1], day)); <ide> } <ide> moods.forEach(function(mood) { <ide> msg.send('- ' + mood.toString()); <ide> }); <ide> }); <ide> <del> robot.respond(/mood month (of|for) (.*)$/i, function(msg) { <del> var user = msg.match[2]; <del> if (user.toLowerCase().trim() === "me") { <del> user = msg.message.user && msg.message.user.name; <del> } <del> engine.graph({ user: user, since: 30 }, function(err, graph) { <del> if (err) return msg.send(err); <del> msg.send(graph); <del> }); <del> }); <del> <del> robot.respond(/mood week (of|for) (.*)$/i, function(msg) { <del> var user = msg.match[2]; <del> if (user.toLowerCase().trim() === "me") { <del> user = msg.message.user && msg.message.user.name; <del> } <del> engine.graph({ user: user, since: 7 }, function(err, graph) { <add> robot.respond(/mood (month|week) (of|for) (.*)$/i, function(msg) { <add> var user = nickname(msg, msg.match[2]) <add> , since = msg.match[1].toLowerCase() === "month" ? 30 : 7; <add> engine.graph({ user: user, since: since }, function(err, graph) { <ide> if (err) return msg.send(err); <ide> msg.send(graph); <ide> }); <ide> }); <ide> <ide> robot.respond(/mood (of|for) (.*)$/i, function(msg) { <del> var user = msg.match[2]; <del> if (user.toLowerCase().trim() === "me") { <del> user = msg.message.user && msg.message.user.name; <del> } <del> engine.query({date: dateUtil.today(), user: user}, function(err, moods) { <add> var user = nickname(msg, msg.match[2]) <add> , date = dateUtil.today(); <add> engine.query({date: date, user: user}, function(err, moods) { <ide> if (err) return msg.send(err); <ide> if (!moods || !moods[0]) { <del> return msg.send(format('%s has not set a mood, yet', user)); <add> return msg.send(format('%s has not set a mood today, yet', user)); <ide> } <ide> msg.send(moods[0].toString()); <ide> });
Java
apache-2.0
a8615334a4f84d97c25c6ffada6f388aee13581d
0
lstNull/NineOldAndroids,luyanbo0001/NineOldAndroids,Peter32/NineOldAndroids,ghtijam/NineOldAndroids,Regis25489/NineOldAndroids,sayan801/NineOldAndroids,micrologic/NineOldAndroids,YlJava110/NineOldAndroids,ajrulez/NineOldAndroids,zolazhang/NineOldAndroids,honeyflyfish/NineOldAndroids,likeshu/NineOldAndroids,serso/NineOldAndroids,nguyenduoc/NineOldAndroids,liduanw/NineOldAndroids,littlezan/NineOldAndroids,wangqi504635/NineOldAndroids,tenghuihua/NineOldAndroids,liyi828328/NineOldAndroids,rekirt/NineOldAndroids,snice/NineOldAndroids,xubuhang/NineOldAndroids,JakeWharton/NineOldAndroids,kangdawei/NineOldAndroids,Jalsoncc/NineOldAndroids,huangzl233/NineOldAndroids,iamyuiwong/NineOldAndroids,qingsong-xu/NineOldAndroids,appdevzhang/NineOldAndroids,chenrui2014/NineOldAndroids
package com.nineoldandroids.view.animation; import java.util.WeakHashMap; import android.graphics.Camera; import android.graphics.Matrix; import android.os.Build; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.Transformation; /** * A proxy class to allow for modifying post-3.0 view properties on all pre-3.0 * platforms. <strong>DO NOT</strong> wrap your views with this class if you * are using {@code ObjectAnimator} as it will handle that itself. */ public final class AnimatorProxy extends Animation { /** Whether or not the current running platform needs to be proxied. */ public static final boolean NEEDS_PROXY = Integer.valueOf(Build.VERSION.SDK).intValue() < Build.VERSION_CODES.HONEYCOMB; private static final WeakHashMap<View, AnimatorProxy> PROXIES = new WeakHashMap<View, AnimatorProxy>(); /** * Create a proxy to allow for modifying post-3.0 view properties on all * pre-3.0 platforms. <strong>DO NOT</strong> wrap your views if you are * using {@code ObjectAnimator} as it will handle that itself. * * @param view View to wrap. * @return Proxy to post-3.0 properties. */ public static AnimatorProxy wrap(View view) { AnimatorProxy proxy = PROXIES.get(view); if (proxy == null) { proxy = new AnimatorProxy(view); PROXIES.put(view, proxy); } return proxy; } private final View mView; private final ViewGroup mViewParent; private final Camera mCamera; private boolean mHasPivot = false; private float mAlpha = 1; private float mPivotX = 0; private float mPivotY = 0; private float mRotationX = 0; private float mRotationY = 0; private float mRotationZ = 0; private float mScaleX = 1; private float mScaleY = 1; private float mTranslationX = 0; private float mTranslationY = 0; private AnimatorProxy(View view) { setDuration(0); //perform transformation immediately setFillAfter(true); //persist transformation beyond duration view.setAnimation(this); mView = view; mViewParent = (ViewGroup)view.getParent(); mCamera = new Camera(); } public float getAlpha() { return mAlpha; } public void setAlpha(float alpha) { if (mAlpha != alpha) { mAlpha = alpha; mView.invalidate(); } } public float getPivotX() { return mPivotX; } public void setPivotX(float pivotX) { if (!mHasPivot || mPivotX != pivotX) { mHasPivot = true; mPivotX = pivotX; mViewParent.invalidate(); } } public float getPivotY() { return mPivotY; } public void setPivotY(float pivotY) { if (!mHasPivot || mPivotY != pivotY) { mHasPivot = true; mPivotY = pivotY; mViewParent.invalidate(); } } public float getRotation() { return mRotationZ; } public void setRotation(float rotation) { if (mRotationZ != rotation) { mRotationZ = rotation; mViewParent.invalidate(); } } public float getRotationX() { return mRotationX; } public void setRotationX(float rotationX) { if (mRotationX != rotationX) { mRotationX = rotationX; mViewParent.invalidate(); } } public float getRotationY() { return mRotationY; } public void setRotationY(float rotationY) { if (mRotationY != rotationY) { mRotationY = rotationY; mViewParent.invalidate(); } } public float getScaleX() { return mScaleX; } public void setScaleX(float scaleX) { if (mScaleX != scaleX) { mScaleX = scaleX; mViewParent.invalidate(); } } public float getScaleY() { return mScaleY; } public void setScaleY(float scaleY) { if (mScaleY != scaleY) { mScaleY = scaleY; mViewParent.invalidate(); } } public int getScrollX() { return mView.getScrollX(); } public void setScrollX(int value) { mView.scrollTo(value, mView.getScrollY()); } public int getScrollY() { return mView.getScrollY(); } public void setScrollY(int value) { mView.scrollTo(mView.getScrollY(), value); } public float getTranslationX() { return mTranslationX; } public void setTranslationX(float translationX) { if (mTranslationX != translationX) { mTranslationX = translationX; mViewParent.invalidate(); } } public float getTranslationY() { return mTranslationY; } public void setTranslationY(float translationY) { if (mTranslationY != translationY) { mTranslationY = translationY; mViewParent.invalidate(); } } public float getX() { return mView.getLeft() + mTranslationX; } public void setX(float x) { setTranslationX(x - mView.getLeft()); } public float getY() { return mView.getTop() + mTranslationY; } public void setY(float y) { setTranslationY(y - mView.getTop()); } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { t.setAlpha(mAlpha); final View view = mView; final float w = view.getWidth(); final float h = view.getHeight(); final Matrix m = t.getMatrix(); final float rX = mRotationX; final float rY = mRotationY; final float rZ = mRotationZ; if ((rX != 0) || (rY != 0) || (rZ != 0)) { final Camera camera = mCamera; final boolean hasPivot = mHasPivot; final float pX = hasPivot ? mPivotX : w/2f; final float pY = hasPivot ? mPivotY : h/2f; camera.save(); camera.rotateX(rX); camera.rotateY(rY); camera.rotateZ(-rZ); camera.getMatrix(m); camera.restore(); m.preTranslate(-pX, -pY); m.postTranslate(pX, pY); } final float sX = mScaleX; final float sY = mScaleY; if ((sX != 1.0f) || (sY != 1.0f)) { final float deltaSX = ((sX * w) - w) / 2f; final float deltaSY = ((sY * h) - h) / 2f; m.postScale(sX, sY); m.postTranslate(-deltaSX, -deltaSY); } m.postTranslate(mTranslationX, mTranslationY); } }
library/src/com/nineoldandroids/view/animation/AnimatorProxy.java
package com.nineoldandroids.view.animation; import java.util.WeakHashMap; import android.graphics.Camera; import android.graphics.Matrix; import android.os.Build; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.Transformation; /** * A proxy class to allow for modifying post-3.0 view properties on all pre-3.0 * platforms. <strong>DO NOT</strong> wrap your views with this class if you * are using {@code ObjectAnimator} as it will handle that itself. */ public final class AnimatorProxy extends Animation { /** Whether or not the current running platform needs to be proxied. */ public static final boolean NEEDS_PROXY = Integer.valueOf(Build.VERSION.SDK).intValue() < Build.VERSION_CODES.HONEYCOMB; private static final WeakHashMap<View, AnimatorProxy> PROXIES = new WeakHashMap<View, AnimatorProxy>(); /** * Create a proxy to allow for modifying post-3.0 view properties on all * pre-3.0 platforms. <strong>DO NOT</strong> wrap your views if you are * using {@code ObjectAnimator} as it will handle that itself. * * @param view View to wrap. * @return Proxy to post-3.0 properties. */ public static AnimatorProxy wrap(View view) { AnimatorProxy proxy = PROXIES.get(view); if (proxy == null) { proxy = new AnimatorProxy(view); PROXIES.put(view, proxy); } return proxy; } private final View mView; private final ViewGroup mViewParent; private final Camera mCamera; private boolean mHasPivot = false; private float mAlpha = 1; private float mPivotX = 0; private float mPivotY = 0; private float mRotationX = 0; private float mRotationY = 0; private float mRotationZ = 0; private float mScaleX = 1; private float mScaleY = 1; private float mTranslationX = 0; private float mTranslationY = 0; private AnimatorProxy(View view) { setDuration(0); //perform transformation immediately setFillAfter(true); //persist transformation beyond duration view.setAnimation(this); mView = view; mViewParent = (ViewGroup)view.getParent(); mCamera = new Camera(); } public float getAlpha() { return mAlpha; } public void setAlpha(float alpha) { if (mAlpha != alpha) { mAlpha = alpha; mView.invalidate(); } } public float getPivotX() { return mPivotX; } public void setPivotX(float pivotX) { if (!mHasPivot || mPivotX != pivotX) { mHasPivot = true; mPivotX = pivotX; mViewParent.invalidate(); } } public float getPivotY() { return mPivotY; } public void setPivotY(float pivotY) { if (!mHasPivot || mPivotY != pivotY) { mHasPivot = true; mPivotY = pivotY; mViewParent.invalidate(); } } public float getRotation() { return mRotationZ; } public void setRotation(float rotation) { if (mRotationZ != rotation) { mRotationZ = rotation; mViewParent.invalidate(); } } public float getRotationX() { return mRotationX; } public void setRotationX(float rotationX) { if (mRotationX != rotationX) { mRotationX = rotationX; mViewParent.invalidate(); } } public float getRotationY() { return mRotationY; } public void setRotationY(float rotationY) { if (mRotationY != rotationY) { mRotationY = rotationY; mViewParent.invalidate(); } } public float getScaleX() { return mScaleX; } public void setScaleX(float scaleX) { if (mScaleX != scaleX) { mScaleX = scaleX; mViewParent.invalidate(); } } public float getScaleY() { return mScaleY; } public void setScaleY(float scaleY) { if (mScaleY != scaleY) { mScaleY = scaleY; mViewParent.invalidate(); } } public int getScrollX() { return mView.getScrollX(); } public void setScrollX(int value) { mView.scrollTo(value, mView.getScrollY()); } public int getScrollY() { return mView.getScrollY(); } public void setScrollY(int value) { mView.scrollTo(mView.getScrollY(), value); } public float getTranslationX() { return mTranslationX; } public void setTranslationX(float translationX) { if (mTranslationX != translationX) { mTranslationX = translationX; mViewParent.invalidate(); } } public float getTranslationY() { return mTranslationY; } public void setTranslationY(float translationY) { if (mTranslationY != translationY) { mTranslationY = translationY; mViewParent.invalidate(); } } public float getX() { return mView.getLeft() + mTranslationX; } public void setX(float x) { setTranslationX(x - mView.getLeft()); } public float getY() { return mView.getTop() + mTranslationY; } public void setY(float y) { setTranslationY(y - mView.getTop()); } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { t.setAlpha(mAlpha); final View view = mView; final float w = view.getWidth(); final float h = view.getHeight(); final Matrix m = t.getMatrix(); final float rX = mRotationX; final float rY = mRotationY; final float rZ = mRotationZ; if ((rX != 0) || (rY != 0) || (rZ != 0)) { final Camera camera = mCamera; final boolean hasPivot = mHasPivot; final float pX = hasPivot ? mPivotX : w/2f; final float pY = hasPivot ? mPivotY : h/2f; camera.save(); camera.rotateX(rX); camera.rotateY(rY); camera.rotateZ(-rZ); camera.getMatrix(m); camera.restore(); m.preTranslate(-pX, -pY); m.postTranslate(pX, pY); } final float sX = mScaleX; final float sY = mScaleY; if ((sX != 0) || (sY != 0)) { final float deltaSX = ((sX * w) - w) / 2f; final float deltaSY = ((sY * h) - h) / 2f; m.postScale(sX, sY); m.postTranslate(-deltaSX, -deltaSY); } m.postTranslate(mTranslationX, mTranslationY); } }
Scale testing is more useful when testing against 1.0, not 0.0
library/src/com/nineoldandroids/view/animation/AnimatorProxy.java
Scale testing is more useful when testing against 1.0, not 0.0
<ide><path>ibrary/src/com/nineoldandroids/view/animation/AnimatorProxy.java <ide> <ide> final float sX = mScaleX; <ide> final float sY = mScaleY; <del> if ((sX != 0) || (sY != 0)) { <add> if ((sX != 1.0f) || (sY != 1.0f)) { <ide> final float deltaSX = ((sX * w) - w) / 2f; <ide> final float deltaSY = ((sY * h) - h) / 2f; <ide> m.postScale(sX, sY);
Java
apache-2.0
7bc96ca4dd118edf0848d7742f998985a6f0f0e8
0
fanky10/tps-utnfrro-ag-2014
package com.utn.ag.algoritmocanonico; import com.utn.ag.algoritmocanonico.model.Cromosoma; import com.utn.ag.algoritmocanonico.model.Poblacion; public class AlgoritmoCanonico { private static Double probmutacion; private static Double probcrossover; private int[][] ruleta; private void seleccionRuleta(Poblacion poblacion) { ruleta = new int[poblacion.size() / 2][2]; Double sumaAcumulada = 0d; for (Cromosoma c : poblacion) { sumaAcumulada = sumaAcumulada + c.getFitness(); c.setSumaAcumulada(sumaAcumulada); } for (int i = 0; i < poblacion.size() / 2; i++) { Double ran = Math.random(); for (int j = 0; j < poblacion.size(); j++) { if (poblacion.get(j).getSumaAcumulada() > ran) { ruleta[i][0] = j; break; } } for (int j = 0; j < poblacion.size(); j++) { if (poblacion.get(j).getSumaAcumulada() > ran) { ruleta[i][1] = j; break; } } } } private Cromosoma operadorMutacion(Cromosoma cromosoma) { if (Math.random() <= probmutacion) { cromosoma.mutarBit(); } return cromosoma; } private Cromosoma[] operadorCrossover(Cromosoma[] cromosomas) { if (Math.random() <= probcrossover) { // TODO crossovear } cromosomas[0] = operadorMutacion(cromosomas[0]); cromosomas[0] = operadorMutacion(cromosomas[1]); return cromosomas; } public AlgoritmoCanonico(Double probcrossover, Double promutacion) { this.probcrossover = probcrossover; this.probmutacion = probcrossover; } public Poblacion siguienteGeneracion(Poblacion poblacion) { poblacion.processFitness(); seleccionRuleta(poblacion); Poblacion hijos = new Poblacion(); Cromosoma[] parCromosomas = null; for (int i = 0; i<poblacion.size()/2; i++){ parCromosomas[0] = poblacion.get(ruleta[i][0]); parCromosomas[1] = poblacion.get(ruleta[i][1]); parCromosomas = operadorCrossover(parCromosomas); hijos.add(parCromosomas[0]); hijos.add(parCromosomas[1]); } // TODO: Implementar Crossover y a cada hijo aplicarle operadorMutacion return hijos; } }
dev/AlgoritmoCanonico/src/main/java/com/utn/ag/algoritmocanonico/AlgoritmoCanonico.java
package com.utn.ag.algoritmocanonico; import com.utn.ag.algoritmocanonico.model.Cromosoma; import com.utn.ag.algoritmocanonico.model.Poblacion; public class AlgoritmoCanonico { private static Double probmutacion; private static Double probcrossover; private int[][] ruleta; private void seleccionRuleta(Poblacion poblacion) { ruleta = new int[poblacion.size() / 2][2]; Double sumaAcumulada = 0d; for (Cromosoma c : poblacion) { sumaAcumulada = sumaAcumulada + c.getFitness(); c.setSumaAcumulada(sumaAcumulada); } for (int i = 0; i < poblacion.size() / 2; i++) { Double ran = Math.random(); for (int j = 0; j < poblacion.size(); j++) { if (poblacion.get(j).getSumaAcumulada() > ran) { ruleta[i][0] = j; break; } } for (int j = 0; j < poblacion.size(); j++) { if (poblacion.get(j).getSumaAcumulada() > ran) { ruleta[i][1] = j; break; } } } } public void operadorMutacion(Cromosoma cromosoma) { if (Math.random() >= probmutacion) { cromosoma.mutarBit(); } } public void operadorCrossover(Cromosoma cromosoma1, Cromosoma cromosoma2) { Cromosoma cromosomaHijo1, cromosomaHijo2; if (Math.random() >= probcrossover) { // TODO crossovear } else { } } public AlgoritmoCanonico(Double probcrossover, Double promutacion) { this.probcrossover = probcrossover; this.probmutacion = probcrossover; } public Poblacion siguienteGeneracion(Poblacion poblacion) { poblacion.processFitness(); seleccionRuleta(poblacion); Poblacion hijos = new Poblacion(); // TODO: Implementar Crossover y a cada hijo aplicarle operadorMutacion return hijos; } }
Funcional sin crossover
dev/AlgoritmoCanonico/src/main/java/com/utn/ag/algoritmocanonico/AlgoritmoCanonico.java
Funcional sin crossover
<ide><path>ev/AlgoritmoCanonico/src/main/java/com/utn/ag/algoritmocanonico/AlgoritmoCanonico.java <ide> } <ide> } <ide> <del> public void operadorMutacion(Cromosoma cromosoma) { <add> private Cromosoma operadorMutacion(Cromosoma cromosoma) { <ide> <del> if (Math.random() >= probmutacion) { <add> if (Math.random() <= probmutacion) { <ide> cromosoma.mutarBit(); <ide> } <add> return cromosoma; <ide> <ide> } <ide> <del> public void operadorCrossover(Cromosoma cromosoma1, Cromosoma cromosoma2) { <del> Cromosoma cromosomaHijo1, cromosomaHijo2; <add> private Cromosoma[] operadorCrossover(Cromosoma[] cromosomas) { <add> <ide> <del> if (Math.random() >= probcrossover) { <add> if (Math.random() <= probcrossover) { <ide> // TODO crossovear <ide> <del> } else { <del> <add> <add> <add> <add> <ide> } <del> <add> <add> cromosomas[0] = operadorMutacion(cromosomas[0]); <add> cromosomas[0] = operadorMutacion(cromosomas[1]); <add> <add> <add> return cromosomas; <ide> } <ide> <ide> public AlgoritmoCanonico(Double probcrossover, Double promutacion) { <ide> poblacion.processFitness(); <ide> seleccionRuleta(poblacion); <ide> Poblacion hijos = new Poblacion(); <del> <add> Cromosoma[] parCromosomas = null; <add> <add> for (int i = 0; i<poblacion.size()/2; i++){ <add> parCromosomas[0] = poblacion.get(ruleta[i][0]); <add> parCromosomas[1] = poblacion.get(ruleta[i][1]); <add> <add> parCromosomas = operadorCrossover(parCromosomas); <add> <add> hijos.add(parCromosomas[0]); <add> hijos.add(parCromosomas[1]); <add> <add> <add> } <add> <add> <ide> // TODO: Implementar Crossover y a cada hijo aplicarle operadorMutacion <ide> <ide> return hijos;
Java
apache-2.0
89d3ab37c2f2fb05bb0aa256b0844bb13d75643e
0
srowen/oryx,OryxProject/oryx,OryxProject/oryx,oncewang/oryx2,oncewang/oryx2,dsdinter/oryx,dsdinter/oryx,srowen/oryx
/* * Copyright (c) 2014, Cloudera and Intel, Inc. All Rights Reserved. * * Cloudera, Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"). You may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for * the specific language governing permissions and limitations under the * License. */ package com.cloudera.oryx.app.serving; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Objects; import java.util.concurrent.atomic.AtomicReference; import java.util.zip.GZIPInputStream; import java.util.zip.ZipInputStream; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import com.google.common.base.Preconditions; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.FileCleanerCleanup; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.cloudera.oryx.api.TopicProducer; import com.cloudera.oryx.api.serving.ServingModel; import com.cloudera.oryx.api.serving.ServingModelManager; /** * Superclass of all Serving Layer application endpoints. */ public abstract class AbstractOryxResource { private static final Logger log = LoggerFactory.getLogger(AbstractOryxResource.class); public static final String MODEL_MANAGER_KEY = "com.cloudera.oryx.lambda.serving.ModelManagerListener.ModelManager"; public static final String INPUT_PRODUCER_KEY = "com.cloudera.oryx.lambda.serving.ModelManagerListener.InputProducer"; private static final AtomicReference<DiskFileItemFactory> sharedFileItemFactory = new AtomicReference<>(); @Context private ServletContext servletContext; private TopicProducer<String,String> inputProducer; private ServingModelManager<?> servingModelManager; private boolean hasLoadedEnough; @SuppressWarnings("unchecked") @PostConstruct protected void init() { servingModelManager = (ServingModelManager<?>) servletContext.getAttribute(MODEL_MANAGER_KEY); inputProducer = (TopicProducer<String,String>) servletContext.getAttribute(INPUT_PRODUCER_KEY); } protected final void sendInput(String message) { inputProducer.send(Integer.toHexString(message.hashCode()), message); } protected final boolean isReadOnly() { return servingModelManager.isReadOnly(); } protected final ServingModel getServingModel() throws OryxServingException { ServingModel servingModel = servingModelManager.getModel(); if (hasLoadedEnough) { Objects.requireNonNull(servingModel); return servingModel; } if (servingModel != null) { double minModelLoadFraction = servingModelManager.getConfig().getDouble("oryx.serving.min-model-load-fraction"); Preconditions.checkArgument(minModelLoadFraction >= 0.0 && minModelLoadFraction <= 1.0); float fractionLoaded = servingModel.getFractionLoaded(); log.info("Model loaded fraction: {}", fractionLoaded); if (fractionLoaded >= minModelLoadFraction) { hasLoadedEnough = true; } } if (hasLoadedEnough) { Objects.requireNonNull(servingModel); return servingModel; } else { throw new OryxServingException(Response.Status.SERVICE_UNAVAILABLE); } } protected final List<FileItem> parseMultipart(HttpServletRequest request) throws OryxServingException { // JAX-RS does not by itself support multipart form data yet, so doing it manually. // We'd use Servlet 3.0 but the Grizzly test harness doesn't let us test it :( // Good old Commons FileUpload it is: if (sharedFileItemFactory.get() == null) { // Not a big deal if two threads actually set this up DiskFileItemFactory fileItemFactory = new DiskFileItemFactory( 1 << 16, (File) servletContext.getAttribute("javax.servlet.context.tempdir")); fileItemFactory.setFileCleaningTracker( FileCleanerCleanup.getFileCleaningTracker(servletContext)); sharedFileItemFactory.compareAndSet(null, fileItemFactory); } List<FileItem> fileItems; try { fileItems = new ServletFileUpload(sharedFileItemFactory.get()).parseRequest(request); } catch (FileUploadException e) { throw new OryxServingException(Response.Status.BAD_REQUEST, e.getMessage()); } check(!fileItems.isEmpty(), "No parts"); return fileItems; } protected static void check(boolean condition, Response.Status status, String errorMessage) throws OryxServingException { if (!condition) { throw new OryxServingException(status, errorMessage); } } protected static void check(boolean condition, String errorMessage) throws OryxServingException { check(condition, Response.Status.BAD_REQUEST, errorMessage); } protected static void checkExists(boolean condition, String entity) throws OryxServingException { check(condition, Response.Status.NOT_FOUND, entity); } protected void checkNotReadOnly() throws OryxServingException { check(!isReadOnly(), Response.Status.FORBIDDEN, "Serving Layer is read-only"); } protected static BufferedReader maybeBuffer(InputStream in) { return maybeBuffer(new InputStreamReader(in, StandardCharsets.UTF_8)); } protected static BufferedReader maybeBuffer(Reader reader) { return reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader); } protected static InputStream maybeDecompress(FileItem item) throws IOException { InputStream in = item.getInputStream(); String contentType = item.getContentType(); if (contentType != null) { switch (contentType) { case "application/zip": in = new ZipInputStream(in); break; case "application/gzip": case "application/x-gzip": in = new GZIPInputStream(in); break; } } return in; } }
app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/AbstractOryxResource.java
/* * Copyright (c) 2014, Cloudera and Intel, Inc. All Rights Reserved. * * Cloudera, Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"). You may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for * the specific language governing permissions and limitations under the * License. */ package com.cloudera.oryx.app.serving; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import java.util.zip.GZIPInputStream; import java.util.zip.ZipInputStream; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import com.google.common.base.Preconditions; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.FileCleanerCleanup; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.cloudera.oryx.api.TopicProducer; import com.cloudera.oryx.api.serving.ServingModel; import com.cloudera.oryx.api.serving.ServingModelManager; /** * Superclass of all Serving Layer application endpoints. */ public abstract class AbstractOryxResource { private static final Logger log = LoggerFactory.getLogger(AbstractOryxResource.class); public static final String MODEL_MANAGER_KEY = "com.cloudera.oryx.lambda.serving.ModelManagerListener.ModelManager"; public static final String INPUT_PRODUCER_KEY = "com.cloudera.oryx.lambda.serving.ModelManagerListener.InputProducer"; private static final AtomicReference<DiskFileItemFactory> sharedFileItemFactory = new AtomicReference<>(); @Context private ServletContext servletContext; private TopicProducer<String,String> inputProducer; private ServingModelManager<?> servingModelManager; private boolean hasLoadedEnough; @SuppressWarnings("unchecked") @PostConstruct protected void init() { servingModelManager = (ServingModelManager<?>) servletContext.getAttribute(MODEL_MANAGER_KEY); inputProducer = (TopicProducer<String,String>) servletContext.getAttribute(INPUT_PRODUCER_KEY); } protected final void sendInput(String message) { inputProducer.send(Integer.toHexString(message.hashCode()), message); } protected final boolean isReadOnly() { return servingModelManager.isReadOnly(); } protected final ServingModel getServingModel() throws OryxServingException { ServingModel servingModel = servingModelManager.getModel(); if (hasLoadedEnough) { return servingModel; } if (servingModel != null) { double minModelLoadFraction = servingModelManager.getConfig().getDouble("oryx.serving.min-model-load-fraction"); Preconditions.checkArgument(minModelLoadFraction >= 0.0 && minModelLoadFraction <= 1.0); float fractionLoaded = servingModel.getFractionLoaded(); log.info("Model loaded fraction: {}", fractionLoaded); if (fractionLoaded >= minModelLoadFraction) { hasLoadedEnough = true; } } if (hasLoadedEnough) { return servingModel; } else { throw new OryxServingException(Response.Status.SERVICE_UNAVAILABLE); } } protected final List<FileItem> parseMultipart(HttpServletRequest request) throws OryxServingException { // JAX-RS does not by itself support multipart form data yet, so doing it manually. // We'd use Servlet 3.0 but the Grizzly test harness doesn't let us test it :( // Good old Commons FileUpload it is: if (sharedFileItemFactory.get() == null) { // Not a big deal if two threads actually set this up DiskFileItemFactory fileItemFactory = new DiskFileItemFactory( 1 << 16, (File) servletContext.getAttribute("javax.servlet.context.tempdir")); fileItemFactory.setFileCleaningTracker( FileCleanerCleanup.getFileCleaningTracker(servletContext)); sharedFileItemFactory.compareAndSet(null, fileItemFactory); } List<FileItem> fileItems; try { fileItems = new ServletFileUpload(sharedFileItemFactory.get()).parseRequest(request); } catch (FileUploadException e) { throw new OryxServingException(Response.Status.BAD_REQUEST, e.getMessage()); } check(!fileItems.isEmpty(), "No parts"); return fileItems; } protected static void check(boolean condition, Response.Status status, String errorMessage) throws OryxServingException { if (!condition) { throw new OryxServingException(status, errorMessage); } } protected static void check(boolean condition, String errorMessage) throws OryxServingException { check(condition, Response.Status.BAD_REQUEST, errorMessage); } protected static void checkExists(boolean condition, String entity) throws OryxServingException { check(condition, Response.Status.NOT_FOUND, entity); } protected void checkNotReadOnly() throws OryxServingException { check(!isReadOnly(), Response.Status.FORBIDDEN, "Serving Layer is read-only"); } protected static BufferedReader maybeBuffer(InputStream in) { return maybeBuffer(new InputStreamReader(in, StandardCharsets.UTF_8)); } protected static BufferedReader maybeBuffer(Reader reader) { return reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader); } protected static InputStream maybeDecompress(FileItem item) throws IOException { InputStream in = item.getInputStream(); String contentType = item.getContentType(); if (contentType != null) { switch (contentType) { case "application/zip": in = new ZipInputStream(in); break; case "application/gzip": case "application/x-gzip": in = new GZIPInputStream(in); break; } } return in; } }
Per Coverity, ensure that the serving model returned is never null
app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/AbstractOryxResource.java
Per Coverity, ensure that the serving model returned is never null
<ide><path>pp/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/AbstractOryxResource.java <ide> import java.io.Reader; <ide> import java.nio.charset.StandardCharsets; <ide> import java.util.List; <add>import java.util.Objects; <ide> import java.util.concurrent.atomic.AtomicReference; <ide> import java.util.zip.GZIPInputStream; <ide> import java.util.zip.ZipInputStream; <ide> protected final ServingModel getServingModel() throws OryxServingException { <ide> ServingModel servingModel = servingModelManager.getModel(); <ide> if (hasLoadedEnough) { <add> Objects.requireNonNull(servingModel); <ide> return servingModel; <ide> } <ide> if (servingModel != null) { <ide> } <ide> } <ide> if (hasLoadedEnough) { <add> Objects.requireNonNull(servingModel); <ide> return servingModel; <ide> } else { <ide> throw new OryxServingException(Response.Status.SERVICE_UNAVAILABLE);
Java
apache-2.0
cc002614029e3ed09c8a84501851039aef84cf22
0
aclemons/osgi-launcher
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.felix.main; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import org.apache.felix.framework.Felix; import org.apache.felix.framework.util.FelixConstants; import org.apache.felix.framework.util.Util; import org.osgi.framework.Constants; import org.osgi.framework.launch.Framework; /** * <p> * This class is the default way to instantiate and execute the framework. It is not * intended to be the only way to instantiate and execute the framework; rather, it is * one example of how to do so. When embedding the framework in a host application, * this class can serve as a simple guide of how to do so. It may even be * worthwhile to reuse some of its property handling capabilities. * </p> **/ public class Main { /** * The property name used to specify an URL to the system * property file. **/ public static final String SYSTEM_PROPERTIES_PROP = "felix.system.properties"; /** * The default name used for the system properties file. **/ public static final String SYSTEM_PROPERTIES_FILE_VALUE = "system.properties"; /** * The property name used to specify an URL to the configuration * property file to be used for the created the framework instance. **/ public static final String CONFIG_PROPERTIES_PROP = "felix.config.properties"; /** * The default name used for the configuration properties file. **/ public static final String CONFIG_PROPERTIES_FILE_VALUE = "config.properties"; private static Framework m_felix = null; /** * <p> * This method performs the main task of constructing an framework instance * and starting its execution. The following functions are performed * when invoked: * </p> * <ol> * <li><i><b>Read the system properties file.<b></i> This is a file * containing properties to be pushed into <tt>System.setProperty()</tt> * before starting the framework. This mechanism is mainly shorthand * for people starting the framework from the command line to avoid having * to specify a bunch of <tt>-D</tt> system property definitions. * The only properties defined in this file that will impact the framework's * behavior are the those concerning setting HTTP proxies, such as * <tt>http.proxyHost</tt>, <tt>http.proxyPort</tt>, and * <tt>http.proxyAuth</tt>. Generally speaking, the framework does * not use system properties at all. * </li> * <li><i><b>Perform system property variable substitution on system * properties.</b></i> Any system properties in the system property * file whose value adheres to <tt>${&lt;system-prop-name&gt;}</tt> * syntax will have their value substituted with the appropriate * system property value. * </li> * <li><i><b>Read the framework's configuration property file.</b></i> This is * a file containing properties used to configure the framework * instance and to pass configuration information into * bundles installed into the framework instance. The configuration * property file is called <tt>config.properties</tt> by default * and is located in the <tt>conf/</tt> directory of the Felix * installation directory, which is the parent directory of the * directory containing the <tt>felix.jar</tt> file. It is possible * to use a different location for the property file by specifying * the desired URL using the <tt>felix.config.properties</tt> * system property; this should be set using the <tt>-D</tt> syntax * when executing the JVM. If the <tt>config.properties</tt> file * cannot be found, then the bare-bones <tt>default.properties</tt> * configuration file will be used to set the configuration properties; * this file is embedded in the launcher JAR file. Refer to the * <a href="Felix.html#Felix(java.util.Map, java.util.List)"> * <tt>Felix</tt></a> constructor documentation for more * information on the framework configuration options. * </li> * <li><i><b>Perform system property variable substitution on configuration * properties.</b></i> Any configuration properties whose value adheres to * <tt>${&lt;system-prop-name&gt;}</tt> syntax will have their value * substituted with the appropriate system property value. * </li> * <li><i><b>Ensure the default bundle cache has sufficient information to * initialize.</b></i> The default implementation of the bundle cache * requires either a profile name or a profile directory in order to * start. The configuration properties are checked for at least one * of the <tt>felix.cache.profile</tt> or <tt>felix.cache.profiledir</tt> * properties. If neither is found, the user is asked to supply a profile * name that is added to the configuration property set. See the * <a href="cache/DefaultBundleCache.html"><tt>DefaultBundleCache</tt></a> * documentation for more details its configuration options. * </li> * <li><i><b>Creates and starts a framework instance.</b></i> A * case insensitive * <a href="util/StringMap.html"><tt>StringMap</tt></a> * is created for the configuration property file and is passed * into the framework. * </li> * </ol> * <p> * It should be noted that simply starting an instance of the framework is not enough * to create an interactive session with it. It is necessary to install * and start bundles that provide a some means to interact with the framework; * this is generally done by specifying an "auto-start" property in the * framework configuration property file. If no bundles providing a means to * interact with the framework are installed or if the configuration property * file cannot be found, the framework will appear to be hung or deadlocked. * This is not the case, it is executing correctly, there is just no way to * interact with it. The default launcher provides two configuration properties * to help you automatically install and/or start bundles, which are: * </p> * <ul> * <li><tt>felix.auto.install.&lt;n&gt;</tt> - Space-delimited list of * bundle URLs to automatically install into start level <tt>n</tt> when * the framework is started. Append a specific start level to this * property name to assign the bundles' start level * (e.g., <tt>felix.auto.install.2</tt>); otherwise, bundles are * installed into the default bundle start level. * </li> * <li><tt>felix.auto.start.&lt;n&gt;</tt> - Space-delimited list of * bundle URLs to automatically install and start into start level * <tt>n</tt> when the framework is started. Append a * specific start level to this property name to assign the * bundles' start level(e.g., <tt>felix.auto.start.2</tt>); otherwise, * bundles are installed into the default bundle start level. * </li> * </ul> * <p> * These properties should be specified in the <tt>config.properties</tt> * so that they can be processed by the launcher during the framework * startup process. * </p> * @param argv An array of arguments, all of which are ignored. * @throws Exception If an error occurs. **/ public static void main(String[] args) throws Exception { // We support at most one argument, which is the bundle // cache directory. if (args.length > 1) { System.out.println("Usage: [<bundle-cache-dir>]"); System.exit(0); } // Load system properties. Main.loadSystemProperties(); // Read configuration properties. Properties configProps = Main.loadConfigProperties(); // Copy framework properties from the system properties. Main.copySystemProperties(configProps); // If there is a passed in bundle cache directory, then // that overwrites anything in the config file. if (args.length > 0) { configProps.setProperty(Constants.FRAMEWORK_STORAGE, args[0]); } // Create a list for custom framework activators and // add an instance of the auto-activator it for processing // auto-install and auto-start properties. Add this list // to the configuration properties. List list = new ArrayList(); list.add(new AutoActivator(configProps)); configProps.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list); // Print welcome banner. System.out.println("\nWelcome to Felix."); System.out.println("=================\n"); try { // Create an instance and start the framework. m_felix = new Felix(configProps); m_felix.start(); // Wait for framework to stop to exit the VM. m_felix.waitForStop(0); System.exit(0); } catch (Exception ex) { System.err.println("Could not create framework: " + ex); ex.printStackTrace(); System.exit(-1); } } /** * <p> * Loads the properties in the system property file associated with the * framework installation into <tt>System.setProperty()</tt>. These properties * are not directly used by the framework in anyway. By default, the system * property file is located in the <tt>conf/</tt> directory of the Felix * installation directory and is called "<tt>system.properties</tt>". The * installation directory of Felix is assumed to be the parent directory of * the <tt>felix.jar</tt> file as found on the system class path property. * The precise file from which to load system properties can be set by * initializing the "<tt>felix.system.properties</tt>" system property to an * arbitrary URL. * </p> **/ public static void loadSystemProperties() { // The system properties file is either specified by a system // property or it is in the same directory as the Felix JAR file. // Try to load it from one of these places. // See if the property URL was specified as a property. URL propURL = null; String custom = System.getProperty(SYSTEM_PROPERTIES_PROP); if (custom != null) { try { propURL = new URL(custom); } catch (MalformedURLException ex) { System.err.print("Main: " + ex); return; } } else { // Determine where the configuration directory is by figuring // out where felix.jar is located on the system class path. File confDir = null; String classpath = System.getProperty("java.class.path"); int index = classpath.toLowerCase().indexOf("felix.jar"); int start = classpath.lastIndexOf(File.pathSeparator, index) + 1; if (index >= start) { // Get the path of the felix.jar file. String jarLocation = classpath.substring(start, index); // Calculate the conf directory based on the parent // directory of the felix.jar directory. confDir = new File( new File(new File(jarLocation).getAbsolutePath()).getParent(), "conf"); } else { // Can't figure it out so use the current directory as default. confDir = new File(System.getProperty("user.dir")); } try { propURL = new File(confDir, SYSTEM_PROPERTIES_FILE_VALUE).toURL(); } catch (MalformedURLException ex) { System.err.print("Main: " + ex); return; } } // Read the properties file. Properties props = new Properties(); InputStream is = null; try { is = propURL.openConnection().getInputStream(); props.load(is); is.close(); } catch (FileNotFoundException ex) { // Ignore file not found. } catch (Exception ex) { System.err.println( "Main: Error loading system properties from " + propURL); System.err.println("Main: " + ex); try { if (is != null) is.close(); } catch (IOException ex2) { // Nothing we can do. } return; } // Perform variable substitution on specified properties. for (Enumeration e = props.propertyNames(); e.hasMoreElements(); ) { String name = (String) e.nextElement(); System.setProperty(name, Util.substVars(props.getProperty(name), name, null, null)); } } /** * <p> * Loads the configuration properties in the configuration property file * associated with the framework installation; these properties * are accessible to the framework and to bundles and are intended * for configuration purposes. By default, the configuration property * file is located in the <tt>conf/</tt> directory of the Felix * installation directory and is called "<tt>config.properties</tt>". * The installation directory of Felix is assumed to be the parent * directory of the <tt>felix.jar</tt> file as found on the system class * path property. The precise file from which to load configuration * properties can be set by initializing the "<tt>felix.config.properties</tt>" * system property to an arbitrary URL. * </p> * @return A <tt>Properties</tt> instance or <tt>null</tt> if there was an error. **/ public static Properties loadConfigProperties() { // The config properties file is either specified by a system // property or it is in the conf/ directory of the Felix // installation directory. Try to load it from one of these // places. // See if the property URL was specified as a property. URL propURL = null; String custom = System.getProperty(CONFIG_PROPERTIES_PROP); if (custom != null) { try { propURL = new URL(custom); } catch (MalformedURLException ex) { System.err.print("Main: " + ex); return null; } } else { // Determine where the configuration directory is by figuring // out where felix.jar is located on the system class path. File confDir = null; String classpath = System.getProperty("java.class.path"); int index = classpath.toLowerCase().indexOf("felix.jar"); int start = classpath.lastIndexOf(File.pathSeparator, index) + 1; if (index >= start) { // Get the path of the felix.jar file. String jarLocation = classpath.substring(start, index); // Calculate the conf directory based on the parent // directory of the felix.jar directory. confDir = new File( new File(new File(jarLocation).getAbsolutePath()).getParent(), "conf"); } else { // Can't figure it out so use the current directory as default. confDir = new File(System.getProperty("user.dir")); } try { propURL = new File(confDir, CONFIG_PROPERTIES_FILE_VALUE).toURL(); } catch (MalformedURLException ex) { System.err.print("Main: " + ex); return null; } } // Read the properties file. Properties props = new Properties(); InputStream is = null; try { // Try to load config.properties. is = propURL.openConnection().getInputStream(); props.load(is); is.close(); } catch (Exception ex) { // Try to close input stream if we have one. try { if (is != null) is.close(); } catch (IOException ex2) { // Nothing we can do. } return null; } // Perform variable substitution for system properties. for (Enumeration e = props.propertyNames(); e.hasMoreElements(); ) { String name = (String) e.nextElement(); props.setProperty(name, Util.substVars(props.getProperty(name), name, null, props)); } return props; } public static void copySystemProperties(Properties configProps) { for (Enumeration e = System.getProperties().propertyNames(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); if (key.startsWith("felix.") || key.startsWith("org.osgi.framework.")) { configProps.setProperty(key, System.getProperty(key)); } } } }
src/main/java/org/apache/felix/main/Main.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.felix.main; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import org.apache.felix.framework.Felix; import org.apache.felix.framework.util.FelixConstants; import org.apache.felix.framework.util.Util; import org.osgi.framework.Constants; /** * <p> * This class is the default way to instantiate and execute the framework. It is not * intended to be the only way to instantiate and execute the framework; rather, it is * one example of how to do so. When embedding the framework in a host application, * this class can serve as a simple guide of how to do so. It may even be * worthwhile to reuse some of its property handling capabilities. * </p> **/ public class Main { /** * The property name used to specify an URL to the system * property file. **/ public static final String SYSTEM_PROPERTIES_PROP = "felix.system.properties"; /** * The default name used for the system properties file. **/ public static final String SYSTEM_PROPERTIES_FILE_VALUE = "system.properties"; /** * The property name used to specify an URL to the configuration * property file to be used for the created the framework instance. **/ public static final String CONFIG_PROPERTIES_PROP = "felix.config.properties"; /** * The default name used for the configuration properties file. **/ public static final String CONFIG_PROPERTIES_FILE_VALUE = "config.properties"; private static Felix m_felix = null; /** * <p> * This method performs the main task of constructing an framework instance * and starting its execution. The following functions are performed * when invoked: * </p> * <ol> * <li><i><b>Read the system properties file.<b></i> This is a file * containing properties to be pushed into <tt>System.setProperty()</tt> * before starting the framework. This mechanism is mainly shorthand * for people starting the framework from the command line to avoid having * to specify a bunch of <tt>-D</tt> system property definitions. * The only properties defined in this file that will impact the framework's * behavior are the those concerning setting HTTP proxies, such as * <tt>http.proxyHost</tt>, <tt>http.proxyPort</tt>, and * <tt>http.proxyAuth</tt>. Generally speaking, the framework does * not use system properties at all. * </li> * <li><i><b>Perform system property variable substitution on system * properties.</b></i> Any system properties in the system property * file whose value adheres to <tt>${&lt;system-prop-name&gt;}</tt> * syntax will have their value substituted with the appropriate * system property value. * </li> * <li><i><b>Read the framework's configuration property file.</b></i> This is * a file containing properties used to configure the framework * instance and to pass configuration information into * bundles installed into the framework instance. The configuration * property file is called <tt>config.properties</tt> by default * and is located in the <tt>conf/</tt> directory of the Felix * installation directory, which is the parent directory of the * directory containing the <tt>felix.jar</tt> file. It is possible * to use a different location for the property file by specifying * the desired URL using the <tt>felix.config.properties</tt> * system property; this should be set using the <tt>-D</tt> syntax * when executing the JVM. If the <tt>config.properties</tt> file * cannot be found, then the bare-bones <tt>default.properties</tt> * configuration file will be used to set the configuration properties; * this file is embedded in the launcher JAR file. Refer to the * <a href="Felix.html#Felix(java.util.Map, java.util.List)"> * <tt>Felix</tt></a> constructor documentation for more * information on the framework configuration options. * </li> * <li><i><b>Perform system property variable substitution on configuration * properties.</b></i> Any configuration properties whose value adheres to * <tt>${&lt;system-prop-name&gt;}</tt> syntax will have their value * substituted with the appropriate system property value. * </li> * <li><i><b>Ensure the default bundle cache has sufficient information to * initialize.</b></i> The default implementation of the bundle cache * requires either a profile name or a profile directory in order to * start. The configuration properties are checked for at least one * of the <tt>felix.cache.profile</tt> or <tt>felix.cache.profiledir</tt> * properties. If neither is found, the user is asked to supply a profile * name that is added to the configuration property set. See the * <a href="cache/DefaultBundleCache.html"><tt>DefaultBundleCache</tt></a> * documentation for more details its configuration options. * </li> * <li><i><b>Creates and starts a framework instance.</b></i> A * case insensitive * <a href="util/StringMap.html"><tt>StringMap</tt></a> * is created for the configuration property file and is passed * into the framework. * </li> * </ol> * <p> * It should be noted that simply starting an instance of the framework is not enough * to create an interactive session with it. It is necessary to install * and start bundles that provide a some means to interact with the framework; * this is generally done by specifying an "auto-start" property in the * framework configuration property file. If no bundles providing a means to * interact with the framework are installed or if the configuration property * file cannot be found, the framework will appear to be hung or deadlocked. * This is not the case, it is executing correctly, there is just no way to * interact with it. The default launcher provides two configuration properties * to help you automatically install and/or start bundles, which are: * </p> * <ul> * <li><tt>felix.auto.install.&lt;n&gt;</tt> - Space-delimited list of * bundle URLs to automatically install into start level <tt>n</tt> when * the framework is started. Append a specific start level to this * property name to assign the bundles' start level * (e.g., <tt>felix.auto.install.2</tt>); otherwise, bundles are * installed into the default bundle start level. * </li> * <li><tt>felix.auto.start.&lt;n&gt;</tt> - Space-delimited list of * bundle URLs to automatically install and start into start level * <tt>n</tt> when the framework is started. Append a * specific start level to this property name to assign the * bundles' start level(e.g., <tt>felix.auto.start.2</tt>); otherwise, * bundles are installed into the default bundle start level. * </li> * </ul> * <p> * These properties should be specified in the <tt>config.properties</tt> * so that they can be processed by the launcher during the framework * startup process. * </p> * @param argv An array of arguments, all of which are ignored. * @throws Exception If an error occurs. **/ public static void main(String[] args) throws Exception { // We support at most one argument, which is the bundle // cache directory. if (args.length > 1) { System.out.println("Usage: [<bundle-cache-dir>]"); System.exit(0); } // Load system properties. Main.loadSystemProperties(); // Read configuration properties. Properties configProps = Main.loadConfigProperties(); // Copy framework properties from the system properties. Main.copySystemProperties(configProps); // If there is a passed in bundle cache directory, then // that overwrites anything in the config file. if (args.length > 0) { configProps.setProperty(Constants.FRAMEWORK_STORAGE, args[0]); } // Create a list for custom framework activators and // add an instance of the auto-activator it for processing // auto-install and auto-start properties. Add this list // to the configuration properties. List list = new ArrayList(); list.add(new AutoActivator(configProps)); configProps.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list); // Print welcome banner. System.out.println("\nWelcome to Felix."); System.out.println("=================\n"); try { // Create an instance and start the framework. m_felix = new Felix(configProps); m_felix.start(); // Wait for framework to stop to exit the VM. m_felix.waitForStop(0); System.exit(0); } catch (Exception ex) { System.err.println("Could not create framework: " + ex); ex.printStackTrace(); System.exit(-1); } } /** * <p> * Loads the properties in the system property file associated with the * framework installation into <tt>System.setProperty()</tt>. These properties * are not directly used by the framework in anyway. By default, the system * property file is located in the <tt>conf/</tt> directory of the Felix * installation directory and is called "<tt>system.properties</tt>". The * installation directory of Felix is assumed to be the parent directory of * the <tt>felix.jar</tt> file as found on the system class path property. * The precise file from which to load system properties can be set by * initializing the "<tt>felix.system.properties</tt>" system property to an * arbitrary URL. * </p> **/ public static void loadSystemProperties() { // The system properties file is either specified by a system // property or it is in the same directory as the Felix JAR file. // Try to load it from one of these places. // See if the property URL was specified as a property. URL propURL = null; String custom = System.getProperty(SYSTEM_PROPERTIES_PROP); if (custom != null) { try { propURL = new URL(custom); } catch (MalformedURLException ex) { System.err.print("Main: " + ex); return; } } else { // Determine where the configuration directory is by figuring // out where felix.jar is located on the system class path. File confDir = null; String classpath = System.getProperty("java.class.path"); int index = classpath.toLowerCase().indexOf("felix.jar"); int start = classpath.lastIndexOf(File.pathSeparator, index) + 1; if (index >= start) { // Get the path of the felix.jar file. String jarLocation = classpath.substring(start, index); // Calculate the conf directory based on the parent // directory of the felix.jar directory. confDir = new File( new File(new File(jarLocation).getAbsolutePath()).getParent(), "conf"); } else { // Can't figure it out so use the current directory as default. confDir = new File(System.getProperty("user.dir")); } try { propURL = new File(confDir, SYSTEM_PROPERTIES_FILE_VALUE).toURL(); } catch (MalformedURLException ex) { System.err.print("Main: " + ex); return; } } // Read the properties file. Properties props = new Properties(); InputStream is = null; try { is = propURL.openConnection().getInputStream(); props.load(is); is.close(); } catch (FileNotFoundException ex) { // Ignore file not found. } catch (Exception ex) { System.err.println( "Main: Error loading system properties from " + propURL); System.err.println("Main: " + ex); try { if (is != null) is.close(); } catch (IOException ex2) { // Nothing we can do. } return; } // Perform variable substitution on specified properties. for (Enumeration e = props.propertyNames(); e.hasMoreElements(); ) { String name = (String) e.nextElement(); System.setProperty(name, Util.substVars(props.getProperty(name), name, null, null)); } } /** * <p> * Loads the configuration properties in the configuration property file * associated with the framework installation; these properties * are accessible to the framework and to bundles and are intended * for configuration purposes. By default, the configuration property * file is located in the <tt>conf/</tt> directory of the Felix * installation directory and is called "<tt>config.properties</tt>". * The installation directory of Felix is assumed to be the parent * directory of the <tt>felix.jar</tt> file as found on the system class * path property. The precise file from which to load configuration * properties can be set by initializing the "<tt>felix.config.properties</tt>" * system property to an arbitrary URL. * </p> * @return A <tt>Properties</tt> instance or <tt>null</tt> if there was an error. **/ public static Properties loadConfigProperties() { // The config properties file is either specified by a system // property or it is in the conf/ directory of the Felix // installation directory. Try to load it from one of these // places. // See if the property URL was specified as a property. URL propURL = null; String custom = System.getProperty(CONFIG_PROPERTIES_PROP); if (custom != null) { try { propURL = new URL(custom); } catch (MalformedURLException ex) { System.err.print("Main: " + ex); return null; } } else { // Determine where the configuration directory is by figuring // out where felix.jar is located on the system class path. File confDir = null; String classpath = System.getProperty("java.class.path"); int index = classpath.toLowerCase().indexOf("felix.jar"); int start = classpath.lastIndexOf(File.pathSeparator, index) + 1; if (index >= start) { // Get the path of the felix.jar file. String jarLocation = classpath.substring(start, index); // Calculate the conf directory based on the parent // directory of the felix.jar directory. confDir = new File( new File(new File(jarLocation).getAbsolutePath()).getParent(), "conf"); } else { // Can't figure it out so use the current directory as default. confDir = new File(System.getProperty("user.dir")); } try { propURL = new File(confDir, CONFIG_PROPERTIES_FILE_VALUE).toURL(); } catch (MalformedURLException ex) { System.err.print("Main: " + ex); return null; } } // Read the properties file. Properties props = new Properties(); InputStream is = null; try { // Try to load config.properties. is = propURL.openConnection().getInputStream(); props.load(is); is.close(); } catch (Exception ex) { // Try to close input stream if we have one. try { if (is != null) is.close(); } catch (IOException ex2) { // Nothing we can do. } return null; } // Perform variable substitution for system properties. for (Enumeration e = props.propertyNames(); e.hasMoreElements(); ) { String name = (String) e.nextElement(); props.setProperty(name, Util.substVars(props.getProperty(name), name, null, props)); } return props; } public static void copySystemProperties(Properties configProps) { for (Enumeration e = System.getProperties().propertyNames(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); if (key.startsWith("felix.") || key.startsWith("org.osgi.framework.")) { configProps.setProperty(key, System.getProperty(key)); } } } }
Change the name of the SystemBundle interface to be Framework as a result of the latest discussions. (FELIX-753) git-svn-id: e057f57e93a604d3b43d277ae69bde5ebf332112@707407 13f79535-47bb-0310-9956-ffa450edef68
src/main/java/org/apache/felix/main/Main.java
Change the name of the SystemBundle interface to be Framework as a result of the latest discussions. (FELIX-753)
<ide><path>rc/main/java/org/apache/felix/main/Main.java <ide> import org.apache.felix.framework.util.FelixConstants; <ide> import org.apache.felix.framework.util.Util; <ide> import org.osgi.framework.Constants; <add>import org.osgi.framework.launch.Framework; <ide> <ide> /** <ide> * <p> <ide> **/ <ide> public static final String CONFIG_PROPERTIES_FILE_VALUE = "config.properties"; <ide> <del> private static Felix m_felix = null; <add> private static Framework m_felix = null; <ide> <ide> /** <ide> * <p>
Java
apache-2.0
9b705695216b97e1f6f7b05203576aa19ef56f0b
0
allotria/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,allotria/intellij-community,xfournet/intellij-community,allotria/intellij-community,xfournet/intellij-community,allotria/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,allotria/intellij-community,xfournet/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,allotria/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community
// Copyright 2000-2017 JetBrains s.r.o. // Use of this source code is governed by the Apache 2.0 license that can be // found in the LICENSE file. package com.intellij.openapi.roots.impl; import com.intellij.codeInsight.daemon.impl.quickfix.LocateLibraryDialog; import com.intellij.codeInsight.daemon.impl.quickfix.OrderEntryFix; import com.intellij.jarRepository.JarRepositoryManager; import com.intellij.jarRepository.RepositoryAttachDialog; import com.intellij.openapi.application.Result; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.ex.JavaSdkUtil; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.ex.ProjectRootManagerEx; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar; import com.intellij.openapi.roots.libraries.LibraryUtil; import com.intellij.openapi.roots.libraries.ui.OrderRoot; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.EmptyRunnable; import com.intellij.pom.java.LanguageLevel; import com.intellij.util.PathUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.concurrency.Promise; import org.jetbrains.concurrency.Promises; import org.jetbrains.idea.maven.utils.library.RepositoryLibraryProperties; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; /** * @author nik */ public class IdeaProjectModelModifier extends JavaProjectModelModifier { private static final Logger LOG = Logger.getInstance(IdeaProjectModelModifier.class); private final Project myProject; public IdeaProjectModelModifier(Project project) { myProject = project; } @Override public Promise<Void> addModuleDependency(@NotNull Module from, @NotNull Module to, @NotNull DependencyScope scope, boolean exported) { ModuleRootModificationUtil.addDependency(from, to, scope, exported); return Promises.resolvedPromise(null); } @Override public Promise<Void> addLibraryDependency(@NotNull Module from, @NotNull Library library, @NotNull DependencyScope scope, boolean exported) { OrderEntryUtil.addLibraryToRoots(from, library, scope, exported); return Promises.resolvedPromise(null); } @Override public Promise<Void> addExternalLibraryDependency(@NotNull final Collection<Module> modules, @NotNull final ExternalLibraryDescriptor descriptor, @NotNull final DependencyScope scope) { List<String> defaultRoots = descriptor.getLibraryClassesRoots(); List<String> classesRoots; Module firstModule = ContainerUtil.getFirstItem(modules); if (!defaultRoots.isEmpty()) { LOG.assertTrue(firstModule != null); classesRoots = new LocateLibraryDialog(firstModule, defaultRoots, descriptor.getPresentableName()).showAndGetResult(); } else { String version = descriptor.getMinVersion(); String mavenCoordinates = descriptor.getLibraryGroupId() + ":" + descriptor.getLibraryArtifactId() + (version != null ? ":" + version : ""); RepositoryAttachDialog dialog = new RepositoryAttachDialog(myProject, mavenCoordinates, RepositoryAttachDialog.Mode.DOWNLOAD); if (!dialog.showAndGet()) { return Promises.rejectedPromise(); } RepositoryLibraryProperties libraryProperties = new RepositoryLibraryProperties(dialog.getCoordinateText(), true); Collection<OrderRoot> roots = JarRepositoryManager.loadDependenciesModal(myProject, libraryProperties, dialog.getAttachSources(), dialog.getAttachJavaDoc(), dialog.getDirectoryPath(), null); if (roots.isEmpty()) { Messages.showErrorDialog(myProject, descriptor.getPresentableName() + " was not loaded.", "Failed to Download Library"); return Promises.rejectedPromise(); } classesRoots = roots.stream() .filter(root -> root.getType() == OrderRootType.CLASSES) .map(root -> PathUtil.getLocalPath(root.getFile())) .collect(Collectors.toList()); } if (!classesRoots.isEmpty()) { String libraryName = classesRoots.size() > 1 ? descriptor.getPresentableName() : null; final List<String> urls = OrderEntryFix.refreshAndConvertToUrls(classesRoots); if (modules.size() == 1) { ModuleRootModificationUtil.addModuleLibrary(firstModule, libraryName, urls, Collections.emptyList(), scope); } else { new WriteAction() { protected void run(@NotNull Result result) { Library library = LibraryUtil.createLibrary(LibraryTablesRegistrar.getInstance().getLibraryTable(myProject), descriptor.getPresentableName()); Library.ModifiableModel model = library.getModifiableModel(); for (String url : urls) { model.addRoot(url, OrderRootType.CLASSES); } model.commit(); for (Module module : modules) { ModuleRootModificationUtil.addDependency(module, library, scope, false); } } }.execute(); } } return Promises.resolvedPromise(null); } @Override public Promise<Void> changeLanguageLevel(@NotNull Module module, @NotNull LanguageLevel level) { final LanguageLevel moduleLevel = LanguageLevelModuleExtensionImpl.getInstance(module).getLanguageLevel(); if (moduleLevel != null && JavaSdkUtil.isLanguageLevelAcceptable(myProject, module, level)) { final ModifiableRootModel rootModel = ModuleRootManager.getInstance(module).getModifiableModel(); rootModel.getModuleExtension(LanguageLevelModuleExtension.class).setLanguageLevel(level); rootModel.commit(); } else { LanguageLevelProjectExtension.getInstance(myProject).setLanguageLevel(level); ProjectRootManagerEx.getInstanceEx(myProject).makeRootsChange(EmptyRunnable.INSTANCE, false, true); } return Promises.resolvedPromise(null); } }
java/idea-ui/src/com/intellij/openapi/roots/impl/IdeaProjectModelModifier.java
// Copyright 2000-2017 JetBrains s.r.o. // Use of this source code is governed by the Apache 2.0 license that can be // found in the LICENSE file. package com.intellij.openapi.roots.impl; import com.intellij.codeInsight.daemon.impl.quickfix.LocateLibraryDialog; import com.intellij.codeInsight.daemon.impl.quickfix.OrderEntryFix; import com.intellij.jarRepository.JarRepositoryManager; import com.intellij.jarRepository.RepositoryAttachDialog; import com.intellij.openapi.application.Result; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.ex.JavaSdkUtil; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.ex.ProjectRootManagerEx; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar; import com.intellij.openapi.roots.libraries.LibraryUtil; import com.intellij.openapi.roots.libraries.ui.OrderRoot; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.EmptyRunnable; import com.intellij.pom.java.LanguageLevel; import com.intellij.util.PathUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.concurrency.Promise; import org.jetbrains.concurrency.Promises; import org.jetbrains.idea.maven.utils.library.RepositoryLibraryProperties; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; /** * @author nik */ public class IdeaProjectModelModifier extends JavaProjectModelModifier { private static final Logger LOG = Logger.getInstance(IdeaProjectModelModifier.class); private final Project myProject; public IdeaProjectModelModifier(Project project) { myProject = project; } @Override public Promise<Void> addModuleDependency(@NotNull Module from, @NotNull Module to, @NotNull DependencyScope scope, boolean exported) { ModuleRootModificationUtil.addDependency(from, to, scope, exported); return Promises.resolvedPromise(null); } @Override public Promise<Void> addLibraryDependency(@NotNull Module from, @NotNull Library library, @NotNull DependencyScope scope, boolean exported) { OrderEntryUtil.addLibraryToRoots(from, library, scope, exported); return Promises.resolvedPromise(null); } @Override public Promise<Void> addExternalLibraryDependency(@NotNull final Collection<Module> modules, @NotNull final ExternalLibraryDescriptor descriptor, @NotNull final DependencyScope scope) { List<String> defaultRoots = descriptor.getLibraryClassesRoots(); List<String> classesRoots; Module firstModule = ContainerUtil.getFirstItem(modules); if (!defaultRoots.isEmpty()) { LOG.assertTrue(firstModule != null); classesRoots = new LocateLibraryDialog(firstModule, defaultRoots, descriptor.getPresentableName()).showAndGetResult(); } else { String version = descriptor.getMinVersion(); String mavenCoordinates = descriptor.getLibraryGroupId() + ":" + descriptor.getLibraryArtifactId() + (version != null ? ":" + version : ""); RepositoryAttachDialog dialog = new RepositoryAttachDialog(myProject, mavenCoordinates, RepositoryAttachDialog.Mode.DOWNLOAD); if (!dialog.showAndGet()) { return Promises.rejectedPromise(); } RepositoryLibraryProperties libraryProperties = new RepositoryLibraryProperties(dialog.getCoordinateText(), true); Collection<OrderRoot> roots = JarRepositoryManager.loadDependenciesModal(myProject, libraryProperties, dialog.getAttachSources(), dialog.getAttachJavaDoc(), null, null); if (roots.isEmpty()) { Messages.showErrorDialog(myProject, descriptor.getPresentableName() + " was not loaded.", "Failed to Download Library"); return Promises.rejectedPromise(); } classesRoots = roots.stream() .filter(root -> root.getType() == OrderRootType.CLASSES) .map(root -> PathUtil.getLocalPath(root.getFile())) .collect(Collectors.toList()); } if (!classesRoots.isEmpty()) { String libraryName = classesRoots.size() > 1 ? descriptor.getPresentableName() : null; final List<String> urls = OrderEntryFix.refreshAndConvertToUrls(classesRoots); if (modules.size() == 1) { ModuleRootModificationUtil.addModuleLibrary(firstModule, libraryName, urls, Collections.emptyList(), scope); } else { new WriteAction() { protected void run(@NotNull Result result) { Library library = LibraryUtil.createLibrary(LibraryTablesRegistrar.getInstance().getLibraryTable(myProject), descriptor.getPresentableName()); Library.ModifiableModel model = library.getModifiableModel(); for (String url : urls) { model.addRoot(url, OrderRootType.CLASSES); } model.commit(); for (Module module : modules) { ModuleRootModificationUtil.addDependency(module, library, scope, false); } } }.execute(); } } return Promises.resolvedPromise(null); } @Override public Promise<Void> changeLanguageLevel(@NotNull Module module, @NotNull LanguageLevel level) { final LanguageLevel moduleLevel = LanguageLevelModuleExtensionImpl.getInstance(module).getLanguageLevel(); if (moduleLevel != null && JavaSdkUtil.isLanguageLevelAcceptable(myProject, module, level)) { final ModifiableRootModel rootModel = ModuleRootManager.getInstance(module).getModifiableModel(); rootModel.getModuleExtension(LanguageLevelModuleExtension.class).setLanguageLevel(level); rootModel.commit(); } else { LanguageLevelProjectExtension.getInstance(myProject).setLanguageLevel(level); ProjectRootManagerEx.getInstanceEx(myProject).makeRootsChange(EmptyRunnable.INSTANCE, false, true); } return Promises.resolvedPromise(null); } }
copy downloaded files to the requested dir (IDEA-183740)
java/idea-ui/src/com/intellij/openapi/roots/impl/IdeaProjectModelModifier.java
copy downloaded files to the requested dir (IDEA-183740)
<ide><path>ava/idea-ui/src/com/intellij/openapi/roots/impl/IdeaProjectModelModifier.java <ide> <ide> RepositoryLibraryProperties libraryProperties = new RepositoryLibraryProperties(dialog.getCoordinateText(), true); <ide> Collection<OrderRoot> roots = <del> JarRepositoryManager.loadDependenciesModal(myProject, libraryProperties, dialog.getAttachSources(), dialog.getAttachJavaDoc(), null, null); <add> JarRepositoryManager.loadDependenciesModal(myProject, libraryProperties, dialog.getAttachSources(), dialog.getAttachJavaDoc(), dialog.getDirectoryPath(), null); <ide> if (roots.isEmpty()) { <ide> Messages.showErrorDialog(myProject, descriptor.getPresentableName() + " was not loaded.", "Failed to Download Library"); <ide> return Promises.rejectedPromise();
Java
lgpl-2.1
f7d377f02fc4bd55e946c5fa82ca03ddb7d6e5ea
0
levants/lightmare
package org.lightmare.jpa.datasource; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Properties; import java.util.Set; import javax.naming.Context; import javax.sql.DataSource; import org.lightmare.config.Configuration; import org.lightmare.jndi.JndiManager; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.reflect.MetaUtils; /** * Parses XML and property files to initialize and cache {@link DataSource} * objects * * @author levan * */ public class Initializer { // Caches already initialized data source file paths private static final Set<String> INITIALIZED_SOURCES = Collections .synchronizedSet(new HashSet<String>()); // Caches already initialized data source JNDI names private static final Set<String> INITIALIZED_NAMES = Collections .synchronizedSet(new HashSet<String>()); /** * Container for connection configuration properties * * @author levan * */ public static enum ConnectionConfig { DRIVER_PROPERTY("driver"), // driver USER_PROPERTY("user"), // user PASSWORD_PROPERTY("password"), // password URL_PROPERTY("url"), // URL JNDI_NAME_PROPERTY("jndiname"), // JNDI name NAME_PROPERTY("name");// name public String name; private ConnectionConfig(String name) { this.name = name; } } private Initializer() { } private static boolean checkForDataSource(String path) { return ObjectUtils.available(path); } public static String getJndiName(Properties properties) { String jndiName = properties .getProperty(ConnectionConfig.JNDI_NAME_PROPERTY.name); return jndiName; } /** * Loads jdbc driver class * * @param driver */ public static void initializeDriver(String driver) throws IOException { MetaUtils.initClassForName(driver); } /** * Initialized data source from passed file path * * @throws IOException */ public static void initializeDataSource(String path) throws IOException { boolean valid = checkForDataSource(path) && ObjectUtils.notTrue(Initializer.checkDSPath(path)); if (valid) { FileParsers parsers = new FileParsers(); parsers.parseStandaloneXml(path); } } /** * Initializes data sources from passed {@link Configuration} instance * * @throws IOException */ public static void initializeDataSources(Configuration config) throws IOException { Collection<String> paths = config.getDataSourcePath(); if (ObjectUtils.available(paths)) { for (String path : paths) { initializeDataSource(path); } } } /** * Initializes and registers {@link DataSource} object in JNDI by * {@link Properties} {@link Context} * * @param poolingProperties * @param dataSource * @param jndiName * @throws IOException */ public static void registerDataSource(Properties properties) throws IOException { InitDataSource initDataSource = InitDataSourceFactory.get(properties); initDataSource.create(); // Caches jndiName for data source String jndiName = getJndiName(properties); INITIALIZED_NAMES.add(jndiName); } public static void setDsAsInitialized(String datasourcePath) { INITIALIZED_SOURCES.add(datasourcePath); } public static void removeInitialized(String datasourcePath) { INITIALIZED_SOURCES.remove(datasourcePath); } public static boolean checkDSPath(String datasourcePath) { return INITIALIZED_SOURCES.contains(datasourcePath); } /** * Closes and removes from {@link Context} data source with specified JNDI * name * * @param jndiName * @throws IOException */ public static void close(String jndiName) throws IOException { JndiManager jndiManager = new JndiManager(); DataSource dataSource = jndiManager.lookup(jndiName); if (ObjectUtils.notNull(dataSource)) { cleanUp(dataSource); } dataSource = null; jndiManager.unbind(jndiName); INITIALIZED_NAMES.remove(jndiName); } /** * Closes and removes from {@link Context} all initialized and cached data * sources * * @throws IOException */ public static void closeAll() throws IOException { Set<String> dataSources = new HashSet<String>(INITIALIZED_NAMES); for (String jndiName : dataSources) { close(jndiName); } } /** * Closes and removes from {@link Context} all data sources from passed file * path * * @param dataSourcePath * @throws IOException */ public static void undeploy(String dataSourcePath) throws IOException { Collection<String> jndiNames = FileParsers .dataSourceNames(dataSourcePath); if (ObjectUtils.available(dataSourcePath)) { for (String jndiName : jndiNames) { close(jndiName); } } removeInitialized(dataSourcePath); } /** * Cleans and destroys passed {@link DataSource} instance * * @param dataSource */ public static void cleanUp(DataSource dataSource) { InitDataSourceFactory.destroy(dataSource); } }
src/main/java/org/lightmare/jpa/datasource/Initializer.java
package org.lightmare.jpa.datasource; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Properties; import java.util.Set; import javax.naming.Context; import javax.sql.DataSource; import org.lightmare.config.Configuration; import org.lightmare.jndi.JndiManager; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.reflect.MetaUtils; /** * Parses XML and property files to initialize and cache {@link DataSource} * objects * * @author levan * */ public class Initializer { // Caches already initialized data source file paths private static final Set<String> INITIALIZED_SOURCES = Collections .synchronizedSet(new HashSet<String>()); // Caches already initialized data source JNDI names private static final Set<String> INITIALIZED_NAMES = Collections .synchronizedSet(new HashSet<String>()); /** * Container for connection configuration properties * * @author levan * */ public static enum ConnectionConfig { DRIVER_PROPERTY("driver"), // driver USER_PROPERTY("user"), // user PASSWORD_PROPERTY("password"), // password URL_PROPERTY("url"), // URL JNDI_NAME_PROPERTY("jndiname"), // JNDI name NAME_PROPERTY("name");// name public String name; private ConnectionConfig(String name) { this.name = name; } } private Initializer() { } private static boolean checkForDataSource(String path) { return ObjectUtils.available(path); } public static String getJndiName(Properties properties) { String jndiName = properties .getProperty(ConnectionConfig.JNDI_NAME_PROPERTY.name); return jndiName; } /** * Loads jdbc driver class * * @param driver */ public static void initializeDriver(String driver) throws IOException { MetaUtils.initClassForName(driver); } /** * Initialized data source from passed file path * * @throws IOException */ public static void initializeDataSource(String path) throws IOException { boolean valid = checkForDataSource(path) && ObjectUtils.notTrue(Initializer.checkDSPath(path)); if (valid) { FileParsers parsers = new FileParsers(); parsers.parseStandaloneXml(path); } } /** * Initializes data sources from passed {@link Configuration} instance * * @throws IOException */ public static void initializeDataSources(Configuration config) throws IOException { Collection<String> paths = config.getDataSourcePath(); if (ObjectUtils.available(paths)) { for (String path : paths) { initializeDataSource(path); } } } /** * Initializes and registers {@link DataSource} object in jndi by * {@link Properties} {@link Context} * * @param poolingProperties * @param dataSource * @param jndiName * @throws IOException */ public static void registerDataSource(Properties properties) throws IOException { InitDataSource initDataSource = InitDataSourceFactory.get(properties); initDataSource.create(); // Caches jndiName for data source String jndiName = getJndiName(properties); INITIALIZED_NAMES.add(jndiName); } public static void setDsAsInitialized(String datasourcePath) { INITIALIZED_SOURCES.add(datasourcePath); } public static void removeInitialized(String datasourcePath) { INITIALIZED_SOURCES.remove(datasourcePath); } public static boolean checkDSPath(String datasourcePath) { return INITIALIZED_SOURCES.contains(datasourcePath); } /** * Closes and removes from {@link Context} data source with specified JNDI * name * * @param jndiName * @throws IOException */ public static void close(String jndiName) throws IOException { JndiManager jndiManager = new JndiManager(); DataSource dataSource = jndiManager.lookup(jndiName); if (ObjectUtils.notNull(dataSource)) { cleanUp(dataSource); } dataSource = null; jndiManager.unbind(jndiName); INITIALIZED_NAMES.remove(jndiName); } /** * Closes and removes from {@link Context} all initialized and cached data * sources * * @throws IOException */ public static void closeAll() throws IOException { Set<String> dataSources = new HashSet<String>(INITIALIZED_NAMES); for (String jndiName : dataSources) { close(jndiName); } } /** * Closes and removes from {@link Context} all data sources from passed file * path * * @param dataSourcePath * @throws IOException */ public static void undeploy(String dataSourcePath) throws IOException { Collection<String> jndiNames = FileParsers .dataSourceNames(dataSourcePath); if (ObjectUtils.available(dataSourcePath)) { for (String jndiName : jndiNames) { close(jndiName); } } removeInitialized(dataSourcePath); } /** * Cleans and destroys passed {@link DataSource} instance * * @param dataSource */ public static void cleanUp(DataSource dataSource) { InitDataSourceFactory.destroy(dataSource); } }
improved naming (JNDI) utilities
src/main/java/org/lightmare/jpa/datasource/Initializer.java
improved naming (JNDI) utilities
<ide><path>rc/main/java/org/lightmare/jpa/datasource/Initializer.java <ide> } <ide> <ide> /** <del> * Initializes and registers {@link DataSource} object in jndi by <add> * Initializes and registers {@link DataSource} object in JNDI by <ide> * {@link Properties} {@link Context} <ide> * <ide> * @param poolingProperties
Java
apache-2.0
00fd1c3c4bf07baa07c4706a34f8b535812321bd
0
TouK/sonar-file-alerts-plugin
package pl.touk.sonar; import com.google.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.batch.*; import org.sonar.api.config.Settings; import org.sonar.api.i18n.I18n; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.measures.Measure; import org.sonar.api.measures.Metric; import org.sonar.api.profiles.Alert; import org.sonar.api.profiles.RulesProfile; import org.sonar.api.resources.Project; import org.sonar.api.resources.Resource; import org.sonar.api.resources.ResourceUtils; import java.util.List; import java.util.Locale; /** * This decorator is mainly a copy-paste of CheckAlertThresholds, because it contained most private methods. * Periods are removed, because it is not available in this API. * https://github.com/SonarSource/sonar/blob/master/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/sensors/CheckAlertThresholds.java?source=c */ public class FileAlertDecorator implements Decorator { private static final Logger LOG = LoggerFactory.getLogger(FileAlertDecorator.class); private static final String VARIATION_METRIC_PREFIX = "new_"; private static final String VARIATION = "variation"; private RulesProfile profile; private I18n i18n; private boolean enabled; public FileAlertDecorator(Settings settings, RulesProfile profile, I18n i18n) { this.enabled = settings.getBoolean(PropertyKey.FILE_ALERTS_ENABLED); this.profile = profile; this.i18n = i18n; } @DependedUpon public Metric generatesAlertStatus() { return CoreMetrics.ALERT_STATUS; } @DependsUpon public String dependsOnVariations() { return DecoratorBarriers.END_OF_TIME_MACHINE; } @DependsUpon public List<Metric> dependsUponMetrics() { List<Metric> metrics = Lists.newLinkedList(); for (Alert alert : profile.getAlerts()) { metrics.add(alert.getMetric()); } return metrics; } public boolean shouldExecuteOnProject(Project project) { return enabled && profile != null && profile.getAlerts() != null && profile.getAlerts().size() > 0; } public void decorate(final Resource resource, final DecoratorContext context) { if (shouldDecorateResource(resource)) { decorateResource(context); } } private void decorateResource(DecoratorContext context) { for (final Alert alert : profile.getAlerts()) { Measure measure = context.getMeasure(alert.getMetric()); if (measure == null) { return; } Metric.Level level = AlertUtils.getLevel(alert, measure); if (level == Metric.Level.OK) { return; } LOG.info("Alert raised on file {}: {} with level {}", context.getResource(), alert.getMetric().getName(), level); measure.setAlertStatus(level); measure.setAlertText(getText(alert, level)); context.saveMeasure(measure); } } private boolean shouldDecorateResource(final Resource resource) { return ResourceUtils.isFile(resource); } private String getText(Alert alert, Metric.Level level) { if (level == Metric.Level.OK) { return null; } return getAlertLabel(alert, level); } private String getAlertLabel(Alert alert, Metric.Level level) { Integer alertPeriod = alert.getPeriod(); String metric = i18n.message(getLocale(), "metric." + alert.getMetric().getKey() + ".name", alert.getMetric().getName()); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(metric); if (alertPeriod != null && !alert.getMetric().getKey().startsWith(VARIATION_METRIC_PREFIX)) { String variation = i18n.message(getLocale(), VARIATION, VARIATION).toLowerCase(); stringBuilder.append(" ").append(variation); } stringBuilder .append(" ").append(alert.getOperator()).append(" ") .append(level.equals(Metric.Level.ERROR) ? alert.getValueError() : alert.getValueWarning()); // if (alertPeriod != null) { // stringBuilder.append(" ").append(periods.label(snapshot, alertPeriod)); // } return stringBuilder.toString(); } @Override public String toString() { return getClass().getSimpleName(); } private Locale getLocale() { return Locale.ENGLISH; } }
src/main/java/pl/touk/sonar/FileAlertDecorator.java
package pl.touk.sonar; import com.google.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.batch.*; import org.sonar.api.config.Settings; import org.sonar.api.i18n.I18n; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.measures.Measure; import org.sonar.api.measures.Metric; import org.sonar.api.profiles.Alert; import org.sonar.api.profiles.RulesProfile; import org.sonar.api.resources.Project; import org.sonar.api.resources.Resource; import org.sonar.api.resources.ResourceUtils; import java.util.List; import java.util.Locale; /** * This decorator is mainly a copy-paste of CheckAlertThresholds, because it contained most private methods. * Periods are removed, because it is not available in this API. * https://github.com/SonarSource/sonar/blob/master/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/sensors/CheckAlertThresholds.java?source=c */ public class FileAlertDecorator implements Decorator { private static final Logger LOG = LoggerFactory.getLogger(FileAlertDecorator.class); private static final String VARIATION_METRIC_PREFIX = "new_"; private static final String VARIATION = "variation"; private RulesProfile profile; private I18n i18n; private boolean enabled; public FileAlertDecorator(Settings settings, RulesProfile profile, I18n i18n) { this.enabled = settings.getBoolean(PropertyKey.FILE_ALERTS_ENABLED); this.profile = profile; this.i18n = i18n; } @DependedUpon public Metric generatesAlertStatus() { return CoreMetrics.ALERT_STATUS; } @DependsUpon public String dependsOnVariations() { return DecoratorBarriers.END_OF_TIME_MACHINE; } @DependsUpon public List<Metric> dependsUponMetrics() { List<Metric> metrics = Lists.newLinkedList(); for (Alert alert : profile.getAlerts()) { metrics.add(alert.getMetric()); } return metrics; } public boolean shouldExecuteOnProject(Project project) { return enabled && profile != null && profile.getAlerts() != null && profile.getAlerts().size() > 0; } public void decorate(final Resource resource, final DecoratorContext context) { if (shouldDecorateResource(resource)) { decorateResource(context); } } private void decorateResource(DecoratorContext context) { LOG.info("Decoration on resource {}", context.getResource()); for (final Alert alert : profile.getAlerts()) { Measure measure = context.getMeasure(alert.getMetric()); if (measure == null) { return; } Metric.Level level = AlertUtils.getLevel(alert, measure); LOG.info("Alert raised on file {}: {} with level {}", context.getResource(), alert.getMetric().getName(), level); if (level == Metric.Level.OK) { return; } measure.setAlertStatus(level); measure.setAlertText(getText(alert, level)); context.saveMeasure(measure); } } private boolean shouldDecorateResource(final Resource resource) { return ResourceUtils.isFile(resource); } private String getText(Alert alert, Metric.Level level) { if (level == Metric.Level.OK) { return null; } return getAlertLabel(alert, level); } private String getAlertLabel(Alert alert, Metric.Level level) { Integer alertPeriod = alert.getPeriod(); String metric = i18n.message(getLocale(), "metric." + alert.getMetric().getKey() + ".name", alert.getMetric().getName()); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(metric); if (alertPeriod != null && !alert.getMetric().getKey().startsWith(VARIATION_METRIC_PREFIX)) { String variation = i18n.message(getLocale(), VARIATION, VARIATION).toLowerCase(); stringBuilder.append(" ").append(variation); } stringBuilder .append(" ").append(alert.getOperator()).append(" ") .append(level.equals(Metric.Level.ERROR) ? alert.getValueError() : alert.getValueWarning()); // if (alertPeriod != null) { // stringBuilder.append(" ").append(periods.label(snapshot, alertPeriod)); // } return stringBuilder.toString(); } @Override public String toString() { return getClass().getSimpleName(); } private Locale getLocale() { return Locale.ENGLISH; } }
Decrease logging.
src/main/java/pl/touk/sonar/FileAlertDecorator.java
Decrease logging.
<ide><path>rc/main/java/pl/touk/sonar/FileAlertDecorator.java <ide> } <ide> <ide> private void decorateResource(DecoratorContext context) { <del> LOG.info("Decoration on resource {}", context.getResource()); <ide> for (final Alert alert : profile.getAlerts()) { <ide> Measure measure = context.getMeasure(alert.getMetric()); <ide> if (measure == null) { <ide> } <ide> <ide> Metric.Level level = AlertUtils.getLevel(alert, measure); <del> LOG.info("Alert raised on file {}: {} with level {}", context.getResource(), alert.getMetric().getName(), level); <ide> if (level == Metric.Level.OK) { <ide> return; <ide> } <ide> <add> LOG.info("Alert raised on file {}: {} with level {}", context.getResource(), alert.getMetric().getName(), level); <ide> measure.setAlertStatus(level); <ide> measure.setAlertText(getText(alert, level)); <ide> context.saveMeasure(measure);
Java
apache-2.0
257905c1425df2bde33007e26ff5938f2129822f
0
greese/dasein-cloud-aws,drewlyall/dasein-cloud-aws,jeffrey-yan/dasein-cloud-aws,dasein-cloud/dasein-cloud-aws,daniellemayne/dasein-cloud-aws_old,maksimov/dasein-cloud-aws,daniellemayne/dasein-cloud-aws,maksimov/dasein-cloud-aws-old
/** * Copyright (C) 2009-2014 Dell, Inc. * See annotations for authorship information * * ==================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ package org.dasein.cloud.aws.compute; import org.apache.log4j.Logger; import org.dasein.cloud.*; import org.dasein.cloud.aws.AWSCloud; import org.dasein.cloud.compute.*; import org.dasein.cloud.identity.ServiceAction; import org.dasein.cloud.util.APITrace; import org.dasein.util.Jiterator; import org.dasein.util.JiteratorPopulator; import org.dasein.util.PopulatorThread; import org.dasein.util.uom.storage.Gigabyte; import org.dasein.util.uom.storage.Storage; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.UnsupportedEncodingException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; public class AutoScaling extends AbstractAutoScalingSupport { static private final Logger logger = Logger.getLogger(AutoScaling.class); private AWSCloud provider = null; AutoScaling(AWSCloud provider) { super(provider); this.provider = provider; } @Override public String createAutoScalingGroup(@Nonnull AutoScalingGroupOptions autoScalingGroupOptions) throws InternalException, CloudException { APITrace.begin(provider, "AutoScaling.createAutoScalingGroup"); try { Map<String, String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.CREATE_AUTO_SCALING_GROUP); EC2Method method; int minServers = autoScalingGroupOptions.getMinServers(); if (minServers < 0) { minServers = 0; } int maxServers = autoScalingGroupOptions.getMaxServers(); if (maxServers < minServers) { maxServers = minServers; } parameters.put("AutoScalingGroupName", autoScalingGroupOptions.getName()); parameters.put("LaunchConfigurationName", autoScalingGroupOptions.getLaunchConfigurationId()); parameters.put("MinSize", String.valueOf(minServers)); parameters.put("MaxSize", String.valueOf(maxServers)); if (autoScalingGroupOptions.getCooldown() != null) { parameters.put("DefaultCooldown", String.valueOf(autoScalingGroupOptions.getCooldown())); } if (autoScalingGroupOptions.getDesiredCapacity() != null) { parameters.put("DesiredCapacity", String.valueOf(autoScalingGroupOptions.getDesiredCapacity())); } if (autoScalingGroupOptions.getHealthCheckGracePeriod() != null) { parameters.put("HealthCheckGracePeriod", String.valueOf(autoScalingGroupOptions.getHealthCheckGracePeriod())); } if (autoScalingGroupOptions.getHealthCheckType() != null) { parameters.put("HealthCheckType", autoScalingGroupOptions.getHealthCheckType()); } if (autoScalingGroupOptions.getProviderSubnetIds() != null) { StringBuilder vpcZones = new StringBuilder(); int i = 0; for (String subnetId : autoScalingGroupOptions.getProviderSubnetIds()) { if (i > 0) { vpcZones.append(","); } vpcZones.append(subnetId); i++; } parameters.put("VPCZoneIdentifier", vpcZones.toString()); } if (autoScalingGroupOptions.getProviderDataCenterIds() != null) { int i = 1; for (String zoneId : autoScalingGroupOptions.getProviderDataCenterIds()) { parameters.put("AvailabilityZones.member." + (i++), zoneId); } } if (autoScalingGroupOptions.getProviderLoadBalancerIds() != null) { int i = 1; for (String lbId : autoScalingGroupOptions.getProviderLoadBalancerIds()) { parameters.put("LoadBalancerNames.member." + (i++), lbId); } } if (autoScalingGroupOptions.getTags() != null) { int i = 1; for (AutoScalingTag tag : autoScalingGroupOptions.getTags()) { parameters.put("Tags.member." + i + ".Key", tag.getKey()); parameters.put("Tags.member." + i + ".Value", tag.getValue()); parameters.put("Tags.member." + i + ".PropagateAtLaunch", String.valueOf(tag.isPropagateAtLaunch())); i++; } } method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { method.invoke(); } catch (EC2Exception e) { logger.error(e.getSummary()); throw new CloudException(e); } return autoScalingGroupOptions.getName(); } finally { APITrace.end(); } } @Override public String createAutoScalingGroup(@Nonnull String name, @Nonnull String launchConfigurationId, @Nonnull Integer minServers, @Nonnull Integer maxServers, @Nullable Integer cooldown, @Nullable String[] loadBalancerIds, @Nullable Integer desiredCapacity, @Nullable Integer healthCheckGracePeriod, @Nullable String healthCheckType, @Nullable String vpcZones, @Nullable String... zoneIds) throws InternalException, CloudException { AutoScalingGroupOptions options = new AutoScalingGroupOptions(name) .withLaunchConfigurationId(launchConfigurationId) .withMinServers(minServers) .withMaxServers(maxServers) .withCooldown(cooldown) .withProviderLoadBalancerIds(loadBalancerIds) .withDesiredCapacity(desiredCapacity) .withHealthCheckGracePeriod(healthCheckGracePeriod) .withHealthCheckType(healthCheckType) .withProviderSubnetIds(vpcZones != null ? vpcZones.split(",") : new String[]{}) .withProviderDataCenterIds(zoneIds); return createAutoScalingGroup(options); } @Override public void updateAutoScalingGroup(@Nonnull String scalingGroupId, @Nullable String launchConfigurationId, @Nonnegative Integer minServers, @Nonnegative Integer maxServers, @Nullable Integer cooldown, @Nullable Integer desiredCapacity, @Nullable Integer healthCheckGracePeriod, @Nullable String healthCheckType, @Nullable String vpcZones, @Nullable String ... zoneIds) throws InternalException, CloudException { APITrace.begin(provider, "AutoScaling.updateAutoScalingGroup"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.UPDATE_AUTO_SCALING_GROUP); EC2Method method; if(scalingGroupId != null) { parameters.put("AutoScalingGroupName", scalingGroupId); } if(launchConfigurationId != null) { parameters.put("LaunchConfigurationName", launchConfigurationId); } if(minServers != null) { if( minServers < 0 ) { minServers = 0; } parameters.put("MinSize", String.valueOf(minServers)); } if(maxServers != null) { if( minServers != null && maxServers < minServers ) { maxServers = minServers; } parameters.put("MaxSize", String.valueOf(maxServers)); } if(cooldown != null) { parameters.put("DefaultCooldown", String.valueOf(cooldown)); } if(desiredCapacity != null) { parameters.put("DesiredCapacity", String.valueOf(desiredCapacity)); } if(healthCheckGracePeriod != null) { parameters.put("HealthCheckGracePeriod", String.valueOf(healthCheckGracePeriod)); } if(healthCheckType != null) { parameters.put("HealthCheckType", healthCheckType); } if(vpcZones != null) { parameters.put("VPCZoneIdentifier", vpcZones); } if(zoneIds != null) { int i = 1; for( String zoneId : zoneIds ) { parameters.put("AvailabilityZones.member." + (i++), zoneId); } } method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } } finally { APITrace.end(); } } @Override public String createLaunchConfiguration(String name, String imageId, VirtualMachineProduct size, String keyPairName, String userData, String providerRoleId, Boolean detailedMonitoring, String ... firewalls) throws InternalException, CloudException { return createLaunchConfiguration(new LaunchConfigurationCreateOptions(name, imageId, size, keyPairName, userData, providerRoleId, detailedMonitoring, firewalls)); } @Override public String createLaunchConfiguration(@Nonnull LaunchConfigurationCreateOptions options) throws InternalException, CloudException { APITrace.begin(provider, "AutoScaling.createLaunchConfigursation"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.CREATE_LAUNCH_CONFIGURATION); EC2Method method; parameters.put("LaunchConfigurationName", options.getName()); if(options.getImageId() != null) { parameters.put("ImageId", options.getImageId()); } if(options.getKeypairName() != null) { parameters.put("KeyName", options.getKeypairName()); } if(options.getUserData() != null) { parameters.put("UserData", options.getUserData()); } if(options.getProviderRoleId() != null) { parameters.put("IamInstanceProfile", options.getProviderRoleId()); } if(options.getDetailedMonitoring() != null) { parameters.put("InstanceMonitoring.Enabled", options.getDetailedMonitoring().toString()); } if(options.getSize() != null) { parameters.put("InstanceType", options.getSize().getProviderProductId()); } int i = 1; if( options.getFirewallIds() != null ) { for (String fw : options.getFirewallIds()) { parameters.put("SecurityGroups.member." + (i++), fw); } } if(options.getAssociatePublicIPAddress() != null) { parameters.put("AssociatePublicIpAddress", options.getAssociatePublicIPAddress().toString()); } if(options.getIOOptimized() != null) { parameters.put("EbsOptimized", options.getIOOptimized().toString()); } if( options.getVolumeAttachment() != null ) { int z = 1; for( VolumeAttachment va : options.getVolumeAttachment() ) { parameters.put("BlockDeviceMappings.member." + z + ".DeviceName", va.deviceId); EBSVolume ebsv = new EBSVolume( provider ); String volType = null; try { VolumeProduct prd = ebsv.getVolumeProduct( va.volumeToCreate.getVolumeProductId() ); volType = prd.getProviderProductId(); } catch ( Exception e ) { // toss it } if( volType == null ) { if( options.getIOOptimized() && va.volumeToCreate.getIops() > 0 ) { parameters.put("BlockDeviceMappings.member." + z + ".Ebs.VolumeType", "io1"); } } else { parameters.put("BlockDeviceMappings.member." + z + ".Ebs.VolumeType", volType); } if(va.volumeToCreate.getIops() > 0) { parameters.put("BlockDeviceMappings.member." + z + ".Ebs.Iops", String.valueOf(va.volumeToCreate.getIops())); } if(va.volumeToCreate.getSnapshotId() != null) { parameters.put("BlockDeviceMappings.member." + z + ".Ebs.SnapshotId", va.volumeToCreate.getSnapshotId()); } if(va.volumeToCreate.getVolumeSize().getQuantity().intValue() > 0) { parameters.put("BlockDeviceMappings.member." + z + ".Ebs.VolumeSize", String.valueOf(va.volumeToCreate.getVolumeSize().getQuantity().intValue())); } z++; } } if(options.getVirtualMachineIdToClone() != null) { parameters.put("InstanceId", options.getVirtualMachineIdToClone()); } method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } return options.getName(); } finally { APITrace.end(); } } @Override public void deleteAutoScalingGroup(String providerAutoScalingGroupId) throws InternalException, CloudException { deleteAutoScalingGroup( new AutoScalingGroupDeleteOptions( providerAutoScalingGroupId ) ); } @Override public void deleteAutoScalingGroup( @Nonnull AutoScalingGroupDeleteOptions options ) throws InternalException, CloudException { APITrace.begin(provider, "AutoScaling.deleteAutoScalingGroup"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DELETE_AUTO_SCALING_GROUP); EC2Method method; parameters.put( "AutoScalingGroupName", options.getProviderAutoScalingGroupId() ); parameters.put( "ForceDelete", options.getForceDelete().toString() ); method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } } finally { APITrace.end(); } } @Override public void deleteLaunchConfiguration(String providerLaunchConfigurationId) throws InternalException, CloudException { APITrace.begin(provider, "AutoScaling.deleteLaunchConfiguration"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DELETE_LAUNCH_CONFIGURATION); EC2Method method; parameters.put("LaunchConfigurationName", providerLaunchConfigurationId); method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } } finally { APITrace.end(); } } @Override public String setTrigger(String name, String scalingGroupId, String statistic, String unitOfMeasure, String metric, int periodInSeconds, double lowerThreshold, double upperThreshold, int lowerIncrement, boolean lowerIncrementAbsolute, int upperIncrement, boolean upperIncrementAbsolute, int breachDuration) throws InternalException, CloudException { APITrace.begin(provider, "AutoScaling.setTrigger"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.CREATE_OR_UPDATE_SCALING_TRIGGER); EC2Method method; parameters.put("AutoScalingGroupName", scalingGroupId); parameters.put("MeasureName", metric); parameters.put("Period", String.valueOf(periodInSeconds)); parameters.put("LowerThreshold", String.valueOf(lowerThreshold)); parameters.put("UpperThreshold", String.valueOf(upperThreshold)); parameters.put("UpperBreachScaleIncrement", String.valueOf(upperIncrement)); parameters.put("LowerBreachScaleIncrement", String.valueOf(lowerIncrement)); parameters.put("BreachDuration", String.valueOf(breachDuration)); parameters.put("TriggerName", name); parameters.put("Unit", unitOfMeasure); parameters.put("Statistic", statistic); parameters.put("Dimensions.member.1.Name", "AutoScalingGroupName"); parameters.put("Dimensions.member.1.Value", scalingGroupId); method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } return name; } finally { APITrace.end(); } } private Map<String,String> getAutoScalingParameters(ProviderContext ctx, String action) throws InternalException { APITrace.begin(provider, "AutoScaling.getAutoScalingParameters"); try { HashMap<String,String> parameters = new HashMap<String,String>(); parameters.put(AWSCloud.P_ACTION, action); parameters.put(AWSCloud.P_SIGNATURE_VERSION, AWSCloud.SIGNATURE); try { parameters.put(AWSCloud.P_ACCESS, new String(ctx.getAccessPublic(), "utf-8")); } catch( UnsupportedEncodingException e ) { logger.error(e); e.printStackTrace(); throw new InternalException(e); } parameters.put(AWSCloud.P_SIGNATURE_METHOD, AWSCloud.EC2_ALGORITHM); parameters.put(AWSCloud.P_TIMESTAMP, provider.getTimestamp(System.currentTimeMillis(), true)); parameters.put(AWSCloud.P_VERSION, provider.getAutoScaleVersion()); return parameters; } finally { APITrace.end(); } } private String getAutoScalingUrl() throws CloudException { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context has been set for this request"); } return "https://autoscaling." + ctx.getRegionId() + ".amazonaws.com"; } @Override public LaunchConfiguration getLaunchConfiguration(String providerLaunchConfigurationId) throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.getLaunchConfiguration"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DESCRIBE_LAUNCH_CONFIGURATIONS); EC2Method method; NodeList blocks; Document doc; parameters.put("LaunchConfigurationNames.member.1", providerLaunchConfigurationId); method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { doc = method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } blocks = doc.getElementsByTagName("LaunchConfigurations"); for( int i=0; i<blocks.getLength(); i++ ) { NodeList items = blocks.item(i).getChildNodes(); for( int j=0; j<items.getLength(); j++ ) { Node item = items.item(j); if( item.getNodeName().equals("member") ) { LaunchConfiguration cfg = toLaunchConfiguration(item); if( cfg != null ) { return cfg; } } } } return null; } finally { APITrace.end(); } } @Override public ScalingGroup getScalingGroup(String providerScalingGroupId) throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.getScalingGroup"); try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context has been set for this request"); } Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DESCRIBE_AUTO_SCALING_GROUPS); EC2Method method; NodeList blocks; Document doc; parameters.put("AutoScalingGroupNames.member.1", providerScalingGroupId); method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { doc = method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } blocks = doc.getElementsByTagName("AutoScalingGroups"); for( int i=0; i<blocks.getLength(); i++ ) { NodeList members = blocks.item(i).getChildNodes(); for( int j=0; j<members.getLength(); j++ ) { Node item = members.item(j); if( item.getNodeName().equals("member") ) { ScalingGroup group = toScalingGroup(ctx, item); if( group != null ) { return group; } } } } return null; } finally { APITrace.end(); } } @Override public boolean isSubscribed() throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.isSubscribed"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DESCRIBE_AUTO_SCALING_GROUPS); EC2Method method; method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { method.invoke(); return true; } catch( EC2Exception e ) { String msg = e.getSummary(); if( msg != null && msg.contains("not able to validate the provided access credentials") ) { return false; } logger.error("AWS Error checking subscription: " + e.getCode() + "/" + e.getSummary()); if( logger.isDebugEnabled() ) { e.printStackTrace(); } throw new CloudException(e); } } finally { APITrace.end(); } } @Override public void suspendAutoScaling(String providerScalingGroupId, String[] processesToSuspend) throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.suspendAutoScaling"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.SUSPEND_AUTO_SCALING_GROUP); EC2Method method; parameters.put("AutoScalingGroupName", providerScalingGroupId); int x = 1; if(processesToSuspend != null) { for( String process : processesToSuspend ) { parameters.put("ScalingProcesses.member." + (x++), process); } } method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } } finally { APITrace.end(); } } @Override public void resumeAutoScaling(String providerScalingGroupId, String[] processesToResume) throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.resumeAutoScaling"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.RESUME_AUTO_SCALING_GROUP); EC2Method method; parameters.put("AutoScalingGroupName", providerScalingGroupId); int x = 1; if(processesToResume != null) { for( String process : processesToResume ) { parameters.put("ScalingProcesses.member." + (x++), process); } } method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } } finally { APITrace.end(); } } @Override public String updateScalingPolicy(String policyName, String adjustmentType, String autoScalingGroupName, Integer cooldown, Integer minAdjustmentStep, Integer scalingAdjustment) throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.updateScalingPolicy"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.PUT_SCALING_POLICY); EC2Method method; NodeList blocks; Document doc; parameters.put("PolicyName", policyName); parameters.put("AdjustmentType", adjustmentType); parameters.put("AutoScalingGroupName", autoScalingGroupName); if(cooldown != null){ parameters.put("Cooldown", String.valueOf(cooldown)); } if(minAdjustmentStep != null){ parameters.put("MinAdjustmentStep", String.valueOf(minAdjustmentStep)); } parameters.put("ScalingAdjustment", String.valueOf(scalingAdjustment)); method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { doc = method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } blocks = doc.getElementsByTagName("PolicyARN"); if( blocks.getLength() > 0 ) { return blocks.item(0).getFirstChild().getNodeValue().trim(); } throw new CloudException("Successful POST, but no Policy information was provided"); } finally { APITrace.end(); } } @Override public void deleteScalingPolicy(@Nonnull String policyName, @Nullable String autoScalingGroupName) throws InternalException, CloudException { APITrace.begin(provider, "AutoScaling.deleteScalingPolicy"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DELETE_SCALING_POLICY); EC2Method method; parameters.put("PolicyName", policyName); if(autoScalingGroupName != null) { parameters.put("AutoScalingGroupName", autoScalingGroupName); } method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } } finally { APITrace.end(); } } @Override public Collection<ScalingPolicy> listScalingPolicies(@Nullable String autoScalingGroupName) throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.getScalingPolicies"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DESCRIBE_SCALING_POLICIES); ArrayList<ScalingPolicy> list = new ArrayList<ScalingPolicy>(); EC2Method method; NodeList blocks; Document doc; if(autoScalingGroupName != null) { parameters.put("AutoScalingGroupName", autoScalingGroupName); } method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { doc = method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } blocks = doc.getElementsByTagName("ScalingPolicies"); for( int i=0; i<blocks.getLength(); i++ ) { NodeList items = blocks.item(i).getChildNodes(); for( int j=0; j<items.getLength(); j++ ) { Node item = items.item(j); if( item.getNodeName().equals("member") ) { ScalingPolicy sp = toScalingPolicy(item); if( sp != null ) { list.add(sp); } } } } return list; } finally { APITrace.end(); } } @Override public ScalingPolicy getScalingPolicy(@Nonnull String policyName) throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.getScalingPolicy"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DESCRIBE_SCALING_POLICIES); EC2Method method; NodeList blocks; Document doc; parameters.put("PolicyNames.member.1", policyName); method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { doc = method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } ScalingPolicy sp = null; blocks = doc.getElementsByTagName("ScalingPolicies"); for( int i=0; i<blocks.getLength(); i++ ) { NodeList items = blocks.item(i).getChildNodes(); for( int j=0; j<items.getLength(); j++ ) { Node item = items.item(j); if( item.getNodeName().equals("member") ) { sp = toScalingPolicy(item); return sp; } } } return sp; } finally { APITrace.end(); } } @Override public @Nonnull Iterable<ResourceStatus> listLaunchConfigurationStatus() throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.listLaunchConfigurationStatus"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DESCRIBE_LAUNCH_CONFIGURATIONS); ArrayList<ResourceStatus> list = new ArrayList<ResourceStatus>(); EC2Method method; NodeList blocks; Document doc; method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { doc = method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } blocks = doc.getElementsByTagName("LaunchConfigurations"); for( int i=0; i<blocks.getLength(); i++ ) { NodeList items = blocks.item(i).getChildNodes(); for( int j=0; j<items.getLength(); j++ ) { Node item = items.item(j); if( item.getNodeName().equals("member") ) { ResourceStatus status = toLCStatus(item); if( status != null ) { list.add(status); } } } } return list; } finally { APITrace.end(); } } @Override public Collection<LaunchConfiguration> listLaunchConfigurations() throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.listLaunchConfigurations"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DESCRIBE_LAUNCH_CONFIGURATIONS); ArrayList<LaunchConfiguration> list = new ArrayList<LaunchConfiguration>(); EC2Method method; NodeList blocks; Document doc; method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { doc = method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } blocks = doc.getElementsByTagName("LaunchConfigurations"); for( int i=0; i<blocks.getLength(); i++ ) { NodeList items = blocks.item(i).getChildNodes(); for( int j=0; j<items.getLength(); j++ ) { Node item = items.item(j); if( item.getNodeName().equals("member") ) { LaunchConfiguration cfg = toLaunchConfiguration(item); if( cfg != null ) { list.add(cfg); } } } } return list; } finally { APITrace.end(); } } @Override public Iterable<ResourceStatus> listScalingGroupStatus() throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.listScalingGroupStatus"); try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context has been set for this request"); } ArrayList<ResourceStatus> list = new ArrayList<ResourceStatus>(); Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DESCRIBE_AUTO_SCALING_GROUPS); EC2Method method; NodeList blocks; Document doc; method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { doc = method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } blocks = doc.getElementsByTagName("AutoScalingGroups"); for( int i=0; i<blocks.getLength(); i++ ) { NodeList items = blocks.item(i).getChildNodes(); for( int j=0; j<items.getLength(); j++ ) { Node item = items.item(j); if( item.getNodeName().equals("member") ) { ResourceStatus status = toGroupStatus(item); if( status != null ) { list.add(status); } } } } return list; } finally { APITrace.end(); } } /** * Provides backwards compatibility */ @Override public Collection<ScalingGroup> listScalingGroups() throws CloudException, InternalException { return listScalingGroups(AutoScalingGroupFilterOptions.getInstance()); } /** * Returns filtered list of auto scaling groups. * * @param options the filter parameters * @return filtered list of scaling groups */ @Override public Collection<ScalingGroup> listScalingGroups(AutoScalingGroupFilterOptions options) throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.listScalingGroups"); try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context has been set for this request"); } ArrayList<ScalingGroup> list = new ArrayList<ScalingGroup>(); Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DESCRIBE_AUTO_SCALING_GROUPS); EC2Method method; NodeList blocks; Document doc; method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { doc = method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } blocks = doc.getElementsByTagName("AutoScalingGroups"); for( int i=0; i<blocks.getLength(); i++ ) { NodeList items = blocks.item(i).getChildNodes(); for( int j=0; j<items.getLength(); j++ ) { Node item = items.item(j); if( item.getNodeName().equals("member") ) { ScalingGroup group = toScalingGroup(ctx, item); if( (group != null && (options != null && !options.hasCriteria())) || (group != null && (options != null && options.hasCriteria() && options.matches(group))) ) { list.add(group); } } } } return list; } finally { APITrace.end(); } } @Override public @Nonnull String[] mapServiceAction(@Nonnull ServiceAction action) { if( action.equals(AutoScalingSupport.ANY) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + "*" }; } if( action.equals(AutoScalingSupport.CREATE_LAUNCH_CONFIGURATION) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.CREATE_LAUNCH_CONFIGURATION }; } else if( action.equals(AutoScalingSupport.CREATE_SCALING_GROUP) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.CREATE_AUTO_SCALING_GROUP }; } else if( action.equals(AutoScalingSupport.GET_LAUNCH_CONFIGURATION) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.DESCRIBE_LAUNCH_CONFIGURATIONS }; } else if( action.equals(AutoScalingSupport.GET_SCALING_GROUP) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.DESCRIBE_AUTO_SCALING_GROUPS }; } else if( action.equals(AutoScalingSupport.LIST_LAUNCH_CONFIGURATION) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.DESCRIBE_LAUNCH_CONFIGURATIONS }; } else if( action.equals(AutoScalingSupport.LIST_SCALING_GROUP) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.DESCRIBE_AUTO_SCALING_GROUPS }; } else if( action.equals(AutoScalingSupport.REMOVE_LAUNCH_CONFIGURATION) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.DELETE_LAUNCH_CONFIGURATION }; } else if( action.equals(AutoScalingSupport.REMOVE_SCALING_GROUP) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.DELETE_AUTO_SCALING_GROUP }; } else if( action.equals(AutoScalingSupport.SET_CAPACITY) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.SET_DESIRED_CAPACITY }; } else if( action.equals(AutoScalingSupport.SET_SCALING_TRIGGER) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.CREATE_OR_UPDATE_SCALING_TRIGGER }; } else if( action.equals(AutoScalingSupport.UPDATE_SCALING_GROUP) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.UPDATE_AUTO_SCALING_GROUP }; } else if( action.equals(AutoScalingSupport.SUSPEND_AUTO_SCALING_GROUP) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.SUSPEND_AUTO_SCALING_GROUP }; } else if( action.equals(AutoScalingSupport.RESUME_AUTO_SCALING_GROUP) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.RESUME_AUTO_SCALING_GROUP }; } else if( action.equals(AutoScalingSupport.PUT_SCALING_POLICY) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.PUT_SCALING_POLICY }; } else if( action.equals(AutoScalingSupport.DELETE_SCALING_POLICY) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.DELETE_SCALING_POLICY }; } else if( action.equals(AutoScalingSupport.LIST_SCALING_POLICIES) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.DESCRIBE_SCALING_POLICIES }; } return new String[0]; } @Override public void setDesiredCapacity(String scalingGroupId, int capacity) throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.setDesiredCapacity"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.SET_DESIRED_CAPACITY); EC2Method method; parameters.put("AutoScalingGroupName", scalingGroupId); parameters.put("DesiredCapacity", String.valueOf(capacity)); method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } } finally { APITrace.end(); } } @Override public void updateTags( @Nonnull String[] providerScalingGroupIds, @Nonnull AutoScalingTag... tags ) throws CloudException, InternalException { APITrace.begin( provider, "AutoScaling.removeTags" ); try { handleTagRequest( EC2Method.UPDATE_AUTO_SCALING_GROUP_TAGS, providerScalingGroupIds, tags ); } finally { APITrace.end(); } } @Override public void removeTags( @Nonnull String[] providerScalingGroupIds, @Nonnull AutoScalingTag... tags ) throws CloudException, InternalException { APITrace.begin( provider, "AutoScaling.removeTags" ); try { handleTagRequest( EC2Method.DELETE_AUTO_SCALING_GROUP_TAGS, providerScalingGroupIds, tags ); } finally { APITrace.end(); } } private Collection<AutoScalingTag> getTagsForDelete(@Nullable Collection<AutoScalingTag> all, @Nonnull AutoScalingTag[] tags) { Collection<AutoScalingTag> result = null; if (all != null) { result = new ArrayList<AutoScalingTag>(); for (AutoScalingTag tag : all) { if (!isTagInTags(tag, tags)) { result.add(tag); } } } return result; } private boolean isTagInTags(@Nonnull AutoScalingTag tag, @Nonnull AutoScalingTag[] tags) { for (AutoScalingTag t : tags) { if (t.getKey().equals(tag.getKey())) { return true; } } return false; } private void handleTagRequest( @Nonnull String methodName, @Nonnull String[] providerScalingGroupIds, @Nonnull AutoScalingTag... tags ) throws CloudException, InternalException { Map<String, String> parameters = getAutoScalingParameters( provider.getContext(), methodName ); EC2Method method; addAutoScalingTagParameters( parameters, providerScalingGroupIds, tags ); if ( parameters.size() == 0 ) { return; } method = new EC2Method( provider, getAutoScalingUrl(), parameters ); try { method.invoke(); } catch ( EC2Exception e ) { logger.error( e.getSummary() ); throw new CloudException( e ); } } @Override public void setNotificationConfig(@Nonnull String scalingGroupId, @Nonnull String topicARN, @Nonnull String[] notificationTypes) throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.setNotificationConfig"); try { Map<String, String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.PUT_NOTIFICATION_CONFIGURATION); parameters.put("AutoScalingGroupName", scalingGroupId); parameters.put("TopicARN", topicARN); for (int i = 0; i < notificationTypes.length; i++) { parameters.put("NotificationTypes.member." + (i + 1), notificationTypes[i]); } EC2Method method = new EC2Method(provider, getAutoScalingUrl(), parameters); method.invoke(); } finally { APITrace.end(); } } @Override public Collection<AutoScalingGroupNotificationConfig> listNotificationConfigs( final String[] scalingGroupIds ) throws CloudException, InternalException { PopulatorThread<AutoScalingGroupNotificationConfig> populatorThread; provider.hold(); populatorThread = new PopulatorThread<AutoScalingGroupNotificationConfig>(new JiteratorPopulator<AutoScalingGroupNotificationConfig>() { @Override public void populate(@Nonnull Jiterator<AutoScalingGroupNotificationConfig> autoScalingGroupNotificationConfigs) throws Exception { try { populateNotificationConfig(autoScalingGroupNotificationConfigs, null, scalingGroupIds); } finally { provider.release(); } } }); populatorThread.populate(); return populatorThread.getResult(); } private void populateNotificationConfig(@Nonnull Jiterator<AutoScalingGroupNotificationConfig> asgNotificationConfig, @Nullable String token, String[] scalingGroupIds) throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.listNotificationConfigs"); try { Map<String, String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DESCRIBE_NOTIFICATION_CONFIGURATIONS); AWSCloud.addValueIfNotNull(parameters, "NextToken", token); for (int i = 0; i < scalingGroupIds.length; i++) { AWSCloud.addValueIfNotNull(parameters, "AutoScalingGroupNames.member." + (i + 1), scalingGroupIds[i]); } EC2Method method = new EC2Method(provider, getAutoScalingUrl(), parameters); Document document = method.invoke(); NodeList blocks = document.getElementsByTagName("NotificationConfigurations"); if (blocks == null) return; NodeList result = blocks.item(0).getChildNodes(); for (int i = 0; i < result.getLength(); i++) { Node configNode = result.item(i); if (configNode.getNodeName().equalsIgnoreCase("member")) { AutoScalingGroupNotificationConfig nc = toASGNotificationConfig(configNode.getChildNodes()); if (nc != null) asgNotificationConfig.push(nc); } } blocks = document.getElementsByTagName("NextToken"); if( blocks != null && blocks.getLength() == 1 && blocks.item(0).hasChildNodes() ) { String nextToken = AWSCloud.getTextValue(blocks.item(0)); populateNotificationConfig(asgNotificationConfig, nextToken, scalingGroupIds); } } finally { APITrace.end(); } } private AutoScalingGroupNotificationConfig toASGNotificationConfig(NodeList attributes) { if (attributes != null && attributes.getLength() != 0) { AutoScalingGroupNotificationConfig result = new AutoScalingGroupNotificationConfig(); for (int i = 0; i < attributes.getLength(); i++) { Node attr = attributes.item(i); if (attr.getNodeName().equalsIgnoreCase("TopicARN")) { result.setTopic(attr.getFirstChild().getNodeValue()); } else if (attr.getNodeName().equalsIgnoreCase("AutoScalingGroupName")) { result.setAutoScalingGroupName(attr.getFirstChild().getNodeValue()); } else if (attr.getNodeName().equalsIgnoreCase("NotificationType")) { result.setNotificationType(attr.getFirstChild().getNodeValue()); } } return result; } return null; } static private void addAutoScalingTagParameters( @Nonnull Map<String, String> parameters, @Nonnull String[] providerScalingGroupIds, @Nonnull AutoScalingTag... tags ) { /** * unlike EC2's regular CreateTags call, for autoscaling we must add a set of tag parameters for each auto scaling group * http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_CreateOrUpdateTags.html */ int tagCounter = 1; for ( int i = 0; i < providerScalingGroupIds.length; i++ ) { for ( AutoScalingTag tag : tags ) { parameters.put( "Tags.member." + tagCounter + ".ResourceType", "auto-scaling-group" ); parameters.put( "Tags.member." + tagCounter + ".ResourceId", providerScalingGroupIds[i] ); parameters.put( "Tags.member." + tagCounter + ".Key", tag.getKey() ); if ( tag.getValue() != null ) { parameters.put( "Tags.member." + tagCounter + ".Value", tag.getValue() ); } parameters.put( "Tags.member." + tagCounter + ".PropagateAtLaunch", String.valueOf( tag.isPropagateAtLaunch() ) ); tagCounter++; } } } private @Nullable ResourceStatus toGroupStatus( @Nullable Node item) { if( item == null ) { return null; } NodeList attrs = item.getChildNodes(); String groupId = null; for( int i=0; i<attrs.getLength(); i++ ) { Node attr = attrs.item(i); if( attr.getNodeName().equalsIgnoreCase("AutoScalingGroupName") ) { groupId = attr.getFirstChild().getNodeValue(); } } if( groupId == null ) { return null; } return new ResourceStatus(groupId, true); } private @Nullable LaunchConfiguration toLaunchConfiguration(@Nullable Node item) { if( item == null ) { return null; } LaunchConfiguration cfg = new LaunchConfiguration(); NodeList attrs = item.getChildNodes(); for( int i=0; i<attrs.getLength(); i++ ) { Node attr = attrs.item(i); String name; name = attr.getNodeName(); if( name.equalsIgnoreCase("ImageId") ) { if(attr.getFirstChild() != null){ cfg.setProviderImageId(attr.getFirstChild().getNodeValue()); } } else if( name.equalsIgnoreCase("KeyName") ) { if(attr.getFirstChild() != null){ cfg.setProviderKeypairName(attr.getFirstChild().getNodeValue()); } } else if( name.equalsIgnoreCase("LaunchConfigurationARN") ) { if(attr.getFirstChild() != null){ cfg.setId(attr.getFirstChild().getNodeValue()); } } else if( name.equalsIgnoreCase("UserData") ) { if(attr.getFirstChild() != null){ cfg.setUserData(attr.getFirstChild().getNodeValue()); } } else if( name.equalsIgnoreCase("InstanceType") ) { if(attr.getFirstChild() != null){ cfg.setServerSizeId(attr.getFirstChild().getNodeValue()); } } else if( name.equalsIgnoreCase("LaunchConfigurationName") ) { if(attr.getFirstChild() != null){ String lcname = attr.getFirstChild().getNodeValue(); cfg.setProviderLaunchConfigurationId(lcname); cfg.setName(lcname); } } else if( name.equalsIgnoreCase("CreatedTime") ) { SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); try { cfg.setCreationTimestamp(fmt.parse(attr.getFirstChild().getNodeValue()).getTime()); } catch( ParseException e ) { logger.error("Could not parse timestamp: " + attr.getFirstChild().getNodeValue()); cfg.setCreationTimestamp(System.currentTimeMillis()); } } else if( name.equalsIgnoreCase("SecurityGroups") ) { String[] ids; if( attr.hasChildNodes() ) { ArrayList<String> securityIds = new ArrayList<String>(); NodeList securityGroups = attr.getChildNodes(); for( int j=0; j<securityGroups.getLength(); j++ ) { Node securityGroup = securityGroups.item(j); if( securityGroup.getNodeName().equalsIgnoreCase("member") ) { if( securityGroup.hasChildNodes() ) { securityIds.add(securityGroup.getFirstChild().getNodeValue()); } } } ids = new String[securityIds.size()]; int j=0; for( String securityId : securityIds ) { ids[j++] = securityId; } } else { ids = new String[0]; } cfg.setProviderFirewallIds(ids); } else if( name.equalsIgnoreCase("IamInstanceProfile") ) { if(attr.getFirstChild() != null){ String providerId = attr.getFirstChild().getNodeValue(); cfg.setProviderRoleId(providerId); } } else if ( "InstanceMonitoring".equals(name) && attr.hasChildNodes() ) { NodeList details = attr.getChildNodes(); for (int j = 0; j < details.getLength(); j++) { Node detail = details.item(j); name = detail.getNodeName(); if (name.equals("Enabled")) { if (detail.hasChildNodes()) { String value = detail.getFirstChild().getNodeValue().trim(); cfg.setDetailedMonitoring( Boolean.valueOf( value ) ); } } } } else if( name.equalsIgnoreCase("AssociatePublicIpAddress") ) { if(attr.getFirstChild() != null){ cfg.setAssociatePublicIPAddress( Boolean.valueOf(attr.getFirstChild().getNodeValue()) ); } } else if( name.equalsIgnoreCase("EbsOptimized") ) { if(attr.getFirstChild() != null){ cfg.setIoOptimized(Boolean.valueOf(attr.getFirstChild().getNodeValue())); } } else if( name.equalsIgnoreCase("BlockDeviceMappings") ) { ArrayList<VolumeAttachment> VAs = new ArrayList<VolumeAttachment>(); VolumeAttachment[] VAArray; if( attr.hasChildNodes() ) { NodeList blockDeviceMaps = attr.getChildNodes(); for( int j=0; j<blockDeviceMaps.getLength(); j++ ) { Node blockDeviceMap = blockDeviceMaps.item(j); if( blockDeviceMap.getNodeName().equalsIgnoreCase("member") ) { VolumeAttachment va = new VolumeAttachment(); if( blockDeviceMap.hasChildNodes() ) { NodeList blockDeviceChildren = blockDeviceMap.getChildNodes(); for( int y=0; y<blockDeviceChildren.getLength(); y++ ) { Node blockDeviceChild = blockDeviceChildren.item(y); String blockDeviceChildName = blockDeviceChild.getNodeName(); if( blockDeviceChildName.equalsIgnoreCase("DeviceName") ) { String value = blockDeviceChild.getFirstChild().getNodeValue().trim(); va.setDeviceId(value); } else if( blockDeviceChildName.equalsIgnoreCase("Ebs") ) { if( blockDeviceChild.hasChildNodes() ) { NodeList ebsChildren = blockDeviceChild.getChildNodes(); int size = 0; String iops = null; String snapShotId = null; String volumeType = null; for( int q=0; q<ebsChildren.getLength(); q++ ) { Node ebsChild = ebsChildren.item(q); String ebsChildName = ebsChild.getNodeName(); if( ebsChildName.equalsIgnoreCase("Iops") ) { iops = ebsChild.getFirstChild().getNodeValue().trim(); } else if( ebsChildName.equalsIgnoreCase("VolumeSize") ) { String value = ebsChild.getFirstChild().getNodeValue().trim(); size = Integer.parseInt(value); } else if( ebsChildName.equalsIgnoreCase("SnapshotId") ) { snapShotId = ebsChild.getFirstChild().getNodeValue().trim(); } else if( ebsChildName.equalsIgnoreCase("VolumeType") ) { volumeType = ebsChild.getFirstChild().getNodeValue().trim(); } } VolumeCreateOptions vco = VolumeCreateOptions.getInstance( new Storage<Gigabyte>(size, Storage.GIGABYTE), "", "" ); try { vco.setIops( Integer.parseInt( iops ) ); } catch( NumberFormatException nfe ) { vco.setIops( 0 ); } vco.setSnapshotId( snapShotId ); vco.setVolumeProductId( volumeType ); va.setVolumeToCreate( vco ); } } } VAs.add( va ); } } } VAArray = new VolumeAttachment[VAs.size()]; int v=0; for( VolumeAttachment va : VAs ) { VAArray[v++] = va; } } else { VAArray = new VolumeAttachment[0]; } cfg.setVolumeAttachment( VAArray ); } } return cfg; } private @Nullable ResourceStatus toLCStatus(@Nullable Node item) { if( item == null ) { return null; } NodeList attrs = item.getChildNodes(); String lcId = null; for( int i=0; i<attrs.getLength(); i++ ) { Node attr = attrs.item(i); if( attr.getNodeName().equalsIgnoreCase("LaunchConfigurationName") ) { lcId = attr.getFirstChild().getNodeValue(); } } if( lcId == null ) { return null; } return new ResourceStatus(lcId, true); } private @Nullable ScalingGroup toScalingGroup(@Nonnull ProviderContext ctx, @Nullable Node item) { if( item == null ) { return null; } NodeList attrs = item.getChildNodes(); ScalingGroup group = new ScalingGroup(); group.setProviderOwnerId(ctx.getAccountNumber()); group.setProviderRegionId(ctx.getRegionId()); for( int i=0; i<attrs.getLength(); i++ ) { Node attr = attrs.item(i); String name; name = attr.getNodeName(); if( name.equalsIgnoreCase("MinSize") ) { group.setMinServers(Integer.parseInt(attr.getFirstChild().getNodeValue())); } else if( name.equalsIgnoreCase("MaxSize") ) { group.setMaxServers(Integer.parseInt(attr.getFirstChild().getNodeValue())); } else if( name.equalsIgnoreCase("DefaultCooldown") ) { group.setDefaultCooldown(Integer.parseInt(attr.getFirstChild().getNodeValue())); } else if( name.equalsIgnoreCase("CreatedTime") ) { SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); try { group.setCreationTimestamp(fmt.parse(attr.getFirstChild().getNodeValue()).getTime()); } catch( ParseException e ) { logger.error("Could not parse timestamp: " + attr.getFirstChild().getNodeValue()); group.setCreationTimestamp(System.currentTimeMillis()); } } else if( name.equalsIgnoreCase("DesiredCapacity") ) { group.setTargetCapacity(Integer.parseInt(attr.getFirstChild().getNodeValue())); } else if( name.equalsIgnoreCase("LaunchConfigurationName") ) { group.setProviderLaunchConfigurationId(attr.getFirstChild().getNodeValue()); } else if( name.equalsIgnoreCase("AutoScalingGroupARN") ) { group.setId(attr.getFirstChild().getNodeValue()); } else if( name.equalsIgnoreCase("HealthCheckGracePeriod") ) { group.setHealthCheckGracePeriod(Integer.parseInt(attr.getFirstChild().getNodeValue())); } else if( name.equalsIgnoreCase("HealthCheckType") ) { group.setHealthCheckType(attr.getFirstChild().getNodeValue()); } else if( name.equalsIgnoreCase("Status") ) { group.setStatus(attr.getFirstChild().getNodeValue()); } else if( name.equalsIgnoreCase("VPCZoneIdentifier") ) { Node subnetChild = attr.getFirstChild(); if( subnetChild != null ) { String subnets = subnetChild.getNodeValue(); group.setProviderSubnetIds( subnets.contains(",") ? subnets.split("\\s*,\\s*") : new String[]{subnets} ); } } else if( name.equalsIgnoreCase("AutoScalingGroupName") ) { String gname = attr.getFirstChild().getNodeValue(); group.setProviderScalingGroupId(gname); group.setName(gname); group.setDescription(gname); } else if( name.equalsIgnoreCase("Instances") ) { String[] ids; if( attr.hasChildNodes() ) { ArrayList<String> instanceIds = new ArrayList<String>(); NodeList instances = attr.getChildNodes(); for( int j=0; j<instances.getLength(); j++ ) { Node instance = instances.item(j); if( instance.getNodeName().equals("member") ) { if( instance.hasChildNodes() ) { NodeList items = instance.getChildNodes(); for( int k=0; k<items.getLength(); k++ ) { Node val = items.item(k); if( val.getNodeName().equalsIgnoreCase("InstanceId") ) { instanceIds.add(val.getFirstChild().getNodeValue()); } } } } } ids = new String[instanceIds.size()]; int j=0; for( String id : instanceIds ) { ids[j++] = id; } } else { ids = new String[0]; } group.setProviderServerIds(ids); } else if( name.equalsIgnoreCase("AvailabilityZones") ) { String[] ids; if( attr.hasChildNodes() ) { ArrayList<String> zoneIds = new ArrayList<String>(); NodeList zones = attr.getChildNodes(); for( int j=0; j<zones.getLength(); j++ ) { Node zone = zones.item(j); if( zone.getNodeName().equalsIgnoreCase("member") ) { zoneIds.add(zone.getFirstChild().getNodeValue()); } } ids = new String[zoneIds.size()]; int j=0; for( String zoneId : zoneIds ) { ids[j++] = zoneId; } } else { ids = new String[0]; } group.setProviderDataCenterIds(ids); } else if( name.equalsIgnoreCase("EnabledMetrics") ) { String[] names; if( attr.hasChildNodes() ) { ArrayList<String> metricNames = new ArrayList<String>(); NodeList metrics = attr.getChildNodes(); for( int j=0; j< metrics.getLength(); j++ ) { Node metric = metrics.item(j); if( metric.getNodeName().equalsIgnoreCase("Metric") ) { metricNames.add(metric.getFirstChild().getNodeValue()); } } names = new String[metricNames.size()]; int j=0; for( String metricName : metricNames ) { names[j++] = metricName; } } else { names = new String[0]; } group.setEnabledMetrics(names); } else if( name.equalsIgnoreCase("LoadBalancerNames") ) { String[] names; if( attr.hasChildNodes() ) { ArrayList<String> lbNames = new ArrayList<String>(); NodeList loadBalancers = attr.getChildNodes(); for( int j=0; j< loadBalancers.getLength(); j++ ) { Node lb = loadBalancers.item(j); if( lb.getNodeName().equalsIgnoreCase("member") ) { lbNames.add(lb.getFirstChild().getNodeValue()); } } names = new String[lbNames.size()]; int j=0; for( String lbName : lbNames ) { names[j++] = lbName; } } else { names = new String[0]; } group.setProviderLoadBalancerNames(names); } else if( name.equalsIgnoreCase("SuspendedProcesses") ) { Collection<String[]> processes; if( attr.hasChildNodes() ) { ArrayList<String[]> processList = new ArrayList<String[]>(); NodeList processesList = attr.getChildNodes(); for( int j=0; j< processesList.getLength(); j++ ) { Node processParent = processesList.item(j); ArrayList<String> theProcess = new ArrayList<String>(); if( processParent.getNodeName().equals("member") ) { if( processParent.hasChildNodes() ) { NodeList items = processParent.getChildNodes(); for( int k=0; k<items.getLength(); k++ ) { Node val = items.item(k); if( val.getNodeName().equalsIgnoreCase("SuspensionReason") ) { theProcess.add(val.getFirstChild().getNodeValue()); } // seems to come second... if( val.getNodeName().equalsIgnoreCase("ProcessName") ) { theProcess.add(val.getFirstChild().getNodeValue()); } } } } if(theProcess.size() > 0){ String[] stringArr = new String[theProcess.size()]; stringArr = theProcess.toArray(stringArr); processList.add(stringArr); } } processes = processList; } else { processes = new ArrayList<String[]>(); } group.setSuspendedProcesses(processes); } else if( name.equalsIgnoreCase("TerminationPolicies") ) { String[] policies; if( attr.hasChildNodes() ) { ArrayList<String> subPolicies = new ArrayList<String>(); NodeList policyList = attr.getChildNodes(); for( int j=0; j< policyList.getLength(); j++ ) { Node lb = policyList.item(j); if( lb.getNodeName().equalsIgnoreCase("member") ) { subPolicies.add(lb.getFirstChild().getNodeValue()); } } policies = new String[subPolicies.size()]; int j=0; for( String policyString : subPolicies ) { policies[j++] = policyString; } } else { policies = new String[0]; } group.setTerminationPolicies(policies); } else if (name.equalsIgnoreCase("Tags") && attr.hasChildNodes()) { ArrayList<AutoScalingTag> tags = new ArrayList<AutoScalingTag>(); NodeList tagList = attr.getChildNodes(); for (int j = 0; j < tagList.getLength(); j++) { Node parent = tagList.item(j); if (parent.getNodeName().equals("member") && parent.hasChildNodes()) { String key = null; String value = null; Boolean propagateAtLaunch = null; NodeList memberNodes = parent.getChildNodes(); for (int k = 0; k < memberNodes.getLength(); k++) { Node val = memberNodes.item(k); if (val.getNodeName().equalsIgnoreCase("Key")) { key = AWSCloud.getTextValue(val); } else if (val.getNodeName().equalsIgnoreCase("Value")) { value = AWSCloud.getTextValue(val); } else if (val.getNodeName().equalsIgnoreCase("PropagateAtLaunch")) { propagateAtLaunch = AWSCloud.getBooleanValue(val); } } tags.add(new AutoScalingTag(key, value, propagateAtLaunch)); } } if (tags.size() > 0) { group.setTags(tags.toArray(new AutoScalingTag[tags.size()])); } } } return group; } private @Nullable ScalingPolicy toScalingPolicy(@Nullable Node item) { if( item == null ) { return null; } ScalingPolicy sp = new ScalingPolicy(); NodeList attrs = item.getChildNodes(); for( int i=0; i<attrs.getLength(); i++ ) { Node attr = attrs.item(i); String name; name = attr.getNodeName(); if( name.equalsIgnoreCase("AdjustmentType") ) { if(attr.getFirstChild() != null){ sp.setAdjustmentType(attr.getFirstChild().getNodeValue()); } } else if( name.equalsIgnoreCase("Alarms") ) { Collection<Alarm> alarms; if( attr.hasChildNodes() ) { ArrayList<Alarm> alarmList = new ArrayList<Alarm>(); NodeList alarmsList = attr.getChildNodes(); for( int j=0; j< alarmsList.getLength(); j++ ) { Node alarmParent = alarmsList.item(j); Alarm anAlarm = new Alarm(); if( alarmParent.getNodeName().equals("member") ) { if( alarmParent.hasChildNodes() ) { NodeList items = alarmParent.getChildNodes(); for( int k=0; k<items.getLength(); k++ ) { Node val = items.item(k); if( val.getNodeName().equalsIgnoreCase("AlarmARN") ) { anAlarm.setId(val.getFirstChild().getNodeValue()); } if( val.getNodeName().equalsIgnoreCase("AlarmName") ) { anAlarm.setName(val.getFirstChild().getNodeValue()); } } alarmList.add(anAlarm); } } } alarms = alarmList; } else { alarms = new ArrayList<Alarm>(); } Alarm[] alarmArr = new Alarm[alarms.size()]; alarmArr = alarms.toArray(alarmArr); sp.setAlarms(alarmArr); } else if( name.equalsIgnoreCase("AutoScalingGroupName") ) { if(attr.getFirstChild() != null){ sp.setAutoScalingGroupName(attr.getFirstChild().getNodeValue()); } } else if( name.equalsIgnoreCase("Cooldown") ) { if(attr.getFirstChild() != null){ sp.setCoolDown(Integer.parseInt(attr.getFirstChild().getNodeValue())); } } else if( name.equalsIgnoreCase("MinAdjustmentStep") ) { if(attr.getFirstChild() != null){ sp.setMinAdjustmentStep(Integer.parseInt(attr.getFirstChild().getNodeValue())); } } else if( name.equalsIgnoreCase("PolicyARN") ) { if(attr.getFirstChild() != null){ sp.setId(attr.getFirstChild().getNodeValue()); } } else if( name.equalsIgnoreCase("PolicyName") ) { if(attr.getFirstChild() != null){ sp.setName(attr.getFirstChild().getNodeValue()); } } else if( name.equalsIgnoreCase("ScalingAdjustment") ) { if(attr.getFirstChild() != null){ sp.setScalingAdjustment(Integer.parseInt(attr.getFirstChild().getNodeValue())); } } } return sp; } }
src/main/java/org/dasein/cloud/aws/compute/AutoScaling.java
/** * Copyright (C) 2009-2014 Dell, Inc. * See annotations for authorship information * * ==================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ package org.dasein.cloud.aws.compute; import org.apache.log4j.Logger; import org.dasein.cloud.*; import org.dasein.cloud.aws.AWSCloud; import org.dasein.cloud.compute.*; import org.dasein.cloud.identity.ServiceAction; import org.dasein.cloud.util.APITrace; import org.dasein.util.Jiterator; import org.dasein.util.JiteratorPopulator; import org.dasein.util.PopulatorThread; import org.dasein.util.uom.storage.Gigabyte; import org.dasein.util.uom.storage.Storage; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.UnsupportedEncodingException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; public class AutoScaling extends AbstractAutoScalingSupport { static private final Logger logger = Logger.getLogger(AutoScaling.class); private AWSCloud provider = null; AutoScaling(AWSCloud provider) { super(provider); this.provider = provider; } @Override public String createAutoScalingGroup(@Nonnull AutoScalingGroupOptions autoScalingGroupOptions) throws InternalException, CloudException { APITrace.begin(provider, "AutoScaling.createAutoScalingGroup"); try { Map<String, String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.CREATE_AUTO_SCALING_GROUP); EC2Method method; int minServers = autoScalingGroupOptions.getMinServers(); if (minServers < 0) { minServers = 0; } int maxServers = autoScalingGroupOptions.getMaxServers(); if (maxServers < minServers) { maxServers = minServers; } parameters.put("AutoScalingGroupName", autoScalingGroupOptions.getName()); parameters.put("LaunchConfigurationName", autoScalingGroupOptions.getLaunchConfigurationId()); parameters.put("MinSize", String.valueOf(minServers)); parameters.put("MaxSize", String.valueOf(maxServers)); if (autoScalingGroupOptions.getCooldown() != null) { parameters.put("DefaultCooldown", String.valueOf(autoScalingGroupOptions.getCooldown())); } if (autoScalingGroupOptions.getDesiredCapacity() != null) { parameters.put("DesiredCapacity", String.valueOf(autoScalingGroupOptions.getDesiredCapacity())); } if (autoScalingGroupOptions.getHealthCheckGracePeriod() != null) { parameters.put("HealthCheckGracePeriod", String.valueOf(autoScalingGroupOptions.getHealthCheckGracePeriod())); } if (autoScalingGroupOptions.getHealthCheckType() != null) { parameters.put("HealthCheckType", autoScalingGroupOptions.getHealthCheckType()); } if (autoScalingGroupOptions.getProviderSubnetIds() != null) { StringBuilder vpcZones = new StringBuilder(); int i = 0; for (String subnetId : autoScalingGroupOptions.getProviderSubnetIds()) { if (i > 0) { vpcZones.append(","); } vpcZones.append(subnetId); i++; } parameters.put("VPCZoneIdentifier", vpcZones.toString()); } if (autoScalingGroupOptions.getProviderDataCenterIds() != null) { int i = 1; for (String zoneId : autoScalingGroupOptions.getProviderDataCenterIds()) { parameters.put("AvailabilityZones.member." + (i++), zoneId); } } if (autoScalingGroupOptions.getProviderLoadBalancerIds() != null) { int i = 1; for (String lbId : autoScalingGroupOptions.getProviderLoadBalancerIds()) { parameters.put("LoadBalancerNames.member." + (i++), lbId); } } if (autoScalingGroupOptions.getTags() != null) { int i = 1; for (AutoScalingTag tag : autoScalingGroupOptions.getTags()) { parameters.put("Tags.member." + i + ".Key", tag.getKey()); parameters.put("Tags.member." + i + ".Value", tag.getValue()); parameters.put("Tags.member." + i + ".PropagateAtLaunch", String.valueOf(tag.isPropagateAtLaunch())); i++; } } method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { method.invoke(); } catch (EC2Exception e) { logger.error(e.getSummary()); throw new CloudException(e); } return autoScalingGroupOptions.getName(); } finally { APITrace.end(); } } @Override public String createAutoScalingGroup(@Nonnull String name, @Nonnull String launchConfigurationId, @Nonnull Integer minServers, @Nonnull Integer maxServers, @Nullable Integer cooldown, @Nullable String[] loadBalancerIds, @Nullable Integer desiredCapacity, @Nullable Integer healthCheckGracePeriod, @Nullable String healthCheckType, @Nullable String vpcZones, @Nullable String... zoneIds) throws InternalException, CloudException { AutoScalingGroupOptions options = new AutoScalingGroupOptions(name) .withLaunchConfigurationId(launchConfigurationId) .withMinServers(minServers) .withMaxServers(maxServers) .withCooldown(cooldown) .withProviderLoadBalancerIds(loadBalancerIds) .withDesiredCapacity(desiredCapacity) .withHealthCheckGracePeriod(healthCheckGracePeriod) .withHealthCheckType(healthCheckType) .withProviderSubnetIds(vpcZones != null ? vpcZones.split(",") : new String[]{}) .withProviderDataCenterIds(zoneIds); return createAutoScalingGroup(options); } @Override public void updateAutoScalingGroup(@Nonnull String scalingGroupId, @Nullable String launchConfigurationId, @Nonnegative Integer minServers, @Nonnegative Integer maxServers, @Nullable Integer cooldown, @Nullable Integer desiredCapacity, @Nullable Integer healthCheckGracePeriod, @Nullable String healthCheckType, @Nullable String vpcZones, @Nullable String ... zoneIds) throws InternalException, CloudException { APITrace.begin(provider, "AutoScaling.updateAutoScalingGroup"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.UPDATE_AUTO_SCALING_GROUP); EC2Method method; if(scalingGroupId != null) { parameters.put("AutoScalingGroupName", scalingGroupId); } if(launchConfigurationId != null) { parameters.put("LaunchConfigurationName", launchConfigurationId); } if(minServers != null) { if( minServers < 0 ) { minServers = 0; } parameters.put("MinSize", String.valueOf(minServers)); } if(maxServers != null) { if( minServers != null && maxServers < minServers ) { maxServers = minServers; } parameters.put("MaxSize", String.valueOf(maxServers)); } if(cooldown != null) { parameters.put("DefaultCooldown", String.valueOf(cooldown)); } if(desiredCapacity != null) { parameters.put("DesiredCapacity", String.valueOf(desiredCapacity)); } if(healthCheckGracePeriod != null) { parameters.put("HealthCheckGracePeriod", String.valueOf(healthCheckGracePeriod)); } if(healthCheckType != null) { parameters.put("HealthCheckType", healthCheckType); } if(vpcZones != null) { parameters.put("VPCZoneIdentifier", vpcZones); } if(zoneIds != null) { int i = 1; for( String zoneId : zoneIds ) { parameters.put("AvailabilityZones.member." + (i++), zoneId); } } method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } } finally { APITrace.end(); } } @Override public String createLaunchConfiguration(String name, String imageId, VirtualMachineProduct size, String keyPairName, String userData, String providerRoleId, Boolean detailedMonitoring, String ... firewalls) throws InternalException, CloudException { return createLaunchConfiguration(new LaunchConfigurationCreateOptions(name, imageId, size, keyPairName, userData, providerRoleId, detailedMonitoring, firewalls)); } @Override public String createLaunchConfiguration(@Nonnull LaunchConfigurationCreateOptions options) throws InternalException, CloudException { APITrace.begin(provider, "AutoScaling.createLaunchConfigursation"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.CREATE_LAUNCH_CONFIGURATION); EC2Method method; parameters.put("LaunchConfigurationName", options.getName()); if(options.getImageId() != null) { parameters.put("ImageId", options.getImageId()); } if(options.getKeypairName() != null) { parameters.put("KeyName", options.getKeypairName()); } if(options.getUserData() != null) { parameters.put("UserData", options.getUserData()); } if(options.getProviderRoleId() != null) { parameters.put("IamInstanceProfile", options.getProviderRoleId()); } if(options.getDetailedMonitoring() != null) { parameters.put("InstanceMonitoring.Enabled", options.getDetailedMonitoring().toString()); } if(options.getSize() != null) { parameters.put("InstanceType", options.getSize().getProviderProductId()); } int i = 1; if( options.getFirewallIds() != null ) { for (String fw : options.getFirewallIds()) { parameters.put("SecurityGroups.member." + (i++), fw); } } if(options.getAssociatePublicIPAddress() != null) { parameters.put("AssociatePublicIpAddress", options.getAssociatePublicIPAddress().toString()); } if(options.getIOOptimized() != null) { parameters.put("EbsOptimized", options.getIOOptimized().toString()); } if( options.getVolumeAttachment() != null ) { int z = 1; for( VolumeAttachment va : options.getVolumeAttachment() ) { parameters.put("BlockDeviceMappings.member." + z + ".DeviceName", va.deviceId); EBSVolume ebsv = new EBSVolume( provider ); String volType = null; try { VolumeProduct prd = ebsv.getVolumeProduct( va.volumeToCreate.getVolumeProductId() ); volType = prd.getProviderProductId(); } catch ( Exception e ) { // toss it } if( volType == null ) { if( options.getIOOptimized() && va.volumeToCreate.getIops() > 0 ) { parameters.put("BlockDeviceMappings.member." + z + ".Ebs.VolumeType", "io1"); } } else { parameters.put("BlockDeviceMappings.member." + z + ".Ebs.VolumeType", volType); } if(va.volumeToCreate.getIops() > 0) { parameters.put("BlockDeviceMappings.member." + z + ".Ebs.Iops", String.valueOf(va.volumeToCreate.getIops())); } if(va.volumeToCreate.getSnapshotId() != null) { parameters.put("BlockDeviceMappings.member." + z + ".Ebs.SnapshotId", va.volumeToCreate.getSnapshotId()); } if(va.volumeToCreate.getVolumeSize().getQuantity().intValue() > 0) { parameters.put("BlockDeviceMappings.member." + z + ".Ebs.VolumeSize", String.valueOf(va.volumeToCreate.getVolumeSize().getQuantity().intValue())); } z++; } } if(options.getVirtualMachineIdToClone() != null) { parameters.put("InstanceId", options.getVirtualMachineIdToClone()); } method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } return options.getName(); } finally { APITrace.end(); } } @Override public void deleteAutoScalingGroup(String providerAutoScalingGroupId) throws InternalException, CloudException { deleteAutoScalingGroup( new AutoScalingGroupDeleteOptions( providerAutoScalingGroupId ) ); } @Override public void deleteAutoScalingGroup( @Nonnull AutoScalingGroupDeleteOptions options ) throws InternalException, CloudException { APITrace.begin(provider, "AutoScaling.deleteAutoScalingGroup"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DELETE_AUTO_SCALING_GROUP); EC2Method method; parameters.put( "AutoScalingGroupName", options.getProviderAutoScalingGroupId() ); parameters.put( "ForceDelete", options.getForceDelete().toString() ); method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } } finally { APITrace.end(); } } @Override public void deleteLaunchConfiguration(String providerLaunchConfigurationId) throws InternalException, CloudException { APITrace.begin(provider, "AutoScaling.deleteLaunchConfiguration"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DELETE_LAUNCH_CONFIGURATION); EC2Method method; parameters.put("LaunchConfigurationName", providerLaunchConfigurationId); method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } } finally { APITrace.end(); } } @Override public String setTrigger(String name, String scalingGroupId, String statistic, String unitOfMeasure, String metric, int periodInSeconds, double lowerThreshold, double upperThreshold, int lowerIncrement, boolean lowerIncrementAbsolute, int upperIncrement, boolean upperIncrementAbsolute, int breachDuration) throws InternalException, CloudException { APITrace.begin(provider, "AutoScaling.setTrigger"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.CREATE_OR_UPDATE_SCALING_TRIGGER); EC2Method method; parameters.put("AutoScalingGroupName", scalingGroupId); parameters.put("MeasureName", metric); parameters.put("Period", String.valueOf(periodInSeconds)); parameters.put("LowerThreshold", String.valueOf(lowerThreshold)); parameters.put("UpperThreshold", String.valueOf(upperThreshold)); parameters.put("UpperBreachScaleIncrement", String.valueOf(upperIncrement)); parameters.put("LowerBreachScaleIncrement", String.valueOf(lowerIncrement)); parameters.put("BreachDuration", String.valueOf(breachDuration)); parameters.put("TriggerName", name); parameters.put("Unit", unitOfMeasure); parameters.put("Statistic", statistic); parameters.put("Dimensions.member.1.Name", "AutoScalingGroupName"); parameters.put("Dimensions.member.1.Value", scalingGroupId); method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } return name; } finally { APITrace.end(); } } private Map<String,String> getAutoScalingParameters(ProviderContext ctx, String action) throws InternalException { APITrace.begin(provider, "AutoScaling.getAutoScalingParameters"); try { HashMap<String,String> parameters = new HashMap<String,String>(); parameters.put(AWSCloud.P_ACTION, action); parameters.put(AWSCloud.P_SIGNATURE_VERSION, AWSCloud.SIGNATURE); try { parameters.put(AWSCloud.P_ACCESS, new String(ctx.getAccessPublic(), "utf-8")); } catch( UnsupportedEncodingException e ) { logger.error(e); e.printStackTrace(); throw new InternalException(e); } parameters.put(AWSCloud.P_SIGNATURE_METHOD, AWSCloud.EC2_ALGORITHM); parameters.put(AWSCloud.P_TIMESTAMP, provider.getTimestamp(System.currentTimeMillis(), true)); parameters.put(AWSCloud.P_VERSION, provider.getAutoScaleVersion()); return parameters; } finally { APITrace.end(); } } private String getAutoScalingUrl() throws CloudException { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context has been set for this request"); } return "https://autoscaling." + ctx.getRegionId() + ".amazonaws.com"; } @Override public LaunchConfiguration getLaunchConfiguration(String providerLaunchConfigurationId) throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.getLaunchConfiguration"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DESCRIBE_LAUNCH_CONFIGURATIONS); EC2Method method; NodeList blocks; Document doc; parameters.put("LaunchConfigurationNames.member.1", providerLaunchConfigurationId); method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { doc = method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } blocks = doc.getElementsByTagName("LaunchConfigurations"); for( int i=0; i<blocks.getLength(); i++ ) { NodeList items = blocks.item(i).getChildNodes(); for( int j=0; j<items.getLength(); j++ ) { Node item = items.item(j); if( item.getNodeName().equals("member") ) { LaunchConfiguration cfg = toLaunchConfiguration(item); if( cfg != null ) { return cfg; } } } } return null; } finally { APITrace.end(); } } @Override public ScalingGroup getScalingGroup(String providerScalingGroupId) throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.getScalingGroup"); try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context has been set for this request"); } Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DESCRIBE_AUTO_SCALING_GROUPS); EC2Method method; NodeList blocks; Document doc; parameters.put("AutoScalingGroupNames.member.1", providerScalingGroupId); method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { doc = method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } blocks = doc.getElementsByTagName("AutoScalingGroups"); for( int i=0; i<blocks.getLength(); i++ ) { NodeList members = blocks.item(i).getChildNodes(); for( int j=0; j<members.getLength(); j++ ) { Node item = members.item(j); if( item.getNodeName().equals("member") ) { ScalingGroup group = toScalingGroup(ctx, item); if( group != null ) { return group; } } } } return null; } finally { APITrace.end(); } } @Override public boolean isSubscribed() throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.isSubscribed"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DESCRIBE_AUTO_SCALING_GROUPS); EC2Method method; method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { method.invoke(); return true; } catch( EC2Exception e ) { String msg = e.getSummary(); if( msg != null && msg.contains("not able to validate the provided access credentials") ) { return false; } logger.error("AWS Error checking subscription: " + e.getCode() + "/" + e.getSummary()); if( logger.isDebugEnabled() ) { e.printStackTrace(); } throw new CloudException(e); } } finally { APITrace.end(); } } @Override public void suspendAutoScaling(String providerScalingGroupId, String[] processesToSuspend) throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.suspendAutoScaling"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.SUSPEND_AUTO_SCALING_GROUP); EC2Method method; parameters.put("AutoScalingGroupName", providerScalingGroupId); int x = 1; if(processesToSuspend != null) { for( String process : processesToSuspend ) { parameters.put("ScalingProcesses.member." + (x++), process); } } method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } } finally { APITrace.end(); } } @Override public void resumeAutoScaling(String providerScalingGroupId, String[] processesToResume) throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.resumeAutoScaling"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.RESUME_AUTO_SCALING_GROUP); EC2Method method; parameters.put("AutoScalingGroupName", providerScalingGroupId); int x = 1; if(processesToResume != null) { for( String process : processesToResume ) { parameters.put("ScalingProcesses.member." + (x++), process); } } method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } } finally { APITrace.end(); } } @Override public String updateScalingPolicy(String policyName, String adjustmentType, String autoScalingGroupName, Integer cooldown, Integer minAdjustmentStep, Integer scalingAdjustment) throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.updateScalingPolicy"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.PUT_SCALING_POLICY); EC2Method method; NodeList blocks; Document doc; parameters.put("PolicyName", policyName); parameters.put("AdjustmentType", adjustmentType); parameters.put("AutoScalingGroupName", autoScalingGroupName); if(cooldown != null){ parameters.put("Cooldown", String.valueOf(cooldown)); } if(minAdjustmentStep != null){ parameters.put("MinAdjustmentStep", String.valueOf(minAdjustmentStep)); } parameters.put("ScalingAdjustment", String.valueOf(scalingAdjustment)); method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { doc = method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } blocks = doc.getElementsByTagName("PolicyARN"); if( blocks.getLength() > 0 ) { return blocks.item(0).getFirstChild().getNodeValue().trim(); } throw new CloudException("Successful POST, but no Policy information was provided"); } finally { APITrace.end(); } } @Override public void deleteScalingPolicy(@Nonnull String policyName, @Nullable String autoScalingGroupName) throws InternalException, CloudException { APITrace.begin(provider, "AutoScaling.deleteScalingPolicy"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DELETE_SCALING_POLICY); EC2Method method; parameters.put("PolicyName", policyName); if(autoScalingGroupName != null) { parameters.put("AutoScalingGroupName", autoScalingGroupName); } method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } } finally { APITrace.end(); } } @Override public Collection<ScalingPolicy> listScalingPolicies(@Nullable String autoScalingGroupName) throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.getScalingPolicies"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DESCRIBE_SCALING_POLICIES); ArrayList<ScalingPolicy> list = new ArrayList<ScalingPolicy>(); EC2Method method; NodeList blocks; Document doc; if(autoScalingGroupName != null) { parameters.put("AutoScalingGroupName", autoScalingGroupName); } method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { doc = method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } blocks = doc.getElementsByTagName("ScalingPolicies"); for( int i=0; i<blocks.getLength(); i++ ) { NodeList items = blocks.item(i).getChildNodes(); for( int j=0; j<items.getLength(); j++ ) { Node item = items.item(j); if( item.getNodeName().equals("member") ) { ScalingPolicy sp = toScalingPolicy(item); if( sp != null ) { list.add(sp); } } } } return list; } finally { APITrace.end(); } } @Override public ScalingPolicy getScalingPolicy(@Nonnull String policyName) throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.getScalingPolicy"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DESCRIBE_SCALING_POLICIES); EC2Method method; NodeList blocks; Document doc; parameters.put("PolicyNames.member.1", policyName); method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { doc = method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } ScalingPolicy sp = null; blocks = doc.getElementsByTagName("ScalingPolicies"); for( int i=0; i<blocks.getLength(); i++ ) { NodeList items = blocks.item(i).getChildNodes(); for( int j=0; j<items.getLength(); j++ ) { Node item = items.item(j); if( item.getNodeName().equals("member") ) { sp = toScalingPolicy(item); return sp; } } } return sp; } finally { APITrace.end(); } } @Override public @Nonnull Iterable<ResourceStatus> listLaunchConfigurationStatus() throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.listLaunchConfigurationStatus"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DESCRIBE_LAUNCH_CONFIGURATIONS); ArrayList<ResourceStatus> list = new ArrayList<ResourceStatus>(); EC2Method method; NodeList blocks; Document doc; method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { doc = method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } blocks = doc.getElementsByTagName("LaunchConfigurations"); for( int i=0; i<blocks.getLength(); i++ ) { NodeList items = blocks.item(i).getChildNodes(); for( int j=0; j<items.getLength(); j++ ) { Node item = items.item(j); if( item.getNodeName().equals("member") ) { ResourceStatus status = toLCStatus(item); if( status != null ) { list.add(status); } } } } return list; } finally { APITrace.end(); } } @Override public Collection<LaunchConfiguration> listLaunchConfigurations() throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.listLaunchConfigurations"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DESCRIBE_LAUNCH_CONFIGURATIONS); ArrayList<LaunchConfiguration> list = new ArrayList<LaunchConfiguration>(); EC2Method method; NodeList blocks; Document doc; method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { doc = method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } blocks = doc.getElementsByTagName("LaunchConfigurations"); for( int i=0; i<blocks.getLength(); i++ ) { NodeList items = blocks.item(i).getChildNodes(); for( int j=0; j<items.getLength(); j++ ) { Node item = items.item(j); if( item.getNodeName().equals("member") ) { LaunchConfiguration cfg = toLaunchConfiguration(item); if( cfg != null ) { list.add(cfg); } } } } return list; } finally { APITrace.end(); } } @Override public Iterable<ResourceStatus> listScalingGroupStatus() throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.listScalingGroupStatus"); try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context has been set for this request"); } ArrayList<ResourceStatus> list = new ArrayList<ResourceStatus>(); Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DESCRIBE_AUTO_SCALING_GROUPS); EC2Method method; NodeList blocks; Document doc; method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { doc = method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } blocks = doc.getElementsByTagName("AutoScalingGroups"); for( int i=0; i<blocks.getLength(); i++ ) { NodeList items = blocks.item(i).getChildNodes(); for( int j=0; j<items.getLength(); j++ ) { Node item = items.item(j); if( item.getNodeName().equals("member") ) { ResourceStatus status = toGroupStatus(item); if( status != null ) { list.add(status); } } } } return list; } finally { APITrace.end(); } } /** * Provides backwards compatibility */ @Override public Collection<ScalingGroup> listScalingGroups() throws CloudException, InternalException { return listScalingGroups(AutoScalingGroupFilterOptions.getInstance()); } /** * Returns filtered list of auto scaling groups. * * @param options the filter parameters * @return filtered list of scaling groups */ @Override public Collection<ScalingGroup> listScalingGroups(AutoScalingGroupFilterOptions options) throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.listScalingGroups"); try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context has been set for this request"); } ArrayList<ScalingGroup> list = new ArrayList<ScalingGroup>(); Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DESCRIBE_AUTO_SCALING_GROUPS); EC2Method method; NodeList blocks; Document doc; method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { doc = method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } blocks = doc.getElementsByTagName("AutoScalingGroups"); for( int i=0; i<blocks.getLength(); i++ ) { NodeList items = blocks.item(i).getChildNodes(); for( int j=0; j<items.getLength(); j++ ) { Node item = items.item(j); if( item.getNodeName().equals("member") ) { ScalingGroup group = toScalingGroup(ctx, item); if( (group != null && (options != null && !options.hasCriteria())) || (group != null && (options != null && options.hasCriteria() && options.matches(group))) ) { list.add(group); } } } } return list; } finally { APITrace.end(); } } @Override public @Nonnull String[] mapServiceAction(@Nonnull ServiceAction action) { if( action.equals(AutoScalingSupport.ANY) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + "*" }; } if( action.equals(AutoScalingSupport.CREATE_LAUNCH_CONFIGURATION) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.CREATE_LAUNCH_CONFIGURATION }; } else if( action.equals(AutoScalingSupport.CREATE_SCALING_GROUP) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.CREATE_AUTO_SCALING_GROUP }; } else if( action.equals(AutoScalingSupport.GET_LAUNCH_CONFIGURATION) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.DESCRIBE_LAUNCH_CONFIGURATIONS }; } else if( action.equals(AutoScalingSupport.GET_SCALING_GROUP) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.DESCRIBE_AUTO_SCALING_GROUPS }; } else if( action.equals(AutoScalingSupport.LIST_LAUNCH_CONFIGURATION) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.DESCRIBE_LAUNCH_CONFIGURATIONS }; } else if( action.equals(AutoScalingSupport.LIST_SCALING_GROUP) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.DESCRIBE_AUTO_SCALING_GROUPS }; } else if( action.equals(AutoScalingSupport.REMOVE_LAUNCH_CONFIGURATION) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.DELETE_LAUNCH_CONFIGURATION }; } else if( action.equals(AutoScalingSupport.REMOVE_SCALING_GROUP) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.DELETE_AUTO_SCALING_GROUP }; } else if( action.equals(AutoScalingSupport.SET_CAPACITY) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.SET_DESIRED_CAPACITY }; } else if( action.equals(AutoScalingSupport.SET_SCALING_TRIGGER) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.CREATE_OR_UPDATE_SCALING_TRIGGER }; } else if( action.equals(AutoScalingSupport.UPDATE_SCALING_GROUP) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.UPDATE_AUTO_SCALING_GROUP }; } else if( action.equals(AutoScalingSupport.SUSPEND_AUTO_SCALING_GROUP) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.SUSPEND_AUTO_SCALING_GROUP }; } else if( action.equals(AutoScalingSupport.RESUME_AUTO_SCALING_GROUP) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.RESUME_AUTO_SCALING_GROUP }; } else if( action.equals(AutoScalingSupport.PUT_SCALING_POLICY) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.PUT_SCALING_POLICY }; } else if( action.equals(AutoScalingSupport.DELETE_SCALING_POLICY) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.DELETE_SCALING_POLICY }; } else if( action.equals(AutoScalingSupport.LIST_SCALING_POLICIES) ) { return new String[] { EC2Method.AUTOSCALING_PREFIX + EC2Method.DESCRIBE_SCALING_POLICIES }; } return new String[0]; } @Override public void setDesiredCapacity(String scalingGroupId, int capacity) throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.setDesiredCapacity"); try { Map<String,String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.SET_DESIRED_CAPACITY); EC2Method method; parameters.put("AutoScalingGroupName", scalingGroupId); parameters.put("DesiredCapacity", String.valueOf(capacity)); method = new EC2Method(provider, getAutoScalingUrl(), parameters); try { method.invoke(); } catch( EC2Exception e ) { logger.error(e.getSummary()); throw new CloudException(e); } } finally { APITrace.end(); } } @Override public void updateTags( @Nonnull String[] providerScalingGroupIds, @Nonnull AutoScalingTag... tags ) throws CloudException, InternalException { APITrace.begin( provider, "AutoScaling.removeTags" ); try { handleTagRequest( EC2Method.UPDATE_AUTO_SCALING_GROUP_TAGS, providerScalingGroupIds, tags ); } finally { APITrace.end(); } } @Override public void removeTags( @Nonnull String[] providerScalingGroupIds, @Nonnull AutoScalingTag... tags ) throws CloudException, InternalException { APITrace.begin( provider, "AutoScaling.removeTags" ); try { handleTagRequest( EC2Method.DELETE_AUTO_SCALING_GROUP_TAGS, providerScalingGroupIds, tags ); } finally { APITrace.end(); } } private Collection<AutoScalingTag> getTagsForDelete(@Nullable Collection<AutoScalingTag> all, @Nonnull AutoScalingTag[] tags) { Collection<AutoScalingTag> result = null; if (all != null) { result = new ArrayList<AutoScalingTag>(); for (AutoScalingTag tag : all) { if (!isTagInTags(tag, tags)) { result.add(tag); } } } return result; } private boolean isTagInTags(@Nonnull AutoScalingTag tag, @Nonnull AutoScalingTag[] tags) { for (AutoScalingTag t : tags) { if (t.getKey().equals(tag.getKey())) { return true; } } return false; } private void handleTagRequest( @Nonnull String methodName, @Nonnull String[] providerScalingGroupIds, @Nonnull AutoScalingTag... tags ) throws CloudException, InternalException { Map<String, String> parameters = getAutoScalingParameters( provider.getContext(), methodName ); EC2Method method; addAutoScalingTagParameters( parameters, providerScalingGroupIds, tags ); if ( parameters.size() == 0 ) { return; } method = new EC2Method( provider, getAutoScalingUrl(), parameters ); try { method.invoke(); } catch ( EC2Exception e ) { logger.error( e.getSummary() ); throw new CloudException( e ); } } @Override public void setNotificationConfig(@Nonnull String scalingGroupId, @Nonnull String topicARN, @Nonnull String[] notificationTypes) throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.setNotificationConfig"); try { Map<String, String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.PUT_NOTIFICATION_CONFIGURATION); parameters.put("AutoScalingGroupName", scalingGroupId); parameters.put("TopicARN", topicARN); for (int i = 0; i < notificationTypes.length; i++) { parameters.put("NotificationTypes.member." + (i + 1), notificationTypes[i]); } EC2Method method = new EC2Method(provider, getAutoScalingUrl(), parameters); method.invoke(); } finally { APITrace.end(); } } @Override public Collection<AutoScalingGroupNotificationConfig> listNotificationConfigs( final String[] scalingGroupIds ) throws CloudException, InternalException { PopulatorThread<AutoScalingGroupNotificationConfig> populatorThread; provider.hold(); populatorThread = new PopulatorThread<AutoScalingGroupNotificationConfig>(new JiteratorPopulator<AutoScalingGroupNotificationConfig>() { @Override public void populate(@Nonnull Jiterator<AutoScalingGroupNotificationConfig> autoScalingGroupNotificationConfigs) throws Exception { try { populateNotificationConfig(autoScalingGroupNotificationConfigs, null, scalingGroupIds); } finally { provider.release(); } } }); populatorThread.populate(); return populatorThread.getResult(); } private void populateNotificationConfig(@Nonnull Jiterator<AutoScalingGroupNotificationConfig> asgNotificationConfig, @Nullable String token, String[] scalingGroupIds) throws CloudException, InternalException { APITrace.begin(provider, "AutoScaling.listNotificationConfigs"); try { Map<String, String> parameters = getAutoScalingParameters(provider.getContext(), EC2Method.DESCRIBE_NOTIFICATION_CONFIGURATIONS); AWSCloud.addValueIfNotNull(parameters, "NextToken", token); for (int i = 0; i < scalingGroupIds.length; i++) { AWSCloud.addValueIfNotNull(parameters, "AutoScalingGroupNames.member." + (i + 1), scalingGroupIds[i]); } EC2Method method = new EC2Method(provider, getAutoScalingUrl(), parameters); Document document = method.invoke(); NodeList blocks = document.getElementsByTagName("NotificationConfigurations"); if (blocks == null) return; NodeList result = blocks.item(0).getChildNodes(); for (int i = 0; i < result.getLength(); i++) { Node configNode = result.item(i); if (configNode.getNodeName().equalsIgnoreCase("member")) { AutoScalingGroupNotificationConfig nc = toASGNotificationConfig(configNode.getChildNodes()); if (nc != null) asgNotificationConfig.push(nc); } } blocks = document.getElementsByTagName("NextToken"); if( blocks != null && blocks.getLength() == 1 && blocks.item(0).hasChildNodes() ) { String nextToken = AWSCloud.getTextValue(blocks.item(0)); populateNotificationConfig(asgNotificationConfig, nextToken, scalingGroupIds); } } finally { APITrace.end(); } } private AutoScalingGroupNotificationConfig toASGNotificationConfig(NodeList attributes) { if (attributes != null && attributes.getLength() != 0) { AutoScalingGroupNotificationConfig result = new AutoScalingGroupNotificationConfig(); for (int i = 0; i < attributes.getLength(); i++) { Node attr = attributes.item(i); if (attr.getNodeName().equalsIgnoreCase("TopicARN")) { result.setTopic(attr.getFirstChild().getNodeValue()); } else if (attr.getNodeName().equalsIgnoreCase("AutoScalingGroupName")) { result.setAutoScalingGroupName(attr.getFirstChild().getNodeValue()); } else if (attr.getNodeName().equalsIgnoreCase("NotificationType")) { result.setNotificationType(attr.getFirstChild().getNodeValue()); } } return result; } return null; } static private void addAutoScalingTagParameters( @Nonnull Map<String, String> parameters, @Nonnull String[] providerScalingGroupIds, @Nonnull AutoScalingTag... tags ) { /** * unlike EC2's regular CreateTags call, for autoscaling we must add a set of tag parameters for each auto scaling group * http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_CreateOrUpdateTags.html */ int tagCounter = 1; for ( int i = 0; i < providerScalingGroupIds.length; i++ ) { for ( AutoScalingTag tag : tags ) { parameters.put( "Tags.member." + tagCounter + ".ResourceType", "auto-scaling-group" ); parameters.put( "Tags.member." + tagCounter + ".ResourceId", providerScalingGroupIds[i] ); parameters.put( "Tags.member." + tagCounter + ".Key", tag.getKey() ); if ( tag.getValue() != null ) { parameters.put( "Tags.member." + tagCounter + ".Value", tag.getValue() ); } parameters.put( "Tags.member." + tagCounter + ".PropagateAtLaunch", String.valueOf( tag.isPropagateAtLaunch() ) ); tagCounter++; } } } private @Nullable ResourceStatus toGroupStatus( @Nullable Node item) { if( item == null ) { return null; } NodeList attrs = item.getChildNodes(); String groupId = null; for( int i=0; i<attrs.getLength(); i++ ) { Node attr = attrs.item(i); if( attr.getNodeName().equalsIgnoreCase("AutoScalingGroupName") ) { groupId = attr.getFirstChild().getNodeValue(); } } if( groupId == null ) { return null; } return new ResourceStatus(groupId, true); } private @Nullable LaunchConfiguration toLaunchConfiguration(@Nullable Node item) { if( item == null ) { return null; } LaunchConfiguration cfg = new LaunchConfiguration(); NodeList attrs = item.getChildNodes(); for( int i=0; i<attrs.getLength(); i++ ) { Node attr = attrs.item(i); String name; name = attr.getNodeName(); if( name.equalsIgnoreCase("ImageId") ) { if(attr.getFirstChild() != null){ cfg.setProviderImageId(attr.getFirstChild().getNodeValue()); } } else if( name.equalsIgnoreCase("KeyName") ) { if(attr.getFirstChild() != null){ cfg.setProviderKeypairName(attr.getFirstChild().getNodeValue()); } } else if( name.equalsIgnoreCase("LaunchConfigurationARN") ) { if(attr.getFirstChild() != null){ cfg.setId(attr.getFirstChild().getNodeValue()); } } else if( name.equalsIgnoreCase("UserData") ) { if(attr.getFirstChild() != null){ cfg.setUserData(attr.getFirstChild().getNodeValue()); } } else if( name.equalsIgnoreCase("InstanceType") ) { if(attr.getFirstChild() != null){ cfg.setServerSizeId(attr.getFirstChild().getNodeValue()); } } else if( name.equalsIgnoreCase("LaunchConfigurationName") ) { if(attr.getFirstChild() != null){ String lcname = attr.getFirstChild().getNodeValue(); cfg.setProviderLaunchConfigurationId(lcname); cfg.setName(lcname); } } else if( name.equalsIgnoreCase("CreatedTime") ) { SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); try { cfg.setCreationTimestamp(fmt.parse(attr.getFirstChild().getNodeValue()).getTime()); } catch( ParseException e ) { logger.error("Could not parse timestamp: " + attr.getFirstChild().getNodeValue()); cfg.setCreationTimestamp(System.currentTimeMillis()); } } else if( name.equalsIgnoreCase("SecurityGroups") ) { String[] ids; if( attr.hasChildNodes() ) { ArrayList<String> securityIds = new ArrayList<String>(); NodeList securityGroups = attr.getChildNodes(); for( int j=0; j<securityGroups.getLength(); j++ ) { Node securityGroup = securityGroups.item(j); if( securityGroup.getNodeName().equalsIgnoreCase("member") ) { if( securityGroup.hasChildNodes() ) { securityIds.add(securityGroup.getFirstChild().getNodeValue()); } } } ids = new String[securityIds.size()]; int j=0; for( String securityId : securityIds ) { ids[j++] = securityId; } } else { ids = new String[0]; } cfg.setProviderFirewallIds(ids); } else if( name.equalsIgnoreCase("IamInstanceProfile") ) { if(attr.getFirstChild() != null){ String providerId = attr.getFirstChild().getNodeValue(); cfg.setProviderRoleId(providerId); } } else if ( "InstanceMonitoring".equals(name) && attr.hasChildNodes() ) { NodeList details = attr.getChildNodes(); for (int j = 0; j < details.getLength(); j++) { Node detail = details.item(j); name = detail.getNodeName(); if (name.equals("Enabled")) { if (detail.hasChildNodes()) { String value = detail.getFirstChild().getNodeValue().trim(); cfg.setDetailedMonitoring( Boolean.valueOf( value ) ); } } } } else if( name.equalsIgnoreCase("AssociatePublicIpAddress") ) { if(attr.getFirstChild() != null){ cfg.setAssociatePublicIPAddress( Boolean.valueOf(attr.getFirstChild().getNodeValue()) ); } } else if( name.equalsIgnoreCase("EbsOptimized") ) { if(attr.getFirstChild() != null){ cfg.setIoOptimized(Boolean.valueOf(attr.getFirstChild().getNodeValue())); } } else if( name.equalsIgnoreCase("BlockDeviceMappings") ) { ArrayList<VolumeAttachment> VAs = new ArrayList<VolumeAttachment>(); VolumeAttachment[] VAArray; if( attr.hasChildNodes() ) { NodeList blockDeviceMaps = attr.getChildNodes(); for( int j=0; j<blockDeviceMaps.getLength(); j++ ) { Node blockDeviceMap = blockDeviceMaps.item(j); if( blockDeviceMap.getNodeName().equalsIgnoreCase("member") ) { VolumeAttachment va = new VolumeAttachment(); if( blockDeviceMap.hasChildNodes() ) { NodeList blockDeviceChildren = blockDeviceMap.getChildNodes(); for( int y=0; y<blockDeviceChildren.getLength(); y++ ) { Node blockDeviceChild = blockDeviceChildren.item(y); String blockDeviceChildName = blockDeviceChild.getNodeName(); if( blockDeviceChildName.equalsIgnoreCase("DeviceName") ) { String value = blockDeviceChild.getFirstChild().getNodeValue().trim(); va.setDeviceId(value); } else if( blockDeviceChildName.equalsIgnoreCase("Ebs") ) { if( blockDeviceChild.hasChildNodes() ) { NodeList ebsChildren = blockDeviceChild.getChildNodes(); int size = 0; String iops = null; String snapShotId = null; String volumeType = null; for( int q=0; q<ebsChildren.getLength(); q++ ) { Node ebsChild = ebsChildren.item(q); String ebsChildName = ebsChild.getNodeName(); if( ebsChildName.equalsIgnoreCase("Iops") ) { iops = ebsChild.getFirstChild().getNodeValue().trim(); } else if( ebsChildName.equalsIgnoreCase("VolumeSize") ) { String value = ebsChild.getFirstChild().getNodeValue().trim(); size = Integer.parseInt(value); } else if( ebsChildName.equalsIgnoreCase("SnapshotId") ) { snapShotId = ebsChild.getFirstChild().getNodeValue().trim(); } else if( ebsChildName.equalsIgnoreCase("VolumeType") ) { volumeType = ebsChild.getFirstChild().getNodeValue().trim(); } } VolumeCreateOptions vco = VolumeCreateOptions.getInstance( new Storage<Gigabyte>(size, Storage.GIGABYTE), "", "" ); try { vco.setIops( Integer.parseInt( iops ) ); } catch( NumberFormatException nfe ) { vco.setIops( 0 ); } vco.setSnapshotId( snapShotId ); vco.setVolumeProductId( volumeType ); va.setVolumeToCreate( vco ); } } } VAs.add( va ); } } } VAArray = new VolumeAttachment[VAs.size()]; int v=0; for( VolumeAttachment va : VAs ) { VAArray[v++] = va; } } else { VAArray = new VolumeAttachment[0]; } cfg.setVolumeAttachment( VAArray ); } } return cfg; } private @Nullable ResourceStatus toLCStatus(@Nullable Node item) { if( item == null ) { return null; } NodeList attrs = item.getChildNodes(); String lcId = null; for( int i=0; i<attrs.getLength(); i++ ) { Node attr = attrs.item(i); if( attr.getNodeName().equalsIgnoreCase("LaunchConfigurationName") ) { lcId = attr.getFirstChild().getNodeValue(); } } if( lcId == null ) { return null; } return new ResourceStatus(lcId, true); } private @Nullable ScalingGroup toScalingGroup(@Nonnull ProviderContext ctx, @Nullable Node item) { if( item == null ) { return null; } NodeList attrs = item.getChildNodes(); ScalingGroup group = new ScalingGroup(); group.setProviderOwnerId(ctx.getAccountNumber()); group.setProviderRegionId(ctx.getRegionId()); for( int i=0; i<attrs.getLength(); i++ ) { Node attr = attrs.item(i); String name; name = attr.getNodeName(); if( name.equalsIgnoreCase("MinSize") ) { group.setMinServers(Integer.parseInt(attr.getFirstChild().getNodeValue())); } else if( name.equalsIgnoreCase("MaxSize") ) { group.setMaxServers(Integer.parseInt(attr.getFirstChild().getNodeValue())); } else if( name.equalsIgnoreCase("DefaultCooldown") ) { group.setDefaultCooldown(Integer.parseInt(attr.getFirstChild().getNodeValue())); } else if( name.equalsIgnoreCase("CreatedTime") ) { SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); try { group.setCreationTimestamp(fmt.parse(attr.getFirstChild().getNodeValue()).getTime()); } catch( ParseException e ) { logger.error("Could not parse timestamp: " + attr.getFirstChild().getNodeValue()); group.setCreationTimestamp(System.currentTimeMillis()); } } else if( name.equalsIgnoreCase("DesiredCapacity") ) { group.setTargetCapacity(Integer.parseInt(attr.getFirstChild().getNodeValue())); } else if( name.equalsIgnoreCase("LaunchConfigurationName") ) { group.setProviderLaunchConfigurationId(attr.getFirstChild().getNodeValue()); } else if( name.equalsIgnoreCase("AutoScalingGroupARN") ) { group.setId(attr.getFirstChild().getNodeValue()); } else if( name.equalsIgnoreCase("HealthCheckGracePeriod") ) { group.setHealthCheckGracePeriod(Integer.parseInt(attr.getFirstChild().getNodeValue())); } else if( name.equalsIgnoreCase("HealthCheckType") ) { group.setHealthCheckType(attr.getFirstChild().getNodeValue()); } else if( name.equalsIgnoreCase("Status") ) { group.setStatus(attr.getFirstChild().getNodeValue()); } else if( name.equalsIgnoreCase("VPCZoneIdentifier") ) { Node subnetChild = attr.getFirstChild(); if( subnetChild != null ) { String subnets = subnetChild.getNodeValue(); group.setSubnets( subnets.contains(",") ? subnets.split("\\s*,\\s*") : new String[]{subnets} ); } } else if( name.equalsIgnoreCase("AutoScalingGroupName") ) { String gname = attr.getFirstChild().getNodeValue(); group.setProviderScalingGroupId(gname); group.setName(gname); group.setDescription(gname); } else if( name.equalsIgnoreCase("Instances") ) { String[] ids; if( attr.hasChildNodes() ) { ArrayList<String> instanceIds = new ArrayList<String>(); NodeList instances = attr.getChildNodes(); for( int j=0; j<instances.getLength(); j++ ) { Node instance = instances.item(j); if( instance.getNodeName().equals("member") ) { if( instance.hasChildNodes() ) { NodeList items = instance.getChildNodes(); for( int k=0; k<items.getLength(); k++ ) { Node val = items.item(k); if( val.getNodeName().equalsIgnoreCase("InstanceId") ) { instanceIds.add(val.getFirstChild().getNodeValue()); } } } } } ids = new String[instanceIds.size()]; int j=0; for( String id : instanceIds ) { ids[j++] = id; } } else { ids = new String[0]; } group.setProviderServerIds(ids); } else if( name.equalsIgnoreCase("AvailabilityZones") ) { String[] ids; if( attr.hasChildNodes() ) { ArrayList<String> zoneIds = new ArrayList<String>(); NodeList zones = attr.getChildNodes(); for( int j=0; j<zones.getLength(); j++ ) { Node zone = zones.item(j); if( zone.getNodeName().equalsIgnoreCase("member") ) { zoneIds.add(zone.getFirstChild().getNodeValue()); } } ids = new String[zoneIds.size()]; int j=0; for( String zoneId : zoneIds ) { ids[j++] = zoneId; } } else { ids = new String[0]; } group.setProviderDataCenterIds(ids); } else if( name.equalsIgnoreCase("EnabledMetrics") ) { String[] names; if( attr.hasChildNodes() ) { ArrayList<String> metricNames = new ArrayList<String>(); NodeList metrics = attr.getChildNodes(); for( int j=0; j< metrics.getLength(); j++ ) { Node metric = metrics.item(j); if( metric.getNodeName().equalsIgnoreCase("Metric") ) { metricNames.add(metric.getFirstChild().getNodeValue()); } } names = new String[metricNames.size()]; int j=0; for( String metricName : metricNames ) { names[j++] = metricName; } } else { names = new String[0]; } group.setEnabledMetrics(names); } else if( name.equalsIgnoreCase("LoadBalancerNames") ) { String[] names; if( attr.hasChildNodes() ) { ArrayList<String> lbNames = new ArrayList<String>(); NodeList loadBalancers = attr.getChildNodes(); for( int j=0; j< loadBalancers.getLength(); j++ ) { Node lb = loadBalancers.item(j); if( lb.getNodeName().equalsIgnoreCase("member") ) { lbNames.add(lb.getFirstChild().getNodeValue()); } } names = new String[lbNames.size()]; int j=0; for( String lbName : lbNames ) { names[j++] = lbName; } } else { names = new String[0]; } group.setProviderLoadBalancerNames(names); } else if( name.equalsIgnoreCase("SuspendedProcesses") ) { Collection<String[]> processes; if( attr.hasChildNodes() ) { ArrayList<String[]> processList = new ArrayList<String[]>(); NodeList processesList = attr.getChildNodes(); for( int j=0; j< processesList.getLength(); j++ ) { Node processParent = processesList.item(j); ArrayList<String> theProcess = new ArrayList<String>(); if( processParent.getNodeName().equals("member") ) { if( processParent.hasChildNodes() ) { NodeList items = processParent.getChildNodes(); for( int k=0; k<items.getLength(); k++ ) { Node val = items.item(k); if( val.getNodeName().equalsIgnoreCase("SuspensionReason") ) { theProcess.add(val.getFirstChild().getNodeValue()); } // seems to come second... if( val.getNodeName().equalsIgnoreCase("ProcessName") ) { theProcess.add(val.getFirstChild().getNodeValue()); } } } } if(theProcess.size() > 0){ String[] stringArr = new String[theProcess.size()]; stringArr = theProcess.toArray(stringArr); processList.add(stringArr); } } processes = processList; } else { processes = new ArrayList<String[]>(); } group.setSuspendedProcesses(processes); } else if( name.equalsIgnoreCase("TerminationPolicies") ) { String[] policies; if( attr.hasChildNodes() ) { ArrayList<String> subPolicies = new ArrayList<String>(); NodeList policyList = attr.getChildNodes(); for( int j=0; j< policyList.getLength(); j++ ) { Node lb = policyList.item(j); if( lb.getNodeName().equalsIgnoreCase("member") ) { subPolicies.add(lb.getFirstChild().getNodeValue()); } } policies = new String[subPolicies.size()]; int j=0; for( String policyString : subPolicies ) { policies[j++] = policyString; } } else { policies = new String[0]; } group.setTerminationPolicies(policies); } else if (name.equalsIgnoreCase("Tags") && attr.hasChildNodes()) { ArrayList<AutoScalingTag> tags = new ArrayList<AutoScalingTag>(); NodeList tagList = attr.getChildNodes(); for (int j = 0; j < tagList.getLength(); j++) { Node parent = tagList.item(j); if (parent.getNodeName().equals("member") && parent.hasChildNodes()) { String key = null; String value = null; Boolean propagateAtLaunch = null; NodeList memberNodes = parent.getChildNodes(); for (int k = 0; k < memberNodes.getLength(); k++) { Node val = memberNodes.item(k); if (val.getNodeName().equalsIgnoreCase("Key")) { key = AWSCloud.getTextValue(val); } else if (val.getNodeName().equalsIgnoreCase("Value")) { value = AWSCloud.getTextValue(val); } else if (val.getNodeName().equalsIgnoreCase("PropagateAtLaunch")) { propagateAtLaunch = AWSCloud.getBooleanValue(val); } } tags.add(new AutoScalingTag(key, value, propagateAtLaunch)); } } if (tags.size() > 0) { group.setTags(tags.toArray(new AutoScalingTag[tags.size()])); } } } return group; } private @Nullable ScalingPolicy toScalingPolicy(@Nullable Node item) { if( item == null ) { return null; } ScalingPolicy sp = new ScalingPolicy(); NodeList attrs = item.getChildNodes(); for( int i=0; i<attrs.getLength(); i++ ) { Node attr = attrs.item(i); String name; name = attr.getNodeName(); if( name.equalsIgnoreCase("AdjustmentType") ) { if(attr.getFirstChild() != null){ sp.setAdjustmentType(attr.getFirstChild().getNodeValue()); } } else if( name.equalsIgnoreCase("Alarms") ) { Collection<Alarm> alarms; if( attr.hasChildNodes() ) { ArrayList<Alarm> alarmList = new ArrayList<Alarm>(); NodeList alarmsList = attr.getChildNodes(); for( int j=0; j< alarmsList.getLength(); j++ ) { Node alarmParent = alarmsList.item(j); Alarm anAlarm = new Alarm(); if( alarmParent.getNodeName().equals("member") ) { if( alarmParent.hasChildNodes() ) { NodeList items = alarmParent.getChildNodes(); for( int k=0; k<items.getLength(); k++ ) { Node val = items.item(k); if( val.getNodeName().equalsIgnoreCase("AlarmARN") ) { anAlarm.setId(val.getFirstChild().getNodeValue()); } if( val.getNodeName().equalsIgnoreCase("AlarmName") ) { anAlarm.setName(val.getFirstChild().getNodeValue()); } } alarmList.add(anAlarm); } } } alarms = alarmList; } else { alarms = new ArrayList<Alarm>(); } Alarm[] alarmArr = new Alarm[alarms.size()]; alarmArr = alarms.toArray(alarmArr); sp.setAlarms(alarmArr); } else if( name.equalsIgnoreCase("AutoScalingGroupName") ) { if(attr.getFirstChild() != null){ sp.setAutoScalingGroupName(attr.getFirstChild().getNodeValue()); } } else if( name.equalsIgnoreCase("Cooldown") ) { if(attr.getFirstChild() != null){ sp.setCoolDown(Integer.parseInt(attr.getFirstChild().getNodeValue())); } } else if( name.equalsIgnoreCase("MinAdjustmentStep") ) { if(attr.getFirstChild() != null){ sp.setMinAdjustmentStep(Integer.parseInt(attr.getFirstChild().getNodeValue())); } } else if( name.equalsIgnoreCase("PolicyARN") ) { if(attr.getFirstChild() != null){ sp.setId(attr.getFirstChild().getNodeValue()); } } else if( name.equalsIgnoreCase("PolicyName") ) { if(attr.getFirstChild() != null){ sp.setName(attr.getFirstChild().getNodeValue()); } } else if( name.equalsIgnoreCase("ScalingAdjustment") ) { if(attr.getFirstChild() != null){ sp.setScalingAdjustment(Integer.parseInt(attr.getFirstChild().getNodeValue())); } } } return sp; } }
rename subnets to providerSubnetIds (#1298)
src/main/java/org/dasein/cloud/aws/compute/AutoScaling.java
rename subnets to providerSubnetIds (#1298)
<ide><path>rc/main/java/org/dasein/cloud/aws/compute/AutoScaling.java <ide> Node subnetChild = attr.getFirstChild(); <ide> if( subnetChild != null ) { <ide> String subnets = subnetChild.getNodeValue(); <del> group.setSubnets( subnets.contains(",") ? subnets.split("\\s*,\\s*") : new String[]{subnets} ); <add> group.setProviderSubnetIds( subnets.contains(",") ? subnets.split("\\s*,\\s*") : new String[]{subnets} ); <ide> } <ide> } <ide> else if( name.equalsIgnoreCase("AutoScalingGroupName") ) {
Java
apache-2.0
13f9acc4f1055897593617521001e63473a56892
0
godwin668/carsample
package com.gaocy.sample.model; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.gaocy.sample.vo.ModelVo; import org.apache.commons.io.FileUtils; import java.io.File; import java.util.HashMap; import java.util.Map; /** * Created by godwin on 2017-06-06. */ public class YouxinpaiModel { public static Map<String, ModelVo> seriesMap = new HashMap<String, ModelVo>(); static { loadSeries(); } private static void loadSeries() { ClassLoader classLoader = YouxinpaiModel.class.getClassLoader(); File file = new File(classLoader.getResource("model/youxinpai_series.txt").getFile()); try { String modelStr = FileUtils.readFileToString(file, "UTF-8"); JSONArray jsonArr = JSON.parseArray(modelStr); for (Object obj : jsonArr) { JSONObject jsonObj = (JSONObject) obj; Integer brandId = jsonObj.getInteger("brandId"); Integer carBrandId = jsonObj.getInteger("carBrandId"); String brandName = jsonObj.getString("brandName"); JSONArray seriesJsonArr = jsonObj.getJSONArray("carSerialList"); System.out.println(brandId + "_" + carBrandId + "_" + brandName + ": " + seriesJsonArr); for (Object seriesJson : seriesJsonArr) { JSONObject seriesJsonObj = (JSONObject) seriesJson; Integer carMakeId = seriesJsonObj.getInteger("carMakeId"); String makeName = seriesJsonObj.getString("makeName"); Integer seriesId = seriesJsonObj.getInteger("seiralId"); Integer carSeriesId = seriesJsonObj.getInteger("carSeiralId"); String seriesName = seriesJsonObj.getString("seiralName"); System.out.println(brandName + "(" + carBrandId + "), " + seriesName + "(" + carSeriesId + ")"); } } } catch (Exception e) { e.printStackTrace(); } } public static Map<String, ModelVo> getSeriesMap() { return seriesMap; } public static ModelVo getSeries(String seriesId) { return seriesMap.get(seriesId); } public static void main(String[] args) { } }
src/main/java/com/gaocy/sample/model/YouxinpaiModel.java
package com.gaocy.sample.model; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.gaocy.sample.spider.SpiderBase; import com.gaocy.sample.util.HttpClientUtil; import com.gaocy.sample.vo.ModelVo; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by godwin on 2017-06-06. */ public class YouxinpaiModel { public static Map<String, ModelVo> seriesMap = new HashMap<String, ModelVo>(); static { loadSeries(); } private static void loadSeries() { ClassLoader classLoader = YouxinpaiModel.class.getClassLoader(); File file = new File(classLoader.getResource("model/youxinpai_series.txt").getFile()); try { String modelStr = FileUtils.readFileToString(file, "UTF-8"); JSONArray jsonArr = JSON.parseArray(modelStr); for (Object obj : jsonArr) { JSONObject jsonObj = (JSONObject) obj; Integer brandId = jsonObj.getInteger("brandId"); Integer carBrandId = jsonObj.getInteger("carBrandId"); String brandName = jsonObj.getString("brandName"); JSONArray seriesJsonArr = jsonObj.getJSONArray("carSerialList"); System.out.println(brandId + "_" + carBrandId + "_" + brandName + ": " + seriesJsonArr); for (Object seriesJson : seriesJsonArr) { JSONObject seriesJsonObj = (JSONObject) seriesJson; Integer carMakeId = seriesJsonObj.getInteger("carMakeId"); Integer makeName = seriesJsonObj.getInteger("makeName"); Integer seiralId = seriesJsonObj.getInteger("seiralId"); Integer carSeiralId = seriesJsonObj.getInteger("carSeiralId"); Integer seiralName = seriesJsonObj.getInteger("seiralName"); System.out.println(); } } } catch (Exception e) { e.printStackTrace(); } } public static Map<String, ModelVo> getSeriesMap() { return seriesMap; } public static ModelVo getSeries(String seriesId) { return seriesMap.get(seriesId); } public static void main(String[] args) { } }
*) update
src/main/java/com/gaocy/sample/model/YouxinpaiModel.java
*) update
<ide><path>rc/main/java/com/gaocy/sample/model/YouxinpaiModel.java <ide> import com.alibaba.fastjson.JSON; <ide> import com.alibaba.fastjson.JSONArray; <ide> import com.alibaba.fastjson.JSONObject; <del>import com.gaocy.sample.spider.SpiderBase; <del>import com.gaocy.sample.util.HttpClientUtil; <ide> import com.gaocy.sample.vo.ModelVo; <ide> import org.apache.commons.io.FileUtils; <del>import org.apache.commons.lang3.StringEscapeUtils; <del>import org.apache.commons.lang3.StringUtils; <ide> <ide> import java.io.File; <ide> import java.util.HashMap; <del>import java.util.List; <ide> import java.util.Map; <ide> <ide> /** <ide> try { <ide> String modelStr = FileUtils.readFileToString(file, "UTF-8"); <ide> JSONArray jsonArr = JSON.parseArray(modelStr); <del> <ide> for (Object obj : jsonArr) { <ide> JSONObject jsonObj = (JSONObject) obj; <ide> Integer brandId = jsonObj.getInteger("brandId"); <ide> for (Object seriesJson : seriesJsonArr) { <ide> JSONObject seriesJsonObj = (JSONObject) seriesJson; <ide> Integer carMakeId = seriesJsonObj.getInteger("carMakeId"); <del> Integer makeName = seriesJsonObj.getInteger("makeName"); <del> Integer seiralId = seriesJsonObj.getInteger("seiralId"); <del> Integer carSeiralId = seriesJsonObj.getInteger("carSeiralId"); <del> Integer seiralName = seriesJsonObj.getInteger("seiralName"); <del> System.out.println(); <add> String makeName = seriesJsonObj.getString("makeName"); <add> Integer seriesId = seriesJsonObj.getInteger("seiralId"); <add> Integer carSeriesId = seriesJsonObj.getInteger("carSeiralId"); <add> String seriesName = seriesJsonObj.getString("seiralName"); <add> System.out.println(brandName + "(" + carBrandId + "), " + seriesName + "(" + carSeriesId + ")"); <ide> } <ide> } <ide> } catch (Exception e) {
JavaScript
agpl-3.0
56eed344f5dbb348e2e8768c37f1b84dfc0c13b4
0
robamler/zotero,LinuxMercedes/zotero,sendecomp/zotero,egh/zotero,gracile-fr/zotero,egh/zotero,gracile-fr/zotero,robamler/zotero,egh/zotero,fbennett/zotero,retorquere/zotero,hoehnp/zotero,LinuxMercedes/zotero,gracile-fr/zotero,sendecomp/zotero,adunning/zotero,adunning/zotero,rmzelle/zotero,hoehnp/zotero,retorquere/zotero,robamler/zotero,LinuxMercedes/zotero,adunning/zotero,rmzelle/zotero,retorquere/zotero,aurimasv/zotero,sendecomp/zotero,rmzelle/zotero,hoehnp/zotero
/* ***** BEGIN LICENSE BLOCK ***** Copyright © 2009 Center for History and New Media George Mason University, Fairfax, Virginia, USA http://zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see <http://www.gnu.org/licenses/>. ***** END LICENSE BLOCK ***** */ const ZOTERO_TAB_URL = "chrome://zotero/content/tab.xul"; /* * This object contains the various functions for the interface */ var ZoteroPane = new function() { this.collectionsView = false; this.itemsView = false; this.__defineGetter__('loaded', function () _loaded); //Privileged methods this.init = init; this.destroy = destroy; this.makeVisible = makeVisible; this.isShowing = isShowing; this.isFullScreen = isFullScreen; this.handleKeyDown = handleKeyDown; this.handleKeyUp = handleKeyUp; this.setHighlightedRowsCallback = setHighlightedRowsCallback; this.handleKeyPress = handleKeyPress; this.newItem = newItem; this.newCollection = newCollection; this.newSearch = newSearch; this.openAdvancedSearchWindow = openAdvancedSearchWindow; this.toggleTagSelector = toggleTagSelector; this.updateTagSelectorSize = updateTagSelectorSize; this.getTagSelection = getTagSelection; this.clearTagSelection = clearTagSelection; this.updateTagFilter = updateTagFilter; this.onCollectionSelected = onCollectionSelected; this.itemSelected = itemSelected; this.reindexItem = reindexItem; this.duplicateSelectedItem = duplicateSelectedItem; this.editSelectedCollection = editSelectedCollection; this.copySelectedItemsToClipboard = copySelectedItemsToClipboard; this.clearQuicksearch = clearQuicksearch; this.handleSearchKeypress = handleSearchKeypress; this.handleSearchInput = handleSearchInput; this.search = search; this.selectItem = selectItem; this.getSelectedCollection = getSelectedCollection; this.getSelectedSavedSearch = getSelectedSavedSearch; this.getSelectedItems = getSelectedItems; this.getSortedItems = getSortedItems; this.getSortField = getSortField; this.getSortDirection = getSortDirection; this.buildItemContextMenu = buildItemContextMenu; this.loadURI = loadURI; this.setItemsPaneMessage = setItemsPaneMessage; this.clearItemsPaneMessage = clearItemsPaneMessage; this.contextPopupShowing = contextPopupShowing; this.openNoteWindow = openNoteWindow; this.addTextToNote = addTextToNote; this.addAttachmentFromDialog = addAttachmentFromDialog; this.viewAttachment = viewAttachment; this.viewSelectedAttachment = viewSelectedAttachment; this.showAttachmentNotFoundDialog = showAttachmentNotFoundDialog; this.relinkAttachment = relinkAttachment; this.reportErrors = reportErrors; this.displayErrorMessage = displayErrorMessage; this.document = document; const COLLECTIONS_HEIGHT = 32; // minimum height of the collections pane and toolbar var self = this; var _loaded = false; var titlebarcolorState, titleState, observerService; var _reloadFunctions = []; // Also needs to be changed in collectionTreeView.js var _lastViewedFolderRE = /^(?:(C|S|G)([0-9]+)|L)$/; /** * Called when the window containing Zotero pane is open */ function init() { // Set "Report Errors..." label via property rather than DTD entity, // since we need to reference it in script elsewhere document.getElementById('zotero-tb-actions-reportErrors').setAttribute('label', Zotero.getString('errorReport.reportErrors')); // Set key down handler document.getElementById('appcontent').addEventListener('keydown', ZoteroPane_Local.handleKeyDown, true); if (Zotero.locked) { return; } _loaded = true; var zp = document.getElementById('zotero-pane'); Zotero.setFontSize(zp); ZoteroPane_Local.updateToolbarPosition(); window.addEventListener("resize", ZoteroPane_Local.updateToolbarPosition, false); window.setTimeout(ZoteroPane_Local.updateToolbarPosition, 0); Zotero.updateQuickSearchBox(document); if (Zotero.isMac) { //document.getElementById('zotero-tb-actions-zeroconf-update').setAttribute('hidden', false); document.getElementById('zotero-pane-stack').setAttribute('platform', 'mac'); } else if(Zotero.isWin) { document.getElementById('zotero-pane-stack').setAttribute('platform', 'win'); } if(Zotero.isFx4 || window.ZoteroTab) { // hack, since Fx 4 no longer sets active, and the reverse in polarity of the preferred // property makes things painful to handle otherwise // DEBUG: remove this once we only support Fx 4 zp.setAttribute("ignoreActiveAttribute", "true"); } // register an observer for Zotero reload observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); observerService.addObserver(_reload, "zotero-reloaded", false); this.addReloadListener(_loadPane); // continue loading pane _loadPane(); } /** * Called on window load or when has been reloaded after switching into or out of connector * mode */ function _loadPane() { if(!Zotero || !Zotero.initialized) return; if(Zotero.isConnector) { ZoteroPane_Local.setItemsPaneMessage(Zotero.getString('connector.standaloneOpen')); return; } else { ZoteroPane_Local.clearItemsPaneMessage(); } //Initialize collections view ZoteroPane_Local.collectionsView = new Zotero.CollectionTreeView(); var collectionsTree = document.getElementById('zotero-collections-tree'); collectionsTree.view = ZoteroPane_Local.collectionsView; collectionsTree.controllers.appendController(new Zotero.CollectionTreeCommandController(collectionsTree)); collectionsTree.addEventListener("click", ZoteroPane_Local.onTreeClick, true); var itemsTree = document.getElementById('zotero-items-tree'); itemsTree.controllers.appendController(new Zotero.ItemTreeCommandController(itemsTree)); itemsTree.addEventListener("click", ZoteroPane_Local.onTreeClick, true); var menu = document.getElementById("contentAreaContextMenu"); menu.addEventListener("popupshowing", ZoteroPane_Local.contextPopupShowing, false); Zotero.Keys.windowInit(document); if (Zotero.restoreFromServer) { Zotero.restoreFromServer = false; setTimeout(function () { var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); var buttonFlags = (ps.BUTTON_POS_0) * (ps.BUTTON_TITLE_IS_STRING) + (ps.BUTTON_POS_1) * (ps.BUTTON_TITLE_CANCEL); var index = ps.confirmEx( null, "Zotero Restore", "The local Zotero database has been cleared." + " " + "Would you like to restore from the Zotero server now?", buttonFlags, "Sync Now", null, null, null, {} ); if (index == 0) { Zotero.Sync.Server.sync({ onSuccess: function () { Zotero.Sync.Runner.setSyncIcon(); ps.alert( null, "Restore Completed", "The local Zotero database has been successfully restored." ); }, onError: function (msg) { ps.alert( null, "Restore Failed", "An error occurred while restoring from the server:\n\n" + msg ); Zotero.Sync.Runner.error(msg); } }); } }, 1000); } // If the database was initialized or there are no sync credentials and // Zotero hasn't been run before in this profile, display the start page // -- this way the page won't be displayed when they sync their DB to // another profile or if the DB is initialized erroneously (e.g. while // switching data directory locations) else if (Zotero.Prefs.get('firstRun2') && !Zotero.isStandalone) { if (Zotero.Schema.dbInitialized || !Zotero.Sync.Server.enabled) { setTimeout(function () { var url = "http://zotero.org/start"; gBrowser.selectedTab = gBrowser.addTab(url); }, 400); } Zotero.Prefs.set('firstRun2', false); try { Zotero.Prefs.clear('firstRun'); } catch (e) {} } // Hide sync debugging menu by default if (Zotero.Prefs.get('sync.debugMenu')) { var sep = document.getElementById('zotero-tb-actions-sync-separator'); sep.hidden = false; sep.nextSibling.hidden = false; sep.nextSibling.nextSibling.hidden = false; sep.nextSibling.nextSibling.nextSibling.hidden = false; } if (Zotero.Prefs.get('debugShowDuplicates')) { document.getElementById('zotero-tb-actions-showDuplicates').hidden = false; } } /* * Create the New Item (+) submenu with each item type */ this.buildItemTypeSubMenu = function () { var moreMenu = document.getElementById('zotero-tb-add-more'); // Sort by localized name var t = Zotero.ItemTypes.getSecondaryTypes(); var itemTypes = []; for (var i=0; i<t.length; i++) { itemTypes.push({ id: t[i].id, name: t[i].name, localized: Zotero.ItemTypes.getLocalizedString(t[i].id) }); } var collation = Zotero.getLocaleCollation(); itemTypes.sort(function(a, b) { return collation.compareString(1, a.localized, b.localized); }); for (var i = 0; i<itemTypes.length; i++) { var menuitem = document.createElement("menuitem"); menuitem.setAttribute("label", itemTypes[i].localized); menuitem.setAttribute("oncommand","ZoteroPane_Local.newItem("+itemTypes[i]['id']+")"); menuitem.setAttribute("tooltiptext", ""); moreMenu.appendChild(menuitem); } } this.updateNewItemTypes = function () { var addMenu = document.getElementById('zotero-tb-add').firstChild; // Remove all nodes so we can regenerate var options = addMenu.getElementsByAttribute("class", "zotero-tb-add"); while (options.length) { var p = options[0].parentNode; p.removeChild(options[0]); } var separator = addMenu.firstChild; // Sort by localized name var t = Zotero.ItemTypes.getPrimaryTypes(); var itemTypes = []; for (var i=0; i<t.length; i++) { itemTypes.push({ id: t[i].id, name: t[i].name, localized: Zotero.ItemTypes.getLocalizedString(t[i].id) }); } var collation = Zotero.getLocaleCollation(); itemTypes.sort(function(a, b) { return collation.compareString(1, a.localized, b.localized); }); for (var i = 0; i<itemTypes.length; i++) { var menuitem = document.createElement("menuitem"); menuitem.setAttribute("label", itemTypes[i].localized); menuitem.setAttribute("oncommand","ZoteroPane_Local.newItem("+itemTypes[i]['id']+")"); menuitem.setAttribute("tooltiptext", ""); menuitem.className = "zotero-tb-add"; addMenu.insertBefore(menuitem, separator); } } /* * Called when the window closes */ function destroy() { if (!Zotero || !Zotero.initialized || !_loaded) { return; } if(this.isShowing()) { this.serializePersist(); } var tagSelector = document.getElementById('zotero-tag-selector'); tagSelector.unregister(); this.collectionsView.unregister(); if (this.itemsView) this.itemsView.unregister(); observerService.removeObserver(_reload, "zotero-reloaded", false); } /** * Called before Zotero pane is to be made visible * @return {Boolean} True if Zotero pane should be loaded, false otherwise (if an error * occurred) */ function makeVisible() { // If pane not loaded, load it or display an error message if (!ZoteroPane_Local.loaded) { if (Zotero.locked) { var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); var msg = Zotero.getString('general.operationInProgress') + '\n\n' + Zotero.getString('general.operationInProgress.waitUntilFinished'); ps.alert(null, "", msg); return false; } ZoteroPane_Local.init(); } // If Zotero could not be initialized, display an error message and return if(!Zotero || !Zotero.initialized) { this.displayStartupError(); return false; } this.buildItemTypeSubMenu(); this.unserializePersist(); this.updateToolbarPosition(); this.updateTagSelectorSize(); // restore saved row selection (for tab switching) var containerWindow = (window.ZoteroTab ? window.ZoteroTab.containerWindow : window); if(containerWindow.zoteroSavedCollectionSelection) { this.collectionsView.rememberSelection(containerWindow.zoteroSavedCollectionSelection); delete containerWindow.zoteroSavedCollectionSelection; } // restore saved item selection (for tab switching) if(containerWindow.zoteroSavedItemSelection) { var me = this; // hack to restore saved selection after itemTreeView finishes loading window.setTimeout(function() { if(containerWindow.zoteroSavedItemSelection) { me.itemsView.rememberSelection(containerWindow.zoteroSavedItemSelection); delete containerWindow.zoteroSavedItemSelection; } }, 51); } // Focus the quicksearch on pane open var searchBar = document.getElementById('zotero-tb-search'); setTimeout(function () { searchBar.inputField.select(); }, 1); // Auto-empty trashed items older than a certain number of days var days = Zotero.Prefs.get('trashAutoEmptyDays'); if (days) { var d = new Date(); var deleted = Zotero.Items.emptyTrash(days); var d2 = new Date(); Zotero.debug("Emptied old items from trash in " + (d2 - d) + " ms"); } var d = new Date(); Zotero.purgeDataObjects(); var d2 = new Date(); Zotero.debug("Purged data tables in " + (d2 - d) + " ms"); // Auto-sync on pane open if (Zotero.Prefs.get('sync.autoSync')) { setTimeout(function () { if (!Zotero.Sync.Server.enabled || Zotero.Sync.Server.syncInProgress || Zotero.Sync.Storage.syncInProgress) { Zotero.debug('Sync already running -- skipping auto-sync', 4); return; } if (Zotero.Sync.Server.manualSyncRequired) { Zotero.debug('Manual sync required -- skipping auto-sync', 4); return; } Zotero.Sync.Runner.sync(true); }, 1000); } // Set sync icon to spinning or not // // We don't bother setting an error state at open if (Zotero.Sync.Server.syncInProgress || Zotero.Sync.Storage.syncInProgress) { Zotero.Sync.Runner.setSyncIcon('animate'); } else { Zotero.Sync.Runner.setSyncIcon(); } return true; } /** * Function to be called before ZoteroPane_Local is hidden. Does not actually hide the Zotero pane. */ this.makeHidden = function() { this.serializePersist(); } function isShowing() { var zoteroPane = document.getElementById('zotero-pane-stack'); return zoteroPane.getAttribute('hidden') != 'true' && zoteroPane.getAttribute('collapsed') != 'true'; } function isFullScreen() { return document.getElementById('zotero-pane-stack').getAttribute('fullscreenmode') == 'true'; } /* * Trigger actions based on keyboard shortcuts */ function handleKeyDown(event, from) { try { // Ignore keystrokes outside of Zotero pane if (!(event.originalTarget.ownerDocument instanceof XULDocument)) { return; } } catch (e) { Zotero.debug(e); } if (Zotero.locked) { event.preventDefault(); return; } if (from == 'zotero-pane') { // Highlight collections containing selected items // // We use Control (17) on Windows because Alt triggers the menubar; // otherwise we use Alt/Option (18) if ((Zotero.isWin && event.keyCode == 17 && !event.altKey) || (!Zotero.isWin && event.keyCode == 18 && !event.ctrlKey) && !event.shiftKey && !event.metaKey) { this.highlightTimer = Components.classes["@mozilla.org/timer;1"]. createInstance(Components.interfaces.nsITimer); // {} implements nsITimerCallback this.highlightTimer.initWithCallback({ notify: ZoteroPane_Local.setHighlightedRowsCallback }, 225, Components.interfaces.nsITimer.TYPE_ONE_SHOT); } else if ((Zotero.isWin && event.ctrlKey) || (!Zotero.isWin && event.altKey)) { if (this.highlightTimer) { this.highlightTimer.cancel(); this.highlightTimer = null; } ZoteroPane_Local.collectionsView.setHighlightedRows(); } return; } // Ignore keystrokes if Zotero pane is closed var zoteroPane = document.getElementById('zotero-pane-stack'); if (zoteroPane.getAttribute('hidden') == 'true' || zoteroPane.getAttribute('collapsed') == 'true') { return; } var useShift = Zotero.isMac; var key = String.fromCharCode(event.which); if (!key) { Zotero.debug('No key'); return; } // Ignore modifiers other than Ctrl-Alt or Cmd-Shift if (!((Zotero.isMac ? event.metaKey : event.ctrlKey) && (useShift ? event.shiftKey : event.altKey))) { return; } var command = Zotero.Keys.getCommand(key); if (!command) { return; } Zotero.debug(command); // Errors don't seem to make it out otherwise try { switch (command) { case 'openZotero': try { // Ignore Cmd-Shift-Z keystroke in text areas if (Zotero.isMac && key == 'Z' && event.originalTarget.localName == 'textarea') { Zotero.debug('Ignoring keystroke in text area'); return; } } catch (e) { Zotero.debug(e); } if(window.ZoteroOverlay) window.ZoteroOverlay.toggleDisplay() break; case 'library': document.getElementById('zotero-collections-tree').focus(); ZoteroPane_Local.collectionsView.selection.select(0); break; case 'quicksearch': document.getElementById('zotero-tb-search').select(); break; case 'newItem': ZoteroPane_Local.newItem(2); // book var menu = document.getElementById('zotero-editpane-item-box').itemTypeMenu; menu.focus(); document.getElementById('zotero-editpane-item-box').itemTypeMenu.menupopup.openPopup(menu, "before_start", 0, 0); break; case 'newNote': // Use key that's not the modifier as the popup toggle ZoteroPane_Local.newNote(useShift ? event.altKey : event.shiftKey); break; case 'toggleTagSelector': ZoteroPane_Local.toggleTagSelector(); break; case 'toggleFullscreen': ZoteroPane_Local.toggleTab(); break; case 'copySelectedItemCitationsToClipboard': ZoteroPane_Local.copySelectedItemsToClipboard(true) break; case 'copySelectedItemsToClipboard': ZoteroPane_Local.copySelectedItemsToClipboard(); break; case 'importFromClipboard': Zotero_File_Interface.importFromClipboard(); break; default: throw ('Command "' + command + '" not found in ZoteroPane_Local.handleKeyDown()'); } } catch (e) { Zotero.debug(e, 1); Components.utils.reportError(e); } event.preventDefault(); } function handleKeyUp(event, from) { if (from == 'zotero-pane') { if ((Zotero.isWin && event.keyCode == 17) || (!Zotero.isWin && event.keyCode == 18)) { if (this.highlightTimer) { this.highlightTimer.cancel(); this.highlightTimer = null; } ZoteroPane_Local.collectionsView.setHighlightedRows(); } } } /* * Highlights collections containing selected items on Ctrl (Win) or * Option/Alt (Mac/Linux) press */ function setHighlightedRowsCallback() { var itemIDs = ZoteroPane_Local.getSelectedItems(true); if (itemIDs && itemIDs.length) { var collectionIDs = Zotero.Collections.getCollectionsContainingItems(itemIDs, true); if (collectionIDs) { ZoteroPane_Local.collectionsView.setHighlightedRows(collectionIDs); } } } function handleKeyPress(event, from) { if (from == 'zotero-collections-tree') { if ((event.keyCode == event.DOM_VK_BACK_SPACE && Zotero.isMac) || event.keyCode == event.DOM_VK_DELETE) { ZoteroPane_Local.deleteSelectedCollection(); event.preventDefault(); return; } } else if (from == 'zotero-items-tree') { if ((event.keyCode == event.DOM_VK_BACK_SPACE && Zotero.isMac) || event.keyCode == event.DOM_VK_DELETE) { // If Cmd/Ctrl delete, use forced mode, which does different // things depending on the context var force = event.metaKey || (!Zotero.isMac && event.ctrlKey); ZoteroPane_Local.deleteSelectedItems(force); event.preventDefault(); return; } } } /* * Create a new item * * _data_ is an optional object with field:value for itemData */ function newItem(typeID, data, row) { if (!Zotero.stateCheck()) { this.displayErrorMessage(true); return false; } // Currently selected row if (row === undefined) { row = this.collectionsView.selection.currentIndex; } if (!this.canEdit(row)) { this.displayCannotEditLibraryMessage(); return; } if (row !== undefined) { var itemGroup = this.collectionsView._getItemAtRow(row); var libraryID = itemGroup.ref.libraryID; } else { var libraryID = null; var itemGroup = null; } Zotero.DB.beginTransaction(); var item = new Zotero.Item(typeID); item.libraryID = libraryID; for (var i in data) { item.setField(i, data[i]); } var itemID = item.save(); if (itemGroup && itemGroup.isCollection()) { itemGroup.ref.addItem(itemID); } Zotero.DB.commitTransaction(); //set to Info tab document.getElementById('zotero-view-item').selectedIndex = 0; this.selectItem(itemID); // Update most-recently-used list for New Item menu var mru = Zotero.Prefs.get('newItemTypeMRU'); if (mru) { var mru = mru.split(','); var pos = mru.indexOf(typeID + ''); if (pos != -1) { mru.splice(pos, 1); } mru.unshift(typeID); } else { var mru = [typeID + '']; } Zotero.Prefs.set('newItemTypeMRU', mru.slice(0, 5).join(',')); return Zotero.Items.get(itemID); } function newCollection(parent) { if (!Zotero.stateCheck()) { this.displayErrorMessage(true); return false; } if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); var untitled = Zotero.DB.getNextName('collections', 'collectionName', Zotero.getString('pane.collections.untitled')); var newName = { value: untitled }; var result = promptService.prompt(window, Zotero.getString('pane.collections.newCollection'), Zotero.getString('pane.collections.name'), newName, "", {}); if (!result) { return; } if (!newName.value) { newName.value = untitled; } var collection = new Zotero.Collection; collection.libraryID = this.getSelectedLibraryID(); collection.name = newName.value; collection.parent = parent; collection.save(); } this.newGroup = function () { this.loadURI(Zotero.Groups.addGroupURL); } function newSearch() { if (!Zotero.stateCheck()) { this.displayErrorMessage(true); return false; } var s = new Zotero.Search(); s.libraryID = this.getSelectedLibraryID(); s.addCondition('title', 'contains', ''); var untitled = Zotero.getString('pane.collections.untitled'); untitled = Zotero.DB.getNextName('savedSearches', 'savedSearchName', Zotero.getString('pane.collections.untitled')); var io = {dataIn: {search: s, name: untitled}, dataOut: null}; window.openDialog('chrome://zotero/content/searchDialog.xul','','chrome,modal',io); } this.setUnfiled = function (libraryID, show) { try { var ids = Zotero.Prefs.get('unfiledLibraries').split(','); } catch (e) { var ids = []; } if (!libraryID) { libraryID = 0; } var newids = []; for each(var id in ids) { id = parseInt(id); if (isNaN(id)) { continue; } // Remove current library if hiding if (id == libraryID && !show) { continue; } // Remove libraryIDs that no longer exist if (id != 0 && !Zotero.Libraries.exists(id)) { continue; } newids.push(id); } // Add the current library if it's not already set if (show && newids.indexOf(libraryID) == -1) { newids.push(libraryID); } newids.sort(); Zotero.Prefs.set('unfiledLibraries', newids.join()); if (show) { // 'UNFILED' + '000' + libraryID Zotero.Prefs.set('lastViewedFolder', 'S' + '8634533000' + libraryID); } this.collectionsView.refresh(); // Select new row var row = this.collectionsView.getLastViewedRow(); this.collectionsView.selection.select(row); } this.openLookupWindow = function () { if (!Zotero.stateCheck()) { this.displayErrorMessage(true); return false; } if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } window.openDialog('chrome://zotero/content/lookup.xul', 'zotero-lookup', 'chrome,modal'); } function openAdvancedSearchWindow() { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var enumerator = wm.getEnumerator('zotero:search'); while (enumerator.hasMoreElements()) { var win = enumerator.getNext(); } if (win) { win.focus(); return; } var s = new Zotero.Search(); s.addCondition('title', 'contains', ''); var io = {dataIn: {search: s}, dataOut: null}; window.openDialog('chrome://zotero/content/advancedSearch.xul', '', 'chrome,dialog=no,centerscreen', io); } function toggleTagSelector(){ var tagSelector = document.getElementById('zotero-tag-selector'); var showing = tagSelector.getAttribute('collapsed') == 'true'; tagSelector.setAttribute('collapsed', !showing); this.updateTagSelectorSize(); // If showing, set scope to items in current view // and focus filter textbox if (showing) { _setTagScope(); tagSelector.focusTextbox(); } // If hiding, clear selection else { tagSelector.uninit(); } } function updateTagSelectorSize() { //Zotero.debug('Updating tag selector size'); var zoteroPane = document.getElementById('zotero-pane-stack'); var splitter = document.getElementById('zotero-tags-splitter'); var tagSelector = document.getElementById('zotero-tag-selector'); // Nothing should be bigger than appcontent's height var max = document.getElementById('appcontent').boxObject.height - splitter.boxObject.height; // Shrink tag selector to appcontent's height var maxTS = max - COLLECTIONS_HEIGHT; if (parseInt(tagSelector.getAttribute("height")) > maxTS) { //Zotero.debug("Limiting tag selector height to appcontent"); tagSelector.setAttribute('height', maxTS); } var height = tagSelector.boxObject.height; /*Zotero.debug("tagSelector.boxObject.height: " + tagSelector.boxObject.height); Zotero.debug("tagSelector.getAttribute('height'): " + tagSelector.getAttribute('height')); Zotero.debug("zoteroPane.boxObject.height: " + zoteroPane.boxObject.height); Zotero.debug("zoteroPane.getAttribute('height'): " + zoteroPane.getAttribute('height'));*/ // Don't let the Z-pane jump back down to its previous height // (if shrinking or hiding the tag selector let it clear the min-height) if (zoteroPane.getAttribute('height') < zoteroPane.boxObject.height) { //Zotero.debug("Setting Zotero pane height attribute to " + zoteroPane.boxObject.height); zoteroPane.setAttribute('height', zoteroPane.boxObject.height); } if (tagSelector.getAttribute('collapsed') == 'true') { // 32px is the default Z pane min-height in overlay.css height = 32; } else { // tS.boxObject.height doesn't exist at startup, so get from attribute if (!height) { height = parseInt(tagSelector.getAttribute('height')); } // 121px seems to be enough room for the toolbar and collections // tree at minimum height height = height + COLLECTIONS_HEIGHT; } //Zotero.debug('Setting Zotero pane minheight to ' + height); zoteroPane.setAttribute('minheight', height); if (this.isShowing() && !this.isFullScreen()) { zoteroPane.setAttribute('savedHeight', zoteroPane.boxObject.height); } // Fix bug whereby resizing the Z pane downward after resizing // the tag selector up and then down sometimes caused the Z pane to // stay at a fixed size and get pushed below the bottom tagSelector.height++; tagSelector.height--; } function getTagSelection(){ var tagSelector = document.getElementById('zotero-tag-selector'); return tagSelector.selection ? tagSelector.selection : {}; } function clearTagSelection() { if (!Zotero.Utilities.isEmpty(this.getTagSelection())) { var tagSelector = document.getElementById('zotero-tag-selector'); tagSelector.clearAll(); } } /* * Sets the tag filter on the items view */ function updateTagFilter(){ this.itemsView.setFilter('tags', getTagSelection()); } /* * Set the tags scope to the items in the current view * * Passed to the items tree to trigger on changes */ function _setTagScope() { var itemGroup = self.collectionsView._getItemAtRow(self.collectionsView.selection.currentIndex); var tagSelector = document.getElementById('zotero-tag-selector'); if (!tagSelector.getAttribute('collapsed') || tagSelector.getAttribute('collapsed') == 'false') { Zotero.debug('Updating tag selector with current tags'); if (itemGroup.editable) { tagSelector.mode = 'edit'; } else { tagSelector.mode = 'view'; } tagSelector.libraryID = itemGroup.ref.libraryID; tagSelector.scope = itemGroup.getChildTags(); } } function onCollectionSelected() { if (this.itemsView) { this.itemsView.unregister(); if (this.itemsView.wrappedJSObject.listener) { document.getElementById('zotero-items-tree').removeEventListener( 'keypress', this.itemsView.wrappedJSObject.listener, false ); } this.itemsView.wrappedJSObject.listener = null; document.getElementById('zotero-items-tree').view = this.itemsView = null; } document.getElementById('zotero-tb-search').value = ""; if (this.collectionsView.selection.count != 1) { document.getElementById('zotero-items-tree').view = this.itemsView = null; return; } // this.collectionsView.selection.currentIndex != -1 var itemgroup = this.collectionsView._getItemAtRow(this.collectionsView.selection.currentIndex); /* if (itemgroup.isSeparator()) { document.getElementById('zotero-items-tree').view = this.itemsView = null; return; } */ itemgroup.setSearch(''); itemgroup.setTags(getTagSelection()); itemgroup.showDuplicates = false; try { Zotero.UnresponsiveScriptIndicator.disable(); this.itemsView = new Zotero.ItemTreeView(itemgroup); this.itemsView.addCallback(_setTagScope); document.getElementById('zotero-items-tree').view = this.itemsView; this.itemsView.selection.clearSelection(); } finally { Zotero.UnresponsiveScriptIndicator.enable(); } if (itemgroup.isLibrary()) { Zotero.Prefs.set('lastViewedFolder', 'L'); } if (itemgroup.isCollection()) { Zotero.Prefs.set('lastViewedFolder', 'C' + itemgroup.ref.id); } else if (itemgroup.isSearch()) { Zotero.Prefs.set('lastViewedFolder', 'S' + itemgroup.ref.id); } else if (itemgroup.isGroup()) { Zotero.Prefs.set('lastViewedFolder', 'G' + itemgroup.ref.id); } } this.showDuplicates = function () { if (this.collectionsView.selection.count == 1 && this.collectionsView.selection.currentIndex != -1) { var itemGroup = this.collectionsView._getItemAtRow(this.collectionsView.selection.currentIndex); itemGroup.showDuplicates = true; try { Zotero.UnresponsiveScriptIndicator.disable(); this.itemsView.refresh(); } finally { Zotero.UnresponsiveScriptIndicator.enable(); } } } this.getItemGroup = function () { return this.collectionsView._getItemAtRow(this.collectionsView.selection.currentIndex); } function itemSelected() { if (!Zotero.stateCheck()) { this.displayErrorMessage(); return; } // Display restore button if items selected in Trash if (this.itemsView && this.itemsView.selection.count) { document.getElementById('zotero-item-restore-button').hidden = !this.itemsView._itemGroup.isTrash() || _nonDeletedItemsSelected(this.itemsView); } else { document.getElementById('zotero-item-restore-button').hidden = true; } var tabs = document.getElementById('zotero-view-tabbox'); // save note when switching from a note if(document.getElementById('zotero-item-pane-content').selectedIndex == 2) { document.getElementById('zotero-note-editor').save(); } // Single item selected if (this.itemsView && this.itemsView.selection.count == 1 && this.itemsView.selection.currentIndex != -1) { var item = this.itemsView._getItemAtRow(this.itemsView.selection.currentIndex); if(item.ref.isNote()) { var noteEditor = document.getElementById('zotero-note-editor'); noteEditor.mode = this.collectionsView.editable ? 'edit' : 'view'; // If loading new or different note, disable undo while we repopulate the text field // so Undo doesn't end up clearing the field. This also ensures that Undo doesn't // undo content from another note into the current one. if (!noteEditor.item || noteEditor.item.id != item.ref.id) { noteEditor.disableUndo(); } noteEditor.parent = null; noteEditor.item = item.ref; noteEditor.enableUndo(); var viewButton = document.getElementById('zotero-view-note-button'); if (this.collectionsView.editable) { viewButton.hidden = false; viewButton.setAttribute('noteID', item.ref.id); if (item.ref.getSource()) { viewButton.setAttribute('sourceID', item.ref.getSource()); } else { viewButton.removeAttribute('sourceID'); } } else { viewButton.hidden = true; } document.getElementById('zotero-item-pane-content').selectedIndex = 2; } else if(item.ref.isAttachment()) { var attachmentBox = document.getElementById('zotero-attachment-box'); attachmentBox.mode = this.collectionsView.editable ? 'edit' : 'view'; attachmentBox.item = item.ref; document.getElementById('zotero-item-pane-content').selectedIndex = 3; } // Regular item else { var isCommons = this.getItemGroup().isBucket(); document.getElementById('zotero-item-pane-content').selectedIndex = 1; var tabBox = document.getElementById('zotero-view-tabbox'); var pane = tabBox.selectedIndex; tabBox.firstChild.hidden = isCommons; var button = document.getElementById('zotero-item-show-original'); if (isCommons) { button.hidden = false; button.disabled = !this.getOriginalItem(); } else { button.hidden = true; } if (this.collectionsView.editable) { ZoteroItemPane.viewItem(item.ref, null, pane); tabs.selectedIndex = document.getElementById('zotero-view-item').selectedIndex; } else { ZoteroItemPane.viewItem(item.ref, 'view', pane); tabs.selectedIndex = document.getElementById('zotero-view-item').selectedIndex; } } } // Zero or multiple items selected else { document.getElementById('zotero-item-pane-content').selectedIndex = 0; var label = document.getElementById('zotero-view-selected-label'); if (this.itemsView && this.itemsView.selection.count) { label.value = Zotero.getString('pane.item.selected.multiple', this.itemsView.selection.count); } else { label.value = Zotero.getString('pane.item.selected.zero'); } } } /** * Check if any selected items in the passed (trash) treeview are not deleted * * @param {nsITreeView} * @return {Boolean} */ function _nonDeletedItemsSelected(itemsView) { var start = {}; var end = {}; for (var i=0, len=itemsView.selection.getRangeCount(); i<len; i++) { itemsView.selection.getRangeAt(i, start, end); for (var j=start.value; j<=end.value; j++) { if (!itemsView._getItemAtRow(j).ref.deleted) { return true; } } } return false; } this.updateNoteButtonMenu = function () { var items = ZoteroPane_Local.getSelectedItems(); var button = document.getElementById('zotero-tb-add-child-note'); button.disabled = !this.canEdit() || !(items.length == 1 && (items[0].isRegularItem() || !items[0].isTopLevelItem())); } this.updateAttachmentButtonMenu = function (popup) { var items = ZoteroPane_Local.getSelectedItems(); var disabled = !this.canEdit() || !(items.length == 1 && items[0].isRegularItem()); if (disabled) { for each(var node in popup.childNodes) { node.disabled = true; } return; } var itemgroup = this.collectionsView._getItemAtRow(this.collectionsView.selection.currentIndex); var canEditFiles = this.canEditFiles(); var prefix = "menuitem-iconic zotero-menuitem-attachments-"; for (var i=0; i<popup.childNodes.length; i++) { var node = popup.childNodes[i]; switch (node.className) { case prefix + 'link': node.disabled = itemgroup.isWithinGroup(); break; case prefix + 'snapshot': case prefix + 'file': node.disabled = !canEditFiles; break; case prefix + 'web-link': node.disabled = false; break; default: throw ("Invalid class name '" + node.className + "' in ZoteroPane_Local.updateAttachmentButtonMenu()"); } } } this.checkPDFConverter = function () { if (Zotero.Fulltext.pdfConverterIsRegistered()) { return true; } var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); var buttonFlags = (ps.BUTTON_POS_0) * (ps.BUTTON_TITLE_IS_STRING) + (ps.BUTTON_POS_1) * (ps.BUTTON_TITLE_CANCEL); var index = ps.confirmEx( null, // TODO: localize "PDF Tools Not Installed", "To use this feature, you must first install the PDF tools in " + "the Zotero preferences.", buttonFlags, "Open Preferences", null, null, null, {} ); if (index == 0) { ZoteroPane_Local.openPreferences('zotero-prefpane-search', 'pdftools-install'); } return false; } function reindexItem() { var items = this.getSelectedItems(); if (!items) { return; } var itemIDs = []; var checkPDF = false; for (var i=0; i<items.length; i++) { // If any PDFs, we need to make sure the converter is installed and // prompt for installation if not if (!checkPDF && items[i].attachmentMIMEType && items[i].attachmentMIMEType == "application/pdf") { checkPDF = true; } itemIDs.push(items[i].id); } if (checkPDF) { var installed = this.checkPDFConverter(); if (!installed) { document.getElementById('zotero-attachment-box').updateItemIndexedState(); return; } } Zotero.Fulltext.indexItems(itemIDs, true); document.getElementById('zotero-attachment-box').updateItemIndexedState(); } function duplicateSelectedItem() { if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } var item = this.getSelectedItems()[0]; Zotero.DB.beginTransaction(); // Create new unsaved clone item in target library var newItem = new Zotero.Item(item.itemTypeID); newItem.libraryID = item.libraryID; // DEBUG: save here because clone() doesn't currently work on unsaved tagged items var id = newItem.save(); var newItem = Zotero.Items.get(id); item.clone(false, newItem); newItem.save(); if (this.itemsView._itemGroup.isCollection() && !newItem.getSource()) { this.itemsView._itemGroup.ref.addItem(newItem.id); } Zotero.DB.commitTransaction(); this.selectItem(newItem.id); } this.deleteSelectedItem = function () { Zotero.debug("ZoteroPane_Local.deleteSelectedItem() is deprecated -- use ZoteroPane_Local.deleteSelectedItems()"); this.deleteSelectedItems(); } /* * Remove, trash, or delete item(s), depending on context * * @param {Boolean} [force=false] Trash or delete even if in a collection or search, * or trash without prompt in library */ this.deleteSelectedItems = function (force) { if (!this.itemsView || !this.itemsView.selection.count) { return; } var itemGroup = this.itemsView._itemGroup; if (!itemGroup.isTrash() && !itemGroup.isBucket() && !this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } var toTrash = { title: Zotero.getString('pane.items.trash.title'), text: Zotero.getString( 'pane.items.trash' + (this.itemsView.selection.count > 1 ? '.multiple' : '') ) }; var toDelete = { title: Zotero.getString('pane.items.delete.title'), text: Zotero.getString( 'pane.items.delete' + (this.itemsView.selection.count > 1 ? '.multiple' : '') ) }; if (itemGroup.isLibrary()) { // In library, don't prompt if meta key was pressed var prompt = force ? false : toTrash; } else if (itemGroup.isCollection()) { // In collection, only prompt if trashing var prompt = force ? (itemGroup.isWithinGroup() ? toDelete : toTrash) : false; } // This should be changed if/when groups get trash else if (itemGroup.isGroup()) { var prompt = toDelete; } else if (itemGroup.isSearch()) { if (!force) { return; } var prompt = toTrash; } // Do nothing in share views else if (itemGroup.isShare()) { return; } else if (itemGroup.isBucket()) { var prompt = toDelete; } // Do nothing in trash view if any non-deleted items are selected else if (itemGroup.isTrash()) { var start = {}; var end = {}; for (var i=0, len=this.itemsView.selection.getRangeCount(); i<len; i++) { this.itemsView.selection.getRangeAt(i, start, end); for (var j=start.value; j<=end.value; j++) { if (!this.itemsView._getItemAtRow(j).ref.deleted) { return; } } } var prompt = toDelete; } var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); if (!prompt || promptService.confirm(window, prompt.title, prompt.text)) { this.itemsView.deleteSelection(force); } } this.deleteSelectedCollection = function () { // Remove virtual Unfiled search var row = this.collectionsView._getItemAtRow(this.collectionsView.selection.currentIndex); if (row.isSearch() && (row.ref.id + "").match(/^8634533000/)) { // 'UNFILED000' this.setUnfiled(row.ref.libraryID, false); return; } if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } if (this.collectionsView.selection.count == 1) { if (row.isCollection()) { if (confirm(Zotero.getString('pane.collections.delete'))) { this.collectionsView.deleteSelection(); } } else if (row.isSearch()) { if (confirm(Zotero.getString('pane.collections.deleteSearch'))) { this.collectionsView.deleteSelection(); } } } } // Currently used only for Commons to find original linked item this.getOriginalItem = function () { var item = this.getSelectedItems()[0]; var itemGroup = this.getItemGroup(); // TEMP: Commons buckets only return itemGroup.ref.getLocalItem(item); } this.showOriginalItem = function () { var item = this.getOriginalItem(); if (!item) { Zotero.debug("Original item not found"); return; } this.selectItem(item.id); } this.restoreSelectedItems = function () { var items = this.getSelectedItems(); if (!items) { return; } Zotero.DB.beginTransaction(); for (var i=0; i<items.length; i++) { items[i].deleted = false; items[i].save(); } Zotero.DB.commitTransaction(); } this.emptyTrash = function () { var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); var result = ps.confirm( null, "", Zotero.getString('pane.collections.emptyTrash') + "\n\n" + Zotero.getString('general.actionCannotBeUndone') ); if (result) { Zotero.Items.emptyTrash(); Zotero.purgeDataObjects(true); } } this.createCommonsBucket = function () { var self = this; Zotero.Commons.getBuckets(function () { var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); var invalid = false; while (true) { if (invalid) { // TODO: localize ps.alert(null, "", "Invalid title. Please try again."); invalid = false; } var newTitle = {}; var result = prompt.prompt( null, "", // TODO: localize "Enter a title for this Zotero Commons collection:", newTitle, "", {} ); if (!result) { return; } var title = Zotero.Utilities.trim(newTitle.value); if (!title) { return; } if (!Zotero.Commons.isValidBucketTitle(title)) { invalid = true; continue; } break; } invalid = false; var origName = title.toLowerCase(); origName = origName.replace(/[^a-z0-9 ._-]/g, ''); origName = origName.replace(/ /g, '-'); origName = origName.substr(0, 32); while (true) { if (invalid) { // TODO: localize var msg = "'" + testName + "' is not a valid Zotero Commons collection identifier.\n\n" + "Collection identifiers can contain basic Latin letters, numbers, " + "hyphens, and underscores and must be no longer than 32 characters. " + "Spaces and other characters are not allowed."; ps.alert(null, "", msg); invalid = false; } var newName = { value: origName }; var result = ps.prompt( null, "", // TODO: localize "Enter an identifier for the collection '" + title + "'.\n\n" + "The identifier will form the collection's URL on archive.org. " + "Identifiers can contain basic Latin letters, numbers, hyphens, and underscores " + "and must be no longer than 32 characters. " + "Spaces and other characters are not allowed.\n\n" + '"' + Zotero.Commons.userNameSlug + '-" ' + "will be automatically prepended to your entry.", newName, "", {} ); if (!result) { return; } var name = Zotero.Utilities.trim(newName.value); if (!name) { return; } var testName = Zotero.Commons.userNameSlug + '-' + name; if (!Zotero.Commons.isValidBucketName(testName)) { invalid = true; continue; } break; } // TODO: localize var progressWin = new Zotero.ProgressWindow(); progressWin.changeHeadline("Creating Zotero Commons Collection"); var icon = self.collectionsView.getImageSrc(self.collectionsView.selection.currentIndex); progressWin.addLines(title, icon) progressWin.show(); Zotero.Commons.createBucket(name, title, function () { progressWin.startCloseTimer(); }); }); } this.refreshCommonsBucket = function() { if (!this.collectionsView || !this.collectionsView.selection || this.collectionsView.selection.count != 1 || this.collectionsView.selection.currentIndex == -1) { return false; } var itemGroup = this.collectionsView._getItemAtRow(this.collectionsView.selection.currentIndex); if (itemGroup && itemGroup.isBucket()) { var self = this; itemGroup.ref.refreshItems(function () { self.itemsView.refresh(); self.itemsView.sort(); // On a manual refresh, also check for new OCRed files //Zotero.Commons.syncFiles(); }); } } function editSelectedCollection() { if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } if (this.collectionsView.selection.count > 0) { var row = this.collectionsView._getItemAtRow(this.collectionsView.selection.currentIndex); if (row.isCollection()) { var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); var newName = { value: row.getName() }; var result = promptService.prompt(window, "", Zotero.getString('pane.collections.rename'), newName, "", {}); if (result && newName.value) { row.ref.name = newName.value; row.ref.save(); } } else { var s = new Zotero.Search(); s.id = row.ref.id; var io = {dataIn: {search: s, name: row.getName()}, dataOut: null}; window.openDialog('chrome://zotero/content/searchDialog.xul','','chrome,modal',io); if (io.dataOut) { this.onCollectionSelected(); //reload itemsView } } } } function copySelectedItemsToClipboard(asCitations) { var items = this.getSelectedItems(); if (!items.length) { return; } // Make sure at least one item is a regular item // // DEBUG: We could copy notes via keyboard shortcut if we altered // Z_F_I.copyItemsToClipboard() to use Z.QuickCopy.getContentFromItems(), // but 1) we'd need to override that function's drag limit and 2) when I // tried it the OS X clipboard seemed to be getting text vs. HTML wrong, // automatically converting text/html to plaintext rather than using // text/unicode. (That may be fixable, however.) var canCopy = false; for each(var item in items) { if (item.isRegularItem()) { canCopy = true; break; } } if (!canCopy) { var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); ps.alert(null, "", Zotero.getString("fileInterface.noReferencesError")); return; } var url = (window.content && window.content.location ? window.content.location.href : null); var [mode, format] = Zotero.QuickCopy.getFormatFromURL(url).split('='); var [mode, contentType] = mode.split('/'); if (mode == 'bibliography') { if (asCitations) { Zotero_File_Interface.copyCitationToClipboard(items, format, contentType == 'html'); } else { Zotero_File_Interface.copyItemsToClipboard(items, format, contentType == 'html'); } } else if (mode == 'export') { // Copy citations doesn't work in export mode if (asCitations) { return; } else { Zotero_File_Interface.exportItemsToClipboard(items, format); } } } function clearQuicksearch() { var search = document.getElementById('zotero-tb-search'); if (search.value != '') { search.value = ''; ZoteroPane_Local.search(); } } function handleSearchKeypress(textbox, event) { // Events that turn find-as-you-type on if (event.keyCode == event.DOM_VK_ESCAPE) { textbox.value = ''; ZoteroPane_Local.setItemsPaneMessage(Zotero.getString('searchInProgress')); setTimeout(function () { ZoteroPane_Local.search(); ZoteroPane_Local.clearItemsPaneMessage(); }, 1); } else if (event.keyCode == event.DOM_VK_RETURN || event.keyCode == event.DOM_VK_ENTER) { ZoteroPane_Local.setItemsPaneMessage(Zotero.getString('searchInProgress')); setTimeout(function () { ZoteroPane_Local.search(true); ZoteroPane_Local.clearItemsPaneMessage(); }, 1); } } function handleSearchInput(textbox, event) { // This is the new length, except, it seems, when the change is a // result of Undo or Redo if (!textbox.value.length) { ZoteroPane_Local.setItemsPaneMessage(Zotero.getString('searchInProgress')); setTimeout(function () { ZoteroPane_Local.search(); ZoteroPane_Local.clearItemsPaneMessage(); }, 1); } else if (textbox.value.indexOf('"') != -1) { ZoteroPane_Local.setItemsPaneMessage(Zotero.getString('advancedSearchMode')); } } function search(runAdvanced) { if (this.itemsView) { var search = document.getElementById('zotero-tb-search'); if (!runAdvanced && search.value.indexOf('"') != -1) { return; } var searchVal = search.value; this.itemsView.setFilter('search', searchVal); } } /* * Select item in current collection or, if not there, in Library * * If _inLibrary_, force switch to Library * If _expand_, open item if it's a container */ function selectItem(itemID, inLibrary, expand) { if (!itemID) { return false; } var item = Zotero.Items.get(itemID); if (!item) { return false; } if (!this.itemsView) { Components.utils.reportError("Items view not set in ZoteroPane_Local.selectItem()"); return false; } var currentLibraryID = this.getSelectedLibraryID(); // If in a different library if (item.libraryID != currentLibraryID) { Zotero.debug("Library ID differs; switching library"); this.collectionsView.selectLibrary(item.libraryID); } // Force switch to library view else if (!this.itemsView._itemGroup.isLibrary() && inLibrary) { Zotero.debug("Told to select in library; switching to library"); this.collectionsView.selectLibrary(item.libraryID); } var selected = this.itemsView.selectItem(itemID, expand); if (!selected) { Zotero.debug("Item was not selected; switching to library"); this.collectionsView.selectLibrary(item.libraryID); this.itemsView.selectItem(itemID, expand); } return true; } this.getSelectedLibraryID = function () { var group = this.getSelectedGroup(); if (group) { return group.libraryID; } var collection = this.getSelectedCollection(); if (collection) { return collection.libraryID; } return null; } function getSelectedCollection(asID) { if (this.collectionsView) { return this.collectionsView.getSelectedCollection(asID); } return false; } function getSelectedSavedSearch(asID) { if (this.collectionsView.selection.count > 0 && this.collectionsView.selection.currentIndex != -1) { var collection = this.collectionsView._getItemAtRow(this.collectionsView.selection.currentIndex); if (collection && collection.isSearch()) { return asID ? collection.ref.id : collection.ref; } } return false; } /* * Return an array of Item objects for selected items * * If asIDs is true, return an array of itemIDs instead */ function getSelectedItems(asIDs) { if (!this.itemsView) { return []; } return this.itemsView.getSelectedItems(asIDs); } this.getSelectedGroup = function (asID) { if (this.collectionsView.selection && this.collectionsView.selection.count > 0 && this.collectionsView.selection.currentIndex != -1) { var itemGroup = this.collectionsView._getItemAtRow(this.collectionsView.selection.currentIndex); if (itemGroup && itemGroup.isGroup()) { return asID ? itemGroup.ref.id : itemGroup.ref; } } return false; } /* * Returns an array of Zotero.Item objects of visible items in current sort order * * If asIDs is true, return an array of itemIDs instead */ function getSortedItems(asIDs) { if (!this.itemsView) { return []; } return this.itemsView.getSortedItems(asIDs); } function getSortField() { if (!this.itemsView) { return false; } return this.itemsView.getSortField(); } function getSortDirection() { if (!this.itemsView) { return false; } return this.itemsView.getSortDirection(); } this.buildCollectionContextMenu = function buildCollectionContextMenu() { var menu = document.getElementById('zotero-collectionmenu'); var m = { newCollection: 0, newSavedSearch: 1, newSubcollection: 2, sep1: 3, showUnfiled: 4, editSelectedCollection: 5, removeCollection: 6, sep2: 7, exportCollection: 8, createBibCollection: 9, exportFile: 10, loadReport: 11, emptyTrash: 12, createCommonsBucket: 13, refreshCommonsBucket: 14 }; var itemGroup = this.collectionsView._getItemAtRow(this.collectionsView.selection.currentIndex); var enable = [], disable = [], show = []; // Collection if (itemGroup.isCollection()) { show = [ m.newSubcollection, m.sep1, m.editSelectedCollection, m.removeCollection, m.sep2, m.exportCollection, m.createBibCollection, m.loadReport ]; var s = [m.exportCollection, m.createBibCollection, m.loadReport]; if (this.itemsView.rowCount>0) { enable = s; } else if (!this.collectionsView.isContainerEmpty(this.collectionsView.selection.currentIndex)) { enable = [m.exportCollection]; disable = [m.createBibCollection, m.loadReport]; } else { disable = s; } // Adjust labels menu.childNodes[m.editSelectedCollection].setAttribute('label', Zotero.getString('pane.collections.menu.rename.collection')); menu.childNodes[m.removeCollection].setAttribute('label', Zotero.getString('pane.collections.menu.remove.collection')); menu.childNodes[m.exportCollection].setAttribute('label', Zotero.getString('pane.collections.menu.export.collection')); menu.childNodes[m.createBibCollection].setAttribute('label', Zotero.getString('pane.collections.menu.createBib.collection')); menu.childNodes[m.loadReport].setAttribute('label', Zotero.getString('pane.collections.menu.generateReport.collection')); } // Saved Search else if (itemGroup.isSearch()) { // Unfiled items view if ((itemGroup.ref.id + "").match(/^8634533000/)) { // 'UNFILED000' show = [ m.removeCollection ]; menu.childNodes[m.removeCollection].setAttribute('label', Zotero.getString('general.remove')); } // Normal search view else { show = [ m.editSelectedCollection, m.removeCollection, m.sep2, m.exportCollection, m.createBibCollection, m.loadReport ]; menu.childNodes[m.removeCollection].setAttribute('label', Zotero.getString('pane.collections.menu.remove.savedSearch')); } var s = [m.exportCollection, m.createBibCollection, m.loadReport]; if (this.itemsView.rowCount>0) { enable = s; } else { disable = s; } // Adjust labels menu.childNodes[m.editSelectedCollection].setAttribute('label', Zotero.getString('pane.collections.menu.edit.savedSearch')); menu.childNodes[m.exportCollection].setAttribute('label', Zotero.getString('pane.collections.menu.export.savedSearch')); menu.childNodes[m.createBibCollection].setAttribute('label', Zotero.getString('pane.collections.menu.createBib.savedSearch')); menu.childNodes[m.loadReport].setAttribute('label', Zotero.getString('pane.collections.menu.generateReport.savedSearch')); } // Trash else if (itemGroup.isTrash()) { show = [m.emptyTrash]; } else if (itemGroup.isHeader()) { if (itemGroup.ref.id == 'commons-header') { show = [m.createCommonsBucket]; } } else if (itemGroup.isBucket()) { show = [m.refreshCommonsBucket]; } // Group else if (itemGroup.isGroup()) { show = [m.newCollection, m.newSavedSearch, m.sep1, m.showUnfiled]; } // Library else { show = [m.newCollection, m.newSavedSearch, m.sep1, m.showUnfiled, m.sep2, m.exportFile]; } // Disable some actions if user doesn't have write access var s = [m.editSelectedCollection, m.removeCollection, m.newCollection, m.newSavedSearch, m.newSubcollection]; if (itemGroup.isWithinGroup() && !itemGroup.editable) { disable = disable.concat(s); } else { enable = enable.concat(s); } for (var i in disable) { menu.childNodes[disable[i]].setAttribute('disabled', true); } for (var i in enable) { menu.childNodes[enable[i]].setAttribute('disabled', false); } // Hide all items by default for each(var pos in m) { menu.childNodes[pos].setAttribute('hidden', true); } for (var i in show) { menu.childNodes[show[i]].setAttribute('hidden', false); } } function buildItemContextMenu() { var m = { showInLibrary: 0, sep1: 1, addNote: 2, addAttachments: 3, sep2: 4, duplicateItem: 5, deleteItem: 6, deleteFromLibrary: 7, sep3: 8, exportItems: 9, createBib: 10, loadReport: 11, sep4: 12, createParent: 13, recognizePDF: 14, renameAttachments: 15, reindexItem: 16 }; var menu = document.getElementById('zotero-itemmenu'); // remove old locate menu items while(menu.firstChild && menu.firstChild.getAttribute("zotero-locate")) { menu.removeChild(menu.firstChild); } var enable = [], disable = [], show = [], hide = [], multiple = ''; if (!this.itemsView) { return; } if (this.itemsView.selection.count > 0) { var itemGroup = this.itemsView._itemGroup; enable.push(m.showInLibrary, m.addNote, m.addAttachments, m.sep2, m.duplicateItem, m.deleteItem, m.deleteFromLibrary, m.exportItems, m.createBib, m.loadReport); // Multiple items selected if (this.itemsView.selection.count > 1) { var multiple = '.multiple'; hide.push(m.showInLibrary, m.sep1, m.addNote, m.addAttachments, m.sep2, m.duplicateItem); // If all items can be reindexed, or all items can be recognized, show option var items = this.getSelectedItems(); var canIndex = true; var canRecognize = true; if (!Zotero.Fulltext.pdfConverterIsRegistered()) { canIndex = false; } for (var i=0; i<items.length; i++) { if (canIndex && !Zotero.Fulltext.canReindex(items[i].id)) { canIndex = false; } if (canRecognize && !Zotero_RecognizePDF.canRecognize(items[i])) { canRecognize = false; } if (!canIndex && !canRecognize) { break; } } if (canIndex) { show.push(m.reindexItem); } else { hide.push(m.reindexItem); } if (canRecognize) { show.push(m.recognizePDF); hide.push(m.createParent); } else { hide.push(m.recognizePDF); var canCreateParent = true; for (var i=0; i<items.length; i++) { if (!items[i].isTopLevelItem() || items[i].isRegularItem() || Zotero_RecognizePDF.canRecognize(items[i])) { canCreateParent = false; break; } } if (canCreateParent) { show.push(m.createParent); } else { hide.push(m.createParent); } } // If all items are child attachments, show rename option var canRename = true; for (var i=0; i<items.length; i++) { var item = items[i]; // Same check as in rename function if (!item.isAttachment() || !item.getSource() || item.attachmentLinkMode == Zotero.Attachments.LINK_MODE_LINKED_URL) { canRename = false; break; } } if (canRename) { show.push(m.renameAttachments); } else { hide.push(m.renameAttachments); } // Add in attachment separator if (canCreateParent || canRecognize || canRename || canIndex) { show.push(m.sep4); } else { hide.push(m.sep4); } // Block certain actions on files if no access and at least one item // is an imported attachment if (!itemGroup.filesEditable) { var hasImportedAttachment = false; for (var i=0; i<items.length; i++) { var item = items[i]; if (item.isImportedAttachment()) { hasImportedAttachment = true; break; } } if (hasImportedAttachment) { var d = [m.deleteFromLibrary, m.createParent, m.renameAttachments]; for each(var val in d) { disable.push(val); var index = enable.indexOf(val); if (index != -1) { enable.splice(index, 1); } } } } } // Single item selected else { var item = this.itemsView._getItemAtRow(this.itemsView.selection.currentIndex).ref; var itemID = item.id; menu.setAttribute('itemID', itemID); // Show in Library if (!itemGroup.isLibrary() && !itemGroup.isWithinGroup()) { show.push(m.showInLibrary, m.sep1); } else { hide.push(m.showInLibrary, m.sep1); } if (item.isRegularItem()) { show.push(m.addNote, m.addAttachments, m.sep2); } else { hide.push(m.addNote, m.addAttachments, m.sep2); } if (item.isAttachment()) { var showSep4 = false; hide.push(m.duplicateItem); if (Zotero_RecognizePDF.canRecognize(item)) { show.push(m.recognizePDF); hide.push(m.createParent); showSep4 = true; } else { hide.push(m.recognizePDF); // If not a PDF, allow parent item creation if (item.isTopLevelItem()) { show.push(m.createParent); showSep4 = true; } else { hide.push(m.createParent); } } // Attachment rename option if (item.getSource() && item.attachmentLinkMode != Zotero.Attachments.LINK_MODE_LINKED_URL) { show.push(m.renameAttachments); showSep4 = true; } else { hide.push(m.renameAttachments); } if (showSep4) { show.push(m.sep4); } else { hide.push(m.sep4); } // If not linked URL, show reindex line if (Zotero.Fulltext.pdfConverterIsRegistered() && Zotero.Fulltext.canReindex(item.id)) { show.push(m.reindexItem); showSep4 = true; } else { hide.push(m.reindexItem); } } else { if (item.isNote() && item.isTopLevelItem()) { show.push(m.sep4, m.createParent); } else { hide.push(m.sep4, m.createParent); } show.push(m.duplicateItem); hide.push(m.recognizePDF, m.renameAttachments, m.reindexItem); } // Update attachment submenu var popup = document.getElementById('zotero-add-attachment-popup') this.updateAttachmentButtonMenu(popup); // Block certain actions on files if no access if (item.isImportedAttachment() && !itemGroup.filesEditable) { var d = [m.deleteFromLibrary, m.createParent, m.renameAttachments]; for each(var val in d) { disable.push(val); var index = enable.indexOf(val); if (index != -1) { enable.splice(index, 1); } } } } } // No items selected else { // Show in Library if (!itemGroup.isLibrary()) { show.push(m.showInLibrary, m.sep1); } else { hide.push(m.showInLibrary, m.sep1); } disable.push(m.showInLibrary, m.duplicateItem, m.deleteItem, m.deleteFromLibrary, m.exportItems, m.createBib, m.loadReport); hide.push(m.addNote, m.addAttachments, m.sep2, m.sep4, m.reindexItem, m.createParent, m.recognizePDF, m.renameAttachments); } // TODO: implement menu for remote items if (!itemGroup.editable) { for (var i in m) { // Still show export/bib/report for non-editable views // (other than Commons buckets, which aren't real items) if (!itemGroup.isBucket()) { switch (i) { case 'exportItems': case 'createBib': case 'loadReport': continue; } } disable.push(m[i]); var index = enable.indexOf(m[i]); if (index != -1) { enable.splice(index, 1); } } } // Remove from collection if (this.itemsView._itemGroup.isCollection() && !(item && item.getSource())) { menu.childNodes[m.deleteItem].setAttribute('label', Zotero.getString('pane.items.menu.remove' + multiple)); show.push(m.deleteItem); } else { hide.push(m.deleteItem); } // Plural if necessary menu.childNodes[m.deleteFromLibrary].setAttribute('label', Zotero.getString('pane.items.menu.erase' + multiple)); menu.childNodes[m.exportItems].setAttribute('label', Zotero.getString('pane.items.menu.export' + multiple)); menu.childNodes[m.createBib].setAttribute('label', Zotero.getString('pane.items.menu.createBib' + multiple)); menu.childNodes[m.loadReport].setAttribute('label', Zotero.getString('pane.items.menu.generateReport' + multiple)); menu.childNodes[m.createParent].setAttribute('label', Zotero.getString('pane.items.menu.createParent' + multiple)); menu.childNodes[m.recognizePDF].setAttribute('label', Zotero.getString('pane.items.menu.recognizePDF' + multiple)); menu.childNodes[m.renameAttachments].setAttribute('label', Zotero.getString('pane.items.menu.renameAttachments' + multiple)); menu.childNodes[m.reindexItem].setAttribute('label', Zotero.getString('pane.items.menu.reindexItem' + multiple)); for (var i in disable) { menu.childNodes[disable[i]].setAttribute('disabled', true); } for (var i in enable) { menu.childNodes[enable[i]].setAttribute('disabled', false); } for (var i in hide) { menu.childNodes[hide[i]].setAttribute('hidden', true); } for (var i in show) { menu.childNodes[show[i]].setAttribute('hidden', false); } // add locate menu options Zotero_LocateMenu.buildContextMenu(menu); } // Adapted from: http://www.xulplanet.com/references/elemref/ref_tree.html#cmnote-9 this.onTreeClick = function (event) { // We only care about primary button double and triple clicks if (!event || (event.detail != 2 && event.detail != 3) || event.button != 0) { return; } var t = event.originalTarget; if (t.localName != 'treechildren') { return; } var tree = t.parentNode; var row = {}, col = {}, obj = {}; tree.treeBoxObject.getCellAt(event.clientX, event.clientY, row, col, obj); // obj.value == 'cell'/'text'/'image' if (!obj.value) { return; } if (tree.id == 'zotero-collections-tree') { // Ignore triple clicks for collections if (event.detail != 2) { return; } var itemGroup = ZoteroPane_Local.collectionsView._getItemAtRow(tree.view.selection.currentIndex); if (itemGroup.isLibrary()) { var uri = Zotero.URI.getCurrentUserLibraryURI(); if (uri) { ZoteroPane_Local.loadURI(uri); event.stopPropagation(); } return; } if (itemGroup.isSearch()) { // Don't do anything on double-click of Unfiled Items if ((itemGroup.ref.id + "").match(/^8634533000/)) { // 'UNFILED000' return; } ZoteroPane_Local.editSelectedCollection(); return; } if (itemGroup.isGroup()) { var uri = Zotero.URI.getGroupURI(itemGroup.ref, true); ZoteroPane_Local.loadURI(uri); event.stopPropagation(); return; } if (itemGroup.isHeader()) { if (itemGroup.ref.id == 'group-libraries-header') { var uri = Zotero.URI.getGroupsURL(); ZoteroPane_Local.loadURI(uri); event.stopPropagation(); } return; } if (itemGroup.isBucket()) { ZoteroPane_Local.loadURI(itemGroup.ref.uri); event.stopPropagation(); } } else if (tree.id == 'zotero-items-tree') { var viewOnDoubleClick = Zotero.Prefs.get('viewOnDoubleClick'); // Expand/collapse on triple-click if (viewOnDoubleClick) { if (event.detail == 3) { tree.view.toggleOpenState(tree.view.selection.currentIndex); return; } // Don't expand/collapse on double-click event.stopPropagation(); } if (tree.view && tree.view.selection.currentIndex > -1) { var item = ZoteroPane_Local.getSelectedItems()[0]; if (item) { if (item.isRegularItem()) { // Double-click on Commons item should load IA page var itemGroup = ZoteroPane_Local.collectionsView._getItemAtRow( ZoteroPane_Local.collectionsView.selection.currentIndex ); if (itemGroup.isBucket()) { var uri = itemGroup.ref.getItemURI(item); ZoteroPane_Local.loadURI(uri); event.stopPropagation(); return; } if (!viewOnDoubleClick) { return; } var uri = Components.classes["@mozilla.org/network/standard-url;1"]. createInstance(Components.interfaces.nsIURI); var snapID = item.getBestAttachment(); if (snapID) { spec = Zotero.Items.get(snapID).getLocalFileURL(); if (spec) { uri.spec = spec; if (uri.scheme && uri.scheme == 'file') { ZoteroPane_Local.viewAttachment(snapID, event); return; } } } var uri = item.getField('url'); if (!uri) { var doi = item.getField('DOI'); if (doi) { // Pull out DOI, in case there's a prefix doi = Zotero.Utilities.cleanDOI(doi); if (doi) { uri = "http://dx.doi.org/" + encodeURIComponent(doi); } } } if (uri) { ZoteroPane_Local.loadURI(uri); } } else if (item.isNote()) { if (!ZoteroPane_Local.collectionsView.editable) { return; } document.getElementById('zotero-view-note-button').doCommand(); } else if (item.isAttachment()) { ZoteroPane_Local.viewSelectedAttachment(event); } } } } } this.openPreferences = function (paneID, action) { var io = { pane: paneID, action: action }; window.openDialog('chrome://zotero/content/preferences/preferences.xul', 'zotero-prefs', 'chrome,titlebar,toolbar,centerscreen,' + Zotero.Prefs.get('browser.preferences.instantApply', true) ? 'dialog=no' : 'modal', io ); } /* * Loads a URL following the standard modifier key behavior * (e.g. meta-click == new background tab, meta-shift-click == new front tab, * shift-click == new window, no modifier == frontmost tab */ function loadURI(uris, event, data) { if(typeof uris === "string") { uris = [uris]; } for each(var uri in uris) { // Ignore javascript: and data: URIs if (uri.match(/^(javascript|data):/)) { return; } if (Zotero.isStandalone && uri.match(/^https?/)) { var io = Components.classes['@mozilla.org/network/io-service;1'] .getService(Components.interfaces.nsIIOService); var uri = io.newURI(uri, null, null); var handler = Components.classes['@mozilla.org/uriloader/external-protocol-service;1'] .getService(Components.interfaces.nsIExternalProtocolService) .getProtocolHandlerInfo('http'); handler.preferredAction = Components.interfaces.nsIHandlerInfo.useSystemDefault; handler.launchWithURI(uri, null); return; } // Open in new tab var openInNewTab = event && (event.metaKey || (!Zotero.isMac && event.ctrlKey)); if (event && event.shiftKey && !openInNewTab) { window.open(uri, "zotero-loaded-page", "menubar=yes,location=yes,toolbar=yes,personalbar=yes,resizable=yes,scrollbars=yes,status=yes"); } else if (openInNewTab || !window.loadURI || uris.length > 1) { // if no gBrowser, find it if(!gBrowser) { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var browserWindow = wm.getMostRecentWindow("navigator:browser"); var gBrowser = browserWindow.gBrowser; } // load in a new tab var tab = gBrowser.addTab(uri); var browser = gBrowser.getBrowserForTab(tab); if (event && event.shiftKey || !openInNewTab) { // if shift key is down, or we are opening in a new tab because there is no loadURI, // select new tab gBrowser.selectedTab = tab; } } else { window.loadURI(uri); } } } function setItemsPaneMessage(msg, lock) { var elem = document.getElementById('zotero-items-pane-message-box'); if (elem.getAttribute('locked') == 'true') { return; } while (elem.hasChildNodes()) { elem.removeChild(elem.firstChild); } var msgParts = msg.split("\n\n"); for (var i=0; i<msgParts.length; i++) { var desc = document.createElement('description'); desc.appendChild(document.createTextNode(msgParts[i])); elem.appendChild(desc); } // Make message permanent if (lock) { elem.setAttribute('locked', true); } document.getElementById('zotero-items-pane-content').selectedIndex = 1; } function clearItemsPaneMessage() { // If message box is locked, don't clear var box = document.getElementById('zotero-items-pane-message-box'); if (box.getAttribute('locked') == 'true') { return; } document.getElementById('zotero-items-pane-content').selectedIndex = 0; } // Updates browser context menu options function contextPopupShowing() { if (!Zotero.Prefs.get('browserContentContextMenu')) { return; } var menuitem = document.getElementById("zotero-context-add-to-current-note"); var showing = false; if (menuitem){ var items = ZoteroPane_Local.getSelectedItems(); if (ZoteroPane_Local.itemsView.selection && ZoteroPane_Local.itemsView.selection.count==1 && items[0] && items[0].isNote() && window.gContextMenu.isTextSelected) { menuitem.hidden = false; showing = true; } else { menuitem.hidden = true; } } var menuitem = document.getElementById("zotero-context-add-to-new-note"); if (menuitem){ if (window.gContextMenu.isTextSelected) { menuitem.hidden = false; showing = true; } else { menuitem.hidden = true; } } var menuitem = document.getElementById("zotero-context-save-link-as-item"); if (menuitem) { if (window.gContextMenu.onLink) { menuitem.hidden = false; showing = true; } else { menuitem.hidden = true; } } var menuitem = document.getElementById("zotero-context-save-image-as-item"); if (menuitem) { // Not using window.gContextMenu.hasBGImage -- if the user wants it, // they can use the Firefox option to view and then import from there if (window.gContextMenu.onImage) { menuitem.hidden = false; showing = true; } else { menuitem.hidden = true; } } // If Zotero is locked or library is read-only, disable menu items var menu = document.getElementById('zotero-content-area-context-menu'); menu.hidden = !showing; var disabled = Zotero.locked; if (!disabled && self.collectionsView.selection && self.collectionsView.selection.count) { var itemGroup = self.collectionsView._getItemAtRow(self.collectionsView.selection.currentIndex); disabled = !itemGroup.editable; } for each(var menuitem in menu.firstChild.childNodes) { menuitem.disabled = disabled; } } this.newNote = function (popup, parent, text, citeURI) { if (!Zotero.stateCheck()) { this.displayErrorMessage(true); return; } if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } if (!popup) { if (!text) { text = ''; } text = Zotero.Utilities.trim(text); if (text) { text = '<blockquote' + (citeURI ? ' cite="' + citeURI + '"' : '') + '>' + Zotero.Utilities.text2html(text) + "</blockquote>"; } var item = new Zotero.Item('note'); item.libraryID = this.getSelectedLibraryID(); item.setNote(text); if (parent) { item.setSource(parent); } var itemID = item.save(); if (!parent && this.itemsView && this.itemsView._itemGroup.isCollection()) { this.itemsView._itemGroup.ref.addItem(itemID); } this.selectItem(itemID); document.getElementById('zotero-note-editor').focus(); } else { // TODO: _text_ var c = this.getSelectedCollection(); if (c) { this.openNoteWindow(null, c.id, parent); } else { this.openNoteWindow(null, null, parent); } } } function addTextToNote(text, citeURI) { if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } if (!text) { return false; } text = Zotero.Utilities.trim(text); if (!text.length) { return false; } text = '<blockquote' + (citeURI ? ' cite="' + citeURI + '"' : '') + '>' + Zotero.Utilities.text2html(text) + "</blockquote>"; var items = this.getSelectedItems(); if (this.itemsView.selection.count == 1 && items[0] && items[0].isNote()) { var note = items[0].getNote() items[0].setNote(note + text); items[0].save(); var noteElem = document.getElementById('zotero-note-editor') noteElem.focus(); return true; } return false; } function openNoteWindow(itemID, col, parentItemID) { if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } var name = null; if (itemID) { // Create a name for this window so we can focus it later // // Collection is only used on new notes, so we don't need to // include it in the name name = 'zotero-note-' + itemID; var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var e = wm.getEnumerator(''); while (e.hasMoreElements()) { var w = e.getNext(); if (w.name == name) { w.focus(); return; } } } window.open('chrome://zotero/content/note.xul?v=1' + (itemID ? '&id=' + itemID : '') + (col ? '&coll=' + col : '') + (parentItemID ? '&p=' + parentItemID : ''), name, 'chrome,resizable,centerscreen'); } this.addAttachmentFromURI = function (link, itemID) { if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); var input = {}; var check = {value : false}; // TODO: Localize // TODO: Allow title to be specified? var result = ps.prompt(null, "Attach Link to URI", "Enter a URI:", input, "", {}); if (!result || !input.value) return false; // Create a new attachment Zotero.Attachments.linkFromURL(input.value, itemID); } function addAttachmentFromDialog(link, id) { if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } var itemGroup = ZoteroPane_Local.collectionsView._getItemAtRow(this.collectionsView.selection.currentIndex); if (link && itemGroup.isWithinGroup()) { var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); ps.alert(null, "", "Linked files cannot be added to group libraries."); return; } // TODO: disable in menu if (!this.canEditFiles()) { this.displayCannotEditLibraryFilesMessage(); return; } var libraryID = itemGroup.ref.libraryID; var nsIFilePicker = Components.interfaces.nsIFilePicker; var fp = Components.classes["@mozilla.org/filepicker;1"] .createInstance(nsIFilePicker); fp.init(window, Zotero.getString('pane.item.attachments.select'), nsIFilePicker.modeOpenMultiple); fp.appendFilters(Components.interfaces.nsIFilePicker.filterAll); if(fp.show() == nsIFilePicker.returnOK) { var files = fp.files; while (files.hasMoreElements()){ var file = files.getNext(); file.QueryInterface(Components.interfaces.nsILocalFile); var attachmentID; if(link) attachmentID = Zotero.Attachments.linkFromFile(file, id); else attachmentID = Zotero.Attachments.importFromFile(file, id, libraryID); if(attachmentID && !id) { var c = this.getSelectedCollection(); if(c) c.addItem(attachmentID); } } } } this.addItemFromPage = function (itemType, saveSnapshot, row) { if (!this.canEdit(row)) { this.displayCannotEditLibraryMessage(); return; } return this.addItemFromDocument(window.content.document, itemType, saveSnapshot, row); } /** * @param {Document} doc * @param {String|Integer} [itemType='webpage'] Item type id or name * @param {Boolean} [saveSnapshot] Force saving or non-saving of a snapshot, * regardless of automaticSnapshots pref */ this.addItemFromDocument = function (doc, itemType, saveSnapshot, row) { var progressWin = new Zotero.ProgressWindow(); progressWin.changeHeadline(Zotero.getString('ingester.scraping')); var icon = 'chrome://zotero/skin/treeitem-webpage.png'; progressWin.addLines(doc.title, icon) progressWin.show(); progressWin.startCloseTimer(); // Save snapshot if explicitly enabled or automatically pref is set and not explicitly disabled saveSnapshot = saveSnapshot || (saveSnapshot !== false && Zotero.Prefs.get('automaticSnapshots')); // TODO: this, needless to say, is a temporary hack if (itemType == 'temporaryPDFHack') { itemType = null; var isPDF = false; if (doc.title.indexOf('application/pdf') != -1) { isPDF = true; } else { var ios = Components.classes["@mozilla.org/network/io-service;1"]. getService(Components.interfaces.nsIIOService); try { var uri = ios.newURI(doc.location, null, null); if (uri.fileName && uri.fileName.match(/pdf$/)) { isPDF = true; } } catch (e) { Zotero.debug(e); Components.utils.reportError(e); } } if (isPDF && saveSnapshot) { // // Duplicate newItem() checks here // if (!Zotero.stateCheck()) { this.displayErrorMessage(true); return false; } // Currently selected row if (row === undefined) { row = this.collectionsView.selection.currentIndex; } if (!this.canEdit(row)) { this.displayCannotEditLibraryMessage(); return; } if (row !== undefined) { var itemGroup = this.collectionsView._getItemAtRow(row); var libraryID = itemGroup.ref.libraryID; } else { var libraryID = null; var itemGroup = null; } // // // if (!this.canEditFiles(row)) { this.displayCannotEditLibraryFilesMessage(); return; } if (itemGroup && itemGroup.isCollection()) { var collectionID = itemGroup.ref.id; } else { var collectionID = false; } var itemID = Zotero.Attachments.importFromDocument(doc, false, false, collectionID, null, libraryID); // importFromDocument() doesn't trigger the notifier for a second // // The one-second delay is weird but better than nothing var self = this; setTimeout(function () { self.selectItem(itemID); }, 1001); return; } } // Save web page item by default if (!itemType) { itemType = 'webpage'; } var data = { title: doc.title, url: doc.location.href, accessDate: "CURRENT_TIMESTAMP" } itemType = Zotero.ItemTypes.getID(itemType); var item = this.newItem(itemType, data, row); if (item.libraryID) { var group = Zotero.Groups.getByLibraryID(item.libraryID); filesEditable = group.filesEditable; } else { filesEditable = true; } if (saveSnapshot) { var link = false; if (link) { Zotero.Attachments.linkFromDocument(doc, item.id); } else if (filesEditable) { Zotero.Attachments.importFromDocument(doc, item.id); } } return item.id; } this.addItemFromURL = function (url, itemType, saveSnapshot, row) { if (url == window.content.document.location.href) { return this.addItemFromPage(itemType, saveSnapshot, row); } var self = this; Zotero.MIME.getMIMETypeFromURL(url, function (mimeType, hasNativeHandler) { // If native type, save using a hidden browser if (hasNativeHandler) { var processor = function (doc) { ZoteroPane_Local.addItemFromDocument(doc, itemType, saveSnapshot, row); }; var done = function () {} var exception = function (e) { Zotero.debug(e); } Zotero.HTTP.processDocuments([url], processor, done, exception); } // Otherwise create placeholder item, attach attachment, and update from that else { // TODO: this, needless to say, is a temporary hack if (itemType == 'temporaryPDFHack') { itemType = null; if (mimeType == 'application/pdf') { // // Duplicate newItem() checks here // if (!Zotero.stateCheck()) { ZoteroPane_Local.displayErrorMessage(true); return false; } // Currently selected row if (row === undefined) { row = ZoteroPane_Local.collectionsView.selection.currentIndex; } if (!ZoteroPane_Local.canEdit(row)) { ZoteroPane_Local.displayCannotEditLibraryMessage(); return; } if (row !== undefined) { var itemGroup = ZoteroPane_Local.collectionsView._getItemAtRow(row); var libraryID = itemGroup.ref.libraryID; } else { var libraryID = null; var itemGroup = null; } // // // if (!ZoteroPane_Local.canEditFiles(row)) { ZoteroPane_Local.displayCannotEditLibraryFilesMessage(); return; } if (itemGroup && itemGroup.isCollection()) { var collectionID = itemGroup.ref.id; } else { var collectionID = false; } var attachmentItem = Zotero.Attachments.importFromURL(url, false, false, false, collectionID, mimeType, libraryID); // importFromURL() doesn't trigger the notifier until // after download is complete // // TODO: add a callback to importFromURL() setTimeout(function () { self.selectItem(attachmentItem.id); }, 1001); return; } } if (!itemType) { itemType = 'webpage'; } var item = ZoteroPane_Local.newItem(itemType, {}, row); if (item.libraryID) { var group = Zotero.Groups.getByLibraryID(item.libraryID); filesEditable = group.filesEditable; } else { filesEditable = true; } // Save snapshot if explicitly enabled or automatically pref is set and not explicitly disabled if (saveSnapshot || (saveSnapshot !== false && Zotero.Prefs.get('automaticSnapshots'))) { var link = false; if (link) { //Zotero.Attachments.linkFromURL(doc, item.id); } else if (filesEditable) { var attachmentItem = Zotero.Attachments.importFromURL(url, item.id, false, false, false, mimeType); if (attachmentItem) { item.setField('title', attachmentItem.getField('title')); item.setField('url', attachmentItem.getField('url')); item.setField('accessDate', attachmentItem.getField('accessDate')); item.save(); } } } return item.id; } }); } /* * Create an attachment from the current page * * |itemID| -- itemID of parent item * |link| -- create web link instead of snapshot */ this.addAttachmentFromPage = function (link, itemID) { if (!Zotero.stateCheck()) { this.displayErrorMessage(true); return; } if (typeof itemID != 'number') { throw ("itemID must be an integer in ZoteroPane_Local.addAttachmentFromPage()"); } var progressWin = new Zotero.ProgressWindow(); progressWin.changeHeadline(Zotero.getString('save.' + (link ? 'link' : 'attachment'))); var type = link ? 'web-link' : 'snapshot'; var icon = 'chrome://zotero/skin/treeitem-attachment-' + type + '.png'; progressWin.addLines(window.content.document.title, icon) progressWin.show(); progressWin.startCloseTimer(); if (link) { Zotero.Attachments.linkFromDocument(window.content.document, itemID); } else { Zotero.Attachments.importFromDocument(window.content.document, itemID); } } function viewAttachment(itemID, event, noLocateOnMissing, forceExternalViewer) { var attachment = Zotero.Items.get(itemID); if (!attachment.isAttachment()) { throw ("Item " + itemID + " is not an attachment in ZoteroPane_Local.viewAttachment()"); } if (attachment.attachmentLinkMode == Zotero.Attachments.LINK_MODE_LINKED_URL) { this.loadURI(attachment.getField('url'), event); return; } var file = attachment.getFile(); if (file) { if(forceExternalViewer !== undefined) { var externalViewer = forceExternalViewer; } else { var mimeType = attachment.attachmentMIMEType; // If no MIME type specified, try to detect again (I guess in case // we've gotten smarter since the file was imported?) if (!mimeType) { mimeType = Zotero.MIME.getMIMETypeFromFile(file); // TODO: update DB with new info } var ext = Zotero.File.getExtension(file); var externalViewer = Zotero.isStandalone || (!Zotero.MIME.hasNativeHandler(mimeType, ext) && (!Zotero.MIME.hasInternalHandler(mimeType, ext) || Zotero.Prefs.get('launchNonNativeFiles'))); } if (!externalViewer) { var url = 'zotero://attachment/' + itemID + '/'; this.loadURI(url, event, { attachmentID: itemID}); } else { // Some platforms don't have nsILocalFile.launch, so we just load it and // let the Firefox external helper app window handle it try { file.launch(); } catch (e) { Zotero.debug("launch() not supported -- passing file to loadURI()"); var fileURL = attachment.getLocalFileURL(); this.loadURI(fileURL); } } } else { this.showAttachmentNotFoundDialog(itemID, noLocateOnMissing); } } function viewSelectedAttachment(event, noLocateOnMissing) { if (this.itemsView && this.itemsView.selection.count == 1) { this.viewAttachment(this.getSelectedItems(true)[0], event, noLocateOnMissing); } } this.showAttachmentInFilesystem = function (itemID, noLocateOnMissing) { var attachment = Zotero.Items.get(itemID) if (attachment.attachmentLinkMode != Zotero.Attachments.LINK_MODE_LINKED_URL) { var file = attachment.getFile(); if (file){ try { file.reveal(); } catch (e) { // On platforms that don't support nsILocalFile.reveal() (e.g. Linux), // "double-click" the parent directory try { var parent = file.parent.QueryInterface(Components.interfaces.nsILocalFile); parent.launch(); } // If launch also fails, try the OS handler catch (e) { var uri = Components.classes["@mozilla.org/network/io-service;1"]. getService(Components.interfaces.nsIIOService). newFileURI(parent); var protocolService = Components.classes["@mozilla.org/uriloader/external-protocol-service;1"]. getService(Components.interfaces.nsIExternalProtocolService); protocolService.loadUrl(uri); } } } else { this.showAttachmentNotFoundDialog(attachment.id, noLocateOnMissing) } } } /** * Test if the user can edit the currently selected library/collection, * and display an error if not * * @param {Integer} [row] * * @return {Boolean} TRUE if user can edit, FALSE if not */ this.canEdit = function (row) { // Currently selected row if (row === undefined) { row = this.collectionsView.selection.currentIndex; } var itemGroup = this.collectionsView._getItemAtRow(row); return itemGroup.editable; } /** * Test if the user can edit the currently selected library/collection, * and display an error if not * * @param {Integer} [row] * * @return {Boolean} TRUE if user can edit, FALSE if not */ this.canEditFiles = function (row) { // Currently selected row if (row === undefined) { row = this.collectionsView.selection.currentIndex; } var itemGroup = this.collectionsView._getItemAtRow(row); return itemGroup.filesEditable; } this.displayCannotEditLibraryMessage = function () { var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); ps.alert(null, "", "You cannot make changes to the currently selected library."); } this.displayCannotEditLibraryFilesMessage = function () { var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); ps.alert(null, "", "You cannot add files to the currently selected library."); } function showAttachmentNotFoundDialog(itemID, noLocate) { var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]. createInstance(Components.interfaces.nsIPromptService); // Don't show Locate button if (noLocate) { var index = ps.alert(null, Zotero.getString('pane.item.attachments.fileNotFound.title'), Zotero.getString('pane.item.attachments.fileNotFound.text') ); return; } var buttonFlags = (ps.BUTTON_POS_0) * (ps.BUTTON_TITLE_IS_STRING) + (ps.BUTTON_POS_1) * (ps.BUTTON_TITLE_CANCEL); var index = ps.confirmEx(null, Zotero.getString('pane.item.attachments.fileNotFound.title'), Zotero.getString('pane.item.attachments.fileNotFound.text'), buttonFlags, Zotero.getString('general.locate'), null, null, null, {}); if (index == 0) { this.relinkAttachment(itemID); } } this.createParentItemsFromSelected = function () { if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } var items = this.getSelectedItems(); for (var i=0; i<items.length; i++) { var item = items[i]; if (!item.isTopLevelItem() || item.isRegularItem()) { throw('Item ' + itemID + ' is not a top-level attachment or note in ZoteroPane_Local.createParentItemsFromSelected()'); } Zotero.DB.beginTransaction(); // TODO: remove once there are no top-level web attachments if (item.isWebAttachment()) { var parent = new Zotero.Item('webpage'); } else { var parent = new Zotero.Item('document'); } parent.libraryID = item.libraryID; parent.setField('title', item.getField('title')); if (item.isWebAttachment()) { parent.setField('accessDate', item.getField('accessDate')); parent.setField('url', item.getField('url')); } var itemID = parent.save(); item.setSource(itemID); item.save(); Zotero.DB.commitTransaction(); } } this.renameSelectedAttachmentsFromParents = function () { if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } var items = this.getSelectedItems(); for (var i=0; i<items.length; i++) { var item = items[i]; if (!item.isAttachment() || !item.getSource() || item.attachmentLinkMode == Zotero.Attachments.LINK_MODE_LINKED_URL) { throw('Item ' + itemID + ' is not a child file attachment in ZoteroPane_Local.renameAttachmentFromParent()'); } var file = item.getFile(); if (!file) { continue; } var parentItemID = item.getSource(); var newName = Zotero.Attachments.getFileBaseNameFromItem(parentItemID); var ext = file.leafName.match(/[^\.]+$/); if (ext) { newName = newName + '.' + ext; } var renamed = item.renameAttachmentFile(newName); if (renamed !== true) { Zotero.debug("Could not rename file (" + renamed + ")"); continue; } item.setField('title', newName); item.save(); } return true; } function relinkAttachment(itemID) { if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } var item = Zotero.Items.get(itemID); if (!item) { throw('Item ' + itemID + ' not found in ZoteroPane_Local.relinkAttachment()'); } var nsIFilePicker = Components.interfaces.nsIFilePicker; var fp = Components.classes["@mozilla.org/filepicker;1"] .createInstance(nsIFilePicker); fp.init(window, Zotero.getString('pane.item.attachments.select'), nsIFilePicker.modeOpen); var file = item.getFile(false, true); var dir = Zotero.File.getClosestDirectory(file); if (dir) { dir.QueryInterface(Components.interfaces.nsILocalFile); fp.displayDirectory = dir; } fp.appendFilters(Components.interfaces.nsIFilePicker.filterAll); if (fp.show() == nsIFilePicker.returnOK) { var file = fp.file; file.QueryInterface(Components.interfaces.nsILocalFile); item.relinkAttachmentFile(file); } } function reportErrors() { var errors = Zotero.getErrors(true); var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"] .getService(Components.interfaces.nsIWindowWatcher); var data = { msg: Zotero.getString('errorReport.followingErrors', Zotero.appName), e: errors.join('\n\n'), askForSteps: true }; var io = { wrappedJSObject: { Zotero: Zotero, data: data } }; var win = ww.openWindow(null, "chrome://zotero/content/errorReport.xul", "zotero-error-report", "chrome,centerscreen,modal", io); } /* * Display an error message saying that an error has occurred and Firefox * needs to be restarted. * * If |popup| is TRUE, display in popup progress window; otherwise, display * as items pane message */ function displayErrorMessage(popup) { var reportErrorsStr = Zotero.getString('errorReport.reportErrors'); var reportInstructions = Zotero.getString('errorReport.reportInstructions', reportErrorsStr) // Display as popup progress window if (popup) { var pw = new Zotero.ProgressWindow(); pw.changeHeadline(Zotero.getString('general.errorHasOccurred')); var msg = Zotero.getString('general.restartFirefox') + ' ' + reportInstructions; pw.addDescription(msg); pw.show(); pw.startCloseTimer(8000); } // Display as items pane message else { var msg = Zotero.getString('general.errorHasOccurred') + ' ' + Zotero.getString('general.restartFirefox') + '\n\n' + reportInstructions; self.setItemsPaneMessage(msg, true); } Zotero.debug(msg, 1); } this.displayStartupError = function(asPaneMessage) { if(!Zotero || !Zotero.initialized) { if (Zotero) { var errMsg = Zotero.startupError; var errFunc = Zotero.startupErrorHandler; } if (!errMsg) { // Get the stringbundle manually var src = 'chrome://zotero/locale/zotero.properties'; var localeService = Components.classes['@mozilla.org/intl/nslocaleservice;1']. getService(Components.interfaces.nsILocaleService); var appLocale = localeService.getApplicationLocale(); var stringBundleService = Components.classes["@mozilla.org/intl/stringbundle;1"] .getService(Components.interfaces.nsIStringBundleService); var stringBundle = stringBundleService.createBundle(src, appLocale); var errMsg = stringBundle.GetStringFromName('startupError'); } if (errFunc) { errFunc(); } else { // TODO: Add a better error page/window here with reporting // instructions // window.loadURI('chrome://zotero/content/error.xul'); //if(asPaneMessage) { // ZoteroPane_Local.setItemsPaneMessage(errMsg, true); //} else { var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); ps.alert(null, "", errMsg); //} } } } /** * Toggles Zotero-as-a-tab by passing off the request to the ZoteroOverlay object associated * with the present window */ this.toggleTab = function() { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var browserWindow = wm.getMostRecentWindow("navigator:browser"); if(browserWindow.ZoteroOverlay) browserWindow.ZoteroOverlay.toggleTab(); } /** * Shows the Zotero pane, making it visible if it is not and switching to the appropriate tab * if necessary. */ this.show = function() { if(window.ZoteroOverlay) { if(ZoteroOverlay.isTab) { ZoteroOverlay.loadZoteroTab(); } else if(!this.isShowing()) { ZoteroOverlay.toggleDisplay(); } } } /** * Unserializes zotero-persist elements from preferences */ this.unserializePersist = function() { var serializedValues = Zotero.Prefs.get("pane.persist"); if(!serializedValues) return; serializedValues = JSON.parse(serializedValues); for(var id in serializedValues) { var el = document.getElementById(id); if(!el) return; var elValues = serializedValues[id]; for(var attr in elValues) { el.setAttribute(attr, elValues[attr]); } } if(this.itemsView) { // may not yet be initialized try { this.itemsView.sort(); } catch(e) {}; } } /** * Serializes zotero-persist elements to preferences */ this.serializePersist = function() { var serializedValues = {}; for each(var el in document.getElementsByAttribute("zotero-persist", "*")) { if(!el.getAttribute) continue; var id = el.getAttribute("id"); if(!id) continue; var elValues = {}; for each(var attr in el.getAttribute("zotero-persist").split(/[\s,]+/)) { var attrValue = el.getAttribute(attr); elValues[attr] = attrValue; } serializedValues[id] = elValues; } Zotero.Prefs.set("pane.persist", JSON.stringify(serializedValues)); } /** * Moves around the toolbar when the user moves around the pane */ this.updateToolbarPosition = function() { if(document.getElementById("zotero-pane-stack").hidden) return; const PANES = ["collections", "items"]; for each(var paneName in PANES) { var pane = document.getElementById("zotero-"+paneName+"-pane"); var splitter = document.getElementById("zotero-"+paneName+"-splitter"); var toolbar = document.getElementById("zotero-"+paneName+"-toolbar"); var paneComputedStyle = window.getComputedStyle(pane, null); var splitterComputedStyle = window.getComputedStyle(splitter, null); toolbar.style.width = paneComputedStyle.getPropertyValue("width"); toolbar.style.marginRight = splitterComputedStyle.getPropertyValue("width"); } } /** * Opens the about dialog */ this.openAboutDialog = function() { window.openDialog('chrome://zotero/content/about.xul', 'about', 'chrome'); } /** * Adds or removes a function to be called when Zotero is reloaded by switching into or out of * the connector */ this.addReloadListener = function(/** @param {Function} **/func) { if(_reloadFunctions.indexOf(func) === -1) _reloadFunctions.push(func); } /** * Called when Zotero is reloaded (i.e., if it is switched into or out of connector mode) */ function _reload() { Zotero.debug("Reloading Zotero pane"); for each(var func in _reloadFunctions) func(); } } /** * Keep track of which ZoteroPane was local (since ZoteroPane object might get swapped out for a * tab's ZoteroPane) */ var ZoteroPane_Local = ZoteroPane;
chrome/content/zotero/zoteroPane.js
/* ***** BEGIN LICENSE BLOCK ***** Copyright © 2009 Center for History and New Media George Mason University, Fairfax, Virginia, USA http://zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see <http://www.gnu.org/licenses/>. ***** END LICENSE BLOCK ***** */ const ZOTERO_TAB_URL = "chrome://zotero/content/tab.xul"; /* * This object contains the various functions for the interface */ var ZoteroPane = new function() { this.collectionsView = false; this.itemsView = false; this.__defineGetter__('loaded', function () _loaded); //Privileged methods this.init = init; this.destroy = destroy; this.makeVisible = makeVisible; this.isShowing = isShowing; this.isFullScreen = isFullScreen; this.handleKeyDown = handleKeyDown; this.handleKeyUp = handleKeyUp; this.setHighlightedRowsCallback = setHighlightedRowsCallback; this.handleKeyPress = handleKeyPress; this.newItem = newItem; this.newCollection = newCollection; this.newSearch = newSearch; this.openAdvancedSearchWindow = openAdvancedSearchWindow; this.toggleTagSelector = toggleTagSelector; this.updateTagSelectorSize = updateTagSelectorSize; this.getTagSelection = getTagSelection; this.clearTagSelection = clearTagSelection; this.updateTagFilter = updateTagFilter; this.onCollectionSelected = onCollectionSelected; this.itemSelected = itemSelected; this.reindexItem = reindexItem; this.duplicateSelectedItem = duplicateSelectedItem; this.editSelectedCollection = editSelectedCollection; this.copySelectedItemsToClipboard = copySelectedItemsToClipboard; this.clearQuicksearch = clearQuicksearch; this.handleSearchKeypress = handleSearchKeypress; this.handleSearchInput = handleSearchInput; this.search = search; this.selectItem = selectItem; this.getSelectedCollection = getSelectedCollection; this.getSelectedSavedSearch = getSelectedSavedSearch; this.getSelectedItems = getSelectedItems; this.getSortedItems = getSortedItems; this.getSortField = getSortField; this.getSortDirection = getSortDirection; this.buildItemContextMenu = buildItemContextMenu; this.loadURI = loadURI; this.setItemsPaneMessage = setItemsPaneMessage; this.clearItemsPaneMessage = clearItemsPaneMessage; this.contextPopupShowing = contextPopupShowing; this.openNoteWindow = openNoteWindow; this.addTextToNote = addTextToNote; this.addAttachmentFromDialog = addAttachmentFromDialog; this.viewAttachment = viewAttachment; this.viewSelectedAttachment = viewSelectedAttachment; this.showAttachmentNotFoundDialog = showAttachmentNotFoundDialog; this.relinkAttachment = relinkAttachment; this.reportErrors = reportErrors; this.displayErrorMessage = displayErrorMessage; this.document = document; const COLLECTIONS_HEIGHT = 32; // minimum height of the collections pane and toolbar var self = this; var _loaded = false; var titlebarcolorState, titleState, observerService; var _reloadFunctions = []; // Also needs to be changed in collectionTreeView.js var _lastViewedFolderRE = /^(?:(C|S|G)([0-9]+)|L)$/; /** * Called when the window containing Zotero pane is open */ function init() { // Set "Report Errors..." label via property rather than DTD entity, // since we need to reference it in script elsewhere document.getElementById('zotero-tb-actions-reportErrors').setAttribute('label', Zotero.getString('errorReport.reportErrors')); // Set key down handler document.getElementById('appcontent').addEventListener('keydown', ZoteroPane_Local.handleKeyDown, true); if (Zotero.locked) { return; } _loaded = true; var zp = document.getElementById('zotero-pane'); Zotero.setFontSize(zp); ZoteroPane_Local.updateToolbarPosition(); window.addEventListener("resize", ZoteroPane_Local.updateToolbarPosition, false); window.setTimeout(ZoteroPane_Local.updateToolbarPosition, 0); Zotero.updateQuickSearchBox(document); if (Zotero.isMac) { //document.getElementById('zotero-tb-actions-zeroconf-update').setAttribute('hidden', false); document.getElementById('zotero-pane-stack').setAttribute('platform', 'mac'); } else if(Zotero.isWin) { document.getElementById('zotero-pane-stack').setAttribute('platform', 'win'); } if(Zotero.isFx4 || window.ZoteroTab) { // hack, since Fx 4 no longer sets active, and the reverse in polarity of the preferred // property makes things painful to handle otherwise // DEBUG: remove this once we only support Fx 4 zp.setAttribute("ignoreActiveAttribute", "true"); } // register an observer for Zotero reload observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); observerService.addObserver(_reload, "zotero-reloaded", false); this.addReloadListener(_loadPane); // continue loading pane _loadPane(); } /** * Called on window load or when has been reloaded after switching into or out of connector * mode */ function _loadPane() { if(!Zotero || !Zotero.initialized) return; if(Zotero.isConnector) { ZoteroPane_Local.setItemsPaneMessage(Zotero.getString('connector.standaloneOpen')); return; } else { ZoteroPane_Local.clearItemsPaneMessage(); } //Initialize collections view ZoteroPane_Local.collectionsView = new Zotero.CollectionTreeView(); var collectionsTree = document.getElementById('zotero-collections-tree'); collectionsTree.view = ZoteroPane_Local.collectionsView; collectionsTree.controllers.appendController(new Zotero.CollectionTreeCommandController(collectionsTree)); collectionsTree.addEventListener("click", ZoteroPane_Local.onTreeClick, true); var itemsTree = document.getElementById('zotero-items-tree'); itemsTree.controllers.appendController(new Zotero.ItemTreeCommandController(itemsTree)); itemsTree.addEventListener("click", ZoteroPane_Local.onTreeClick, true); var menu = document.getElementById("contentAreaContextMenu"); menu.addEventListener("popupshowing", ZoteroPane_Local.contextPopupShowing, false); Zotero.Keys.windowInit(document); if (Zotero.restoreFromServer) { Zotero.restoreFromServer = false; setTimeout(function () { var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); var buttonFlags = (ps.BUTTON_POS_0) * (ps.BUTTON_TITLE_IS_STRING) + (ps.BUTTON_POS_1) * (ps.BUTTON_TITLE_CANCEL); var index = ps.confirmEx( null, "Zotero Restore", "The local Zotero database has been cleared." + " " + "Would you like to restore from the Zotero server now?", buttonFlags, "Sync Now", null, null, null, {} ); if (index == 0) { Zotero.Sync.Server.sync({ onSuccess: function () { Zotero.Sync.Runner.setSyncIcon(); ps.alert( null, "Restore Completed", "The local Zotero database has been successfully restored." ); }, onError: function (msg) { ps.alert( null, "Restore Failed", "An error occurred while restoring from the server:\n\n" + msg ); Zotero.Sync.Runner.error(msg); } }); } }, 1000); } // If the database was initialized or there are no sync credentials and // Zotero hasn't been run before in this profile, display the start page // -- this way the page won't be displayed when they sync their DB to // another profile or if the DB is initialized erroneously (e.g. while // switching data directory locations) else if (Zotero.Prefs.get('firstRun2') && !Zotero.isStandalone) { if (Zotero.Schema.dbInitialized || !Zotero.Sync.Server.enabled) { setTimeout(function () { var url = "http://zotero.org/start"; gBrowser.selectedTab = gBrowser.addTab(url); }, 400); } Zotero.Prefs.set('firstRun2', false); try { Zotero.Prefs.clear('firstRun'); } catch (e) {} } // Hide sync debugging menu by default if (Zotero.Prefs.get('sync.debugMenu')) { var sep = document.getElementById('zotero-tb-actions-sync-separator'); sep.hidden = false; sep.nextSibling.hidden = false; sep.nextSibling.nextSibling.hidden = false; sep.nextSibling.nextSibling.nextSibling.hidden = false; } if (Zotero.Prefs.get('debugShowDuplicates')) { document.getElementById('zotero-tb-actions-showDuplicates').hidden = false; } } /* * Create the New Item (+) submenu with each item type */ this.buildItemTypeSubMenu = function () { var moreMenu = document.getElementById('zotero-tb-add-more'); // Sort by localized name var t = Zotero.ItemTypes.getSecondaryTypes(); var itemTypes = []; for (var i=0; i<t.length; i++) { itemTypes.push({ id: t[i].id, name: t[i].name, localized: Zotero.ItemTypes.getLocalizedString(t[i].id) }); } var collation = Zotero.getLocaleCollation(); itemTypes.sort(function(a, b) { return collation.compareString(1, a.localized, b.localized); }); for (var i = 0; i<itemTypes.length; i++) { var menuitem = document.createElement("menuitem"); menuitem.setAttribute("label", itemTypes[i].localized); menuitem.setAttribute("oncommand","ZoteroPane_Local.newItem("+itemTypes[i]['id']+")"); menuitem.setAttribute("tooltiptext", ""); moreMenu.appendChild(menuitem); } } this.updateNewItemTypes = function () { var addMenu = document.getElementById('zotero-tb-add').firstChild; // Remove all nodes so we can regenerate var options = addMenu.getElementsByAttribute("class", "zotero-tb-add"); while (options.length) { var p = options[0].parentNode; p.removeChild(options[0]); } var separator = addMenu.firstChild; // Sort by localized name var t = Zotero.ItemTypes.getPrimaryTypes(); var itemTypes = []; for (var i=0; i<t.length; i++) { itemTypes.push({ id: t[i].id, name: t[i].name, localized: Zotero.ItemTypes.getLocalizedString(t[i].id) }); } var collation = Zotero.getLocaleCollation(); itemTypes.sort(function(a, b) { return collation.compareString(1, a.localized, b.localized); }); for (var i = 0; i<itemTypes.length; i++) { var menuitem = document.createElement("menuitem"); menuitem.setAttribute("label", itemTypes[i].localized); menuitem.setAttribute("oncommand","ZoteroPane_Local.newItem("+itemTypes[i]['id']+")"); menuitem.setAttribute("tooltiptext", ""); menuitem.className = "zotero-tb-add"; addMenu.insertBefore(menuitem, separator); } } /* * Called when the window closes */ function destroy() { if (!Zotero || !Zotero.initialized || !_loaded) { return; } if(this.isShowing()) { this.serializePersist(); } var tagSelector = document.getElementById('zotero-tag-selector'); tagSelector.unregister(); this.collectionsView.unregister(); if (this.itemsView) this.itemsView.unregister(); observerService.removeObserver(_reload, "zotero-reloaded", false); } /** * Called before Zotero pane is to be made visible * @return {Boolean} True if Zotero pane should be loaded, false otherwise (if an error * occurred) */ function makeVisible() { // If pane not loaded, load it or display an error message if (!ZoteroPane_Local.loaded) { if (Zotero.locked) { var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); var msg = Zotero.getString('general.operationInProgress') + '\n\n' + Zotero.getString('general.operationInProgress.waitUntilFinished'); ps.alert(null, "", msg); return false; } ZoteroPane_Local.init(); } // If Zotero could not be initialized, display an error message and return if(!Zotero || !Zotero.initialized) { this.displayStartupError(); return false; } this.buildItemTypeSubMenu(); this.unserializePersist(); this.updateToolbarPosition(); this.updateTagSelectorSize(); // restore saved row selection (for tab switching) var containerWindow = (window.ZoteroTab ? window.ZoteroTab.containerWindow : window); if(containerWindow.zoteroSavedCollectionSelection) { this.collectionsView.rememberSelection(containerWindow.zoteroSavedCollectionSelection); delete containerWindow.zoteroSavedCollectionSelection; } // restore saved item selection (for tab switching) if(containerWindow.zoteroSavedItemSelection) { var me = this; // hack to restore saved selection after itemTreeView finishes loading window.setTimeout(function() { if(containerWindow.zoteroSavedItemSelection) { me.itemsView.rememberSelection(containerWindow.zoteroSavedItemSelection); delete containerWindow.zoteroSavedItemSelection; } }, 51); } // Focus the quicksearch on pane open var searchBar = document.getElementById('zotero-tb-search'); setTimeout(function () { searchBar.inputField.select(); }, 1); // Auto-empty trashed items older than a certain number of days var days = Zotero.Prefs.get('trashAutoEmptyDays'); if (days) { var d = new Date(); var deleted = Zotero.Items.emptyTrash(days); var d2 = new Date(); Zotero.debug("Emptied old items from trash in " + (d2 - d) + " ms"); } var d = new Date(); Zotero.purgeDataObjects(); var d2 = new Date(); Zotero.debug("Purged data tables in " + (d2 - d) + " ms"); // Auto-sync on pane open if (Zotero.Prefs.get('sync.autoSync')) { setTimeout(function () { if (!Zotero.Sync.Server.enabled || Zotero.Sync.Server.syncInProgress || Zotero.Sync.Storage.syncInProgress) { Zotero.debug('Sync already running -- skipping auto-sync', 4); return; } if (Zotero.Sync.Server.manualSyncRequired) { Zotero.debug('Manual sync required -- skipping auto-sync', 4); return; } Zotero.Sync.Runner.sync(true); }, 1000); } // Set sync icon to spinning or not // // We don't bother setting an error state at open if (Zotero.Sync.Server.syncInProgress || Zotero.Sync.Storage.syncInProgress) { Zotero.Sync.Runner.setSyncIcon('animate'); } else { Zotero.Sync.Runner.setSyncIcon(); } return true; } /** * Function to be called before ZoteroPane_Local is hidden. Does not actually hide the Zotero pane. */ this.makeHidden = function() { this.serializePersist(); } function isShowing() { var zoteroPane = document.getElementById('zotero-pane-stack'); return zoteroPane.getAttribute('hidden') != 'true' && zoteroPane.getAttribute('collapsed') != 'true'; } function isFullScreen() { return document.getElementById('zotero-pane-stack').getAttribute('fullscreenmode') == 'true'; } /* * Trigger actions based on keyboard shortcuts */ function handleKeyDown(event, from) { try { // Ignore keystrokes outside of Zotero pane if (!(event.originalTarget.ownerDocument instanceof XULDocument)) { return; } } catch (e) { Zotero.debug(e); } if (Zotero.locked) { event.preventDefault(); return; } if (from == 'zotero-pane') { // Highlight collections containing selected items // // We use Control (17) on Windows because Alt triggers the menubar; // otherwise we use Alt/Option (18) if ((Zotero.isWin && event.keyCode == 17 && !event.altKey) || (!Zotero.isWin && event.keyCode == 18 && !event.ctrlKey) && !event.shiftKey && !event.metaKey) { this.highlightTimer = Components.classes["@mozilla.org/timer;1"]. createInstance(Components.interfaces.nsITimer); // {} implements nsITimerCallback this.highlightTimer.initWithCallback({ notify: ZoteroPane_Local.setHighlightedRowsCallback }, 225, Components.interfaces.nsITimer.TYPE_ONE_SHOT); } else if ((Zotero.isWin && event.ctrlKey) || (!Zotero.isWin && event.altKey)) { if (this.highlightTimer) { this.highlightTimer.cancel(); this.highlightTimer = null; } ZoteroPane_Local.collectionsView.setHighlightedRows(); } return; } // Ignore keystrokes if Zotero pane is closed var zoteroPane = document.getElementById('zotero-pane-stack'); if (zoteroPane.getAttribute('hidden') == 'true' || zoteroPane.getAttribute('collapsed') == 'true') { return; } var useShift = Zotero.isMac; var key = String.fromCharCode(event.which); if (!key) { Zotero.debug('No key'); return; } // Ignore modifiers other than Ctrl-Alt or Cmd-Shift if (!((Zotero.isMac ? event.metaKey : event.ctrlKey) && (useShift ? event.shiftKey : event.altKey))) { return; } var command = Zotero.Keys.getCommand(key); if (!command) { return; } Zotero.debug(command); // Errors don't seem to make it out otherwise try { switch (command) { case 'openZotero': try { // Ignore Cmd-Shift-Z keystroke in text areas if (Zotero.isMac && key == 'Z' && event.originalTarget.localName == 'textarea') { Zotero.debug('Ignoring keystroke in text area'); return; } } catch (e) { Zotero.debug(e); } if(window.ZoteroOverlay) window.ZoteroOverlay.toggleDisplay() break; case 'library': document.getElementById('zotero-collections-tree').focus(); ZoteroPane_Local.collectionsView.selection.select(0); break; case 'quicksearch': document.getElementById('zotero-tb-search').select(); break; case 'newItem': ZoteroPane_Local.newItem(2); // book var menu = document.getElementById('zotero-editpane-item-box').itemTypeMenu; menu.focus(); document.getElementById('zotero-editpane-item-box').itemTypeMenu.menupopup.openPopup(menu, "before_start", 0, 0); break; case 'newNote': // Use key that's not the modifier as the popup toggle ZoteroPane_Local.newNote(useShift ? event.altKey : event.shiftKey); break; case 'toggleTagSelector': ZoteroPane_Local.toggleTagSelector(); break; case 'toggleFullscreen': ZoteroPane_Local.toggleTab(); break; case 'copySelectedItemCitationsToClipboard': ZoteroPane_Local.copySelectedItemsToClipboard(true) break; case 'copySelectedItemsToClipboard': ZoteroPane_Local.copySelectedItemsToClipboard(); break; case 'importFromClipboard': Zotero_File_Interface.importFromClipboard(); break; default: throw ('Command "' + command + '" not found in ZoteroPane_Local.handleKeyDown()'); } } catch (e) { Zotero.debug(e, 1); Components.utils.reportError(e); } event.preventDefault(); } function handleKeyUp(event, from) { if (from == 'zotero-pane') { if ((Zotero.isWin && event.keyCode == 17) || (!Zotero.isWin && event.keyCode == 18)) { if (this.highlightTimer) { this.highlightTimer.cancel(); this.highlightTimer = null; } ZoteroPane_Local.collectionsView.setHighlightedRows(); } } } /* * Highlights collections containing selected items on Ctrl (Win) or * Option/Alt (Mac/Linux) press */ function setHighlightedRowsCallback() { var itemIDs = ZoteroPane_Local.getSelectedItems(true); if (itemIDs && itemIDs.length) { var collectionIDs = Zotero.Collections.getCollectionsContainingItems(itemIDs, true); if (collectionIDs) { ZoteroPane_Local.collectionsView.setHighlightedRows(collectionIDs); } } } function handleKeyPress(event, from) { if (from == 'zotero-collections-tree') { if ((event.keyCode == event.DOM_VK_BACK_SPACE && Zotero.isMac) || event.keyCode == event.DOM_VK_DELETE) { ZoteroPane_Local.deleteSelectedCollection(); event.preventDefault(); return; } } else if (from == 'zotero-items-tree') { if ((event.keyCode == event.DOM_VK_BACK_SPACE && Zotero.isMac) || event.keyCode == event.DOM_VK_DELETE) { // If Cmd/Ctrl delete, use forced mode, which does different // things depending on the context var force = event.metaKey || (!Zotero.isMac && event.ctrlKey); ZoteroPane_Local.deleteSelectedItems(force); event.preventDefault(); return; } } } /* * Create a new item * * _data_ is an optional object with field:value for itemData */ function newItem(typeID, data, row) { if (!Zotero.stateCheck()) { this.displayErrorMessage(true); return false; } // Currently selected row if (row === undefined) { row = this.collectionsView.selection.currentIndex; } if (!this.canEdit(row)) { this.displayCannotEditLibraryMessage(); return; } if (row !== undefined) { var itemGroup = this.collectionsView._getItemAtRow(row); var libraryID = itemGroup.ref.libraryID; } else { var libraryID = null; var itemGroup = null; } Zotero.DB.beginTransaction(); var item = new Zotero.Item(typeID); item.libraryID = libraryID; for (var i in data) { item.setField(i, data[i]); } var itemID = item.save(); if (itemGroup && itemGroup.isCollection()) { itemGroup.ref.addItem(itemID); } Zotero.DB.commitTransaction(); //set to Info tab document.getElementById('zotero-view-item').selectedIndex = 0; this.selectItem(itemID); // Update most-recently-used list for New Item menu var mru = Zotero.Prefs.get('newItemTypeMRU'); if (mru) { var mru = mru.split(','); var pos = mru.indexOf(typeID + ''); if (pos != -1) { mru.splice(pos, 1); } mru.unshift(typeID); } else { var mru = [typeID + '']; } Zotero.Prefs.set('newItemTypeMRU', mru.slice(0, 5).join(',')); return Zotero.Items.get(itemID); } function newCollection(parent) { if (!Zotero.stateCheck()) { this.displayErrorMessage(true); return false; } if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); var untitled = Zotero.DB.getNextName('collections', 'collectionName', Zotero.getString('pane.collections.untitled')); var newName = { value: untitled }; var result = promptService.prompt(window, Zotero.getString('pane.collections.newCollection'), Zotero.getString('pane.collections.name'), newName, "", {}); if (!result) { return; } if (!newName.value) { newName.value = untitled; } var collection = new Zotero.Collection; collection.libraryID = this.getSelectedLibraryID(); collection.name = newName.value; collection.parent = parent; collection.save(); } this.newGroup = function () { this.loadURI(Zotero.Groups.addGroupURL); } function newSearch() { if (!Zotero.stateCheck()) { this.displayErrorMessage(true); return false; } var s = new Zotero.Search(); s.libraryID = this.getSelectedLibraryID(); s.addCondition('title', 'contains', ''); var untitled = Zotero.getString('pane.collections.untitled'); untitled = Zotero.DB.getNextName('savedSearches', 'savedSearchName', Zotero.getString('pane.collections.untitled')); var io = {dataIn: {search: s, name: untitled}, dataOut: null}; window.openDialog('chrome://zotero/content/searchDialog.xul','','chrome,modal',io); } this.setUnfiled = function (libraryID, show) { try { var ids = Zotero.Prefs.get('unfiledLibraries').split(','); } catch (e) { var ids = []; } if (!libraryID) { libraryID = 0; } var newids = []; for each(var id in ids) { id = parseInt(id); if (isNaN(id)) { continue; } // Remove current library if hiding if (id == libraryID && !show) { continue; } // Remove libraryIDs that no longer exist if (id != 0 && !Zotero.Libraries.exists(id)) { continue; } newids.push(id); } // Add the current library if it's not already set if (show && newids.indexOf(libraryID) == -1) { newids.push(libraryID); } newids.sort(); Zotero.Prefs.set('unfiledLibraries', newids.join()); if (show) { // 'UNFILED' + '000' + libraryID Zotero.Prefs.set('lastViewedFolder', 'S' + '8634533000' + libraryID); } this.collectionsView.refresh(); // Select new row var row = this.collectionsView.getLastViewedRow(); this.collectionsView.selection.select(row); } this.openLookupWindow = function () { if (!Zotero.stateCheck()) { this.displayErrorMessage(true); return false; } if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } window.openDialog('chrome://zotero/content/lookup.xul', 'zotero-lookup', 'chrome,modal'); } function openAdvancedSearchWindow() { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var enumerator = wm.getEnumerator('zotero:search'); while (enumerator.hasMoreElements()) { var win = enumerator.getNext(); } if (win) { win.focus(); return; } var s = new Zotero.Search(); s.addCondition('title', 'contains', ''); var io = {dataIn: {search: s}, dataOut: null}; window.openDialog('chrome://zotero/content/advancedSearch.xul', '', 'chrome,dialog=no,centerscreen', io); } function toggleTagSelector(){ var tagSelector = document.getElementById('zotero-tag-selector'); var showing = tagSelector.getAttribute('collapsed') == 'true'; tagSelector.setAttribute('collapsed', !showing); this.updateTagSelectorSize(); // If showing, set scope to items in current view // and focus filter textbox if (showing) { _setTagScope(); tagSelector.focusTextbox(); } // If hiding, clear selection else { tagSelector.uninit(); } } function updateTagSelectorSize() { //Zotero.debug('Updating tag selector size'); var zoteroPane = document.getElementById('zotero-pane-stack'); var splitter = document.getElementById('zotero-tags-splitter'); var tagSelector = document.getElementById('zotero-tag-selector'); // Nothing should be bigger than appcontent's height var max = document.getElementById('appcontent').boxObject.height - splitter.boxObject.height; // Shrink tag selector to appcontent's height var maxTS = max - COLLECTIONS_HEIGHT; if (parseInt(tagSelector.getAttribute("height")) > maxTS) { //Zotero.debug("Limiting tag selector height to appcontent"); tagSelector.setAttribute('height', maxTS); } var height = tagSelector.boxObject.height; /*Zotero.debug("tagSelector.boxObject.height: " + tagSelector.boxObject.height); Zotero.debug("tagSelector.getAttribute('height'): " + tagSelector.getAttribute('height')); Zotero.debug("zoteroPane.boxObject.height: " + zoteroPane.boxObject.height); Zotero.debug("zoteroPane.getAttribute('height'): " + zoteroPane.getAttribute('height'));*/ // Don't let the Z-pane jump back down to its previous height // (if shrinking or hiding the tag selector let it clear the min-height) if (zoteroPane.getAttribute('height') < zoteroPane.boxObject.height) { //Zotero.debug("Setting Zotero pane height attribute to " + zoteroPane.boxObject.height); zoteroPane.setAttribute('height', zoteroPane.boxObject.height); } if (tagSelector.getAttribute('collapsed') == 'true') { // 32px is the default Z pane min-height in overlay.css height = 32; } else { // tS.boxObject.height doesn't exist at startup, so get from attribute if (!height) { height = parseInt(tagSelector.getAttribute('height')); } // 121px seems to be enough room for the toolbar and collections // tree at minimum height height = height + COLLECTIONS_HEIGHT; } //Zotero.debug('Setting Zotero pane minheight to ' + height); zoteroPane.setAttribute('minheight', height); if (this.isShowing() && !this.isFullScreen()) { zoteroPane.setAttribute('savedHeight', zoteroPane.boxObject.height); } // Fix bug whereby resizing the Z pane downward after resizing // the tag selector up and then down sometimes caused the Z pane to // stay at a fixed size and get pushed below the bottom tagSelector.height++; tagSelector.height--; } function getTagSelection(){ var tagSelector = document.getElementById('zotero-tag-selector'); return tagSelector.selection ? tagSelector.selection : {}; } function clearTagSelection() { if (!Zotero.Utilities.isEmpty(this.getTagSelection())) { var tagSelector = document.getElementById('zotero-tag-selector'); tagSelector.clearAll(); } } /* * Sets the tag filter on the items view */ function updateTagFilter(){ this.itemsView.setFilter('tags', getTagSelection()); } /* * Set the tags scope to the items in the current view * * Passed to the items tree to trigger on changes */ function _setTagScope() { var itemGroup = self.collectionsView._getItemAtRow(self.collectionsView.selection.currentIndex); var tagSelector = document.getElementById('zotero-tag-selector'); if (!tagSelector.getAttribute('collapsed') || tagSelector.getAttribute('collapsed') == 'false') { Zotero.debug('Updating tag selector with current tags'); if (itemGroup.editable) { tagSelector.mode = 'edit'; } else { tagSelector.mode = 'view'; } tagSelector.libraryID = itemGroup.ref.libraryID; tagSelector.scope = itemGroup.getChildTags(); } } function onCollectionSelected() { if (this.itemsView) { this.itemsView.unregister(); if (this.itemsView.wrappedJSObject.listener) { document.getElementById('zotero-items-tree').removeEventListener( 'keypress', this.itemsView.wrappedJSObject.listener, false ); } this.itemsView.wrappedJSObject.listener = null; document.getElementById('zotero-items-tree').view = this.itemsView = null; } document.getElementById('zotero-tb-search').value = ""; if (this.collectionsView.selection.count != 1) { document.getElementById('zotero-items-tree').view = this.itemsView = null; return; } // this.collectionsView.selection.currentIndex != -1 var itemgroup = this.collectionsView._getItemAtRow(this.collectionsView.selection.currentIndex); /* if (itemgroup.isSeparator()) { document.getElementById('zotero-items-tree').view = this.itemsView = null; return; } */ itemgroup.setSearch(''); itemgroup.setTags(getTagSelection()); itemgroup.showDuplicates = false; try { Zotero.UnresponsiveScriptIndicator.disable(); this.itemsView = new Zotero.ItemTreeView(itemgroup); this.itemsView.addCallback(_setTagScope); document.getElementById('zotero-items-tree').view = this.itemsView; this.itemsView.selection.clearSelection(); } finally { Zotero.UnresponsiveScriptIndicator.enable(); } if (itemgroup.isLibrary()) { Zotero.Prefs.set('lastViewedFolder', 'L'); } if (itemgroup.isCollection()) { Zotero.Prefs.set('lastViewedFolder', 'C' + itemgroup.ref.id); } else if (itemgroup.isSearch()) { Zotero.Prefs.set('lastViewedFolder', 'S' + itemgroup.ref.id); } else if (itemgroup.isGroup()) { Zotero.Prefs.set('lastViewedFolder', 'G' + itemgroup.ref.id); } } this.showDuplicates = function () { if (this.collectionsView.selection.count == 1 && this.collectionsView.selection.currentIndex != -1) { var itemGroup = this.collectionsView._getItemAtRow(this.collectionsView.selection.currentIndex); itemGroup.showDuplicates = true; try { Zotero.UnresponsiveScriptIndicator.disable(); this.itemsView.refresh(); } finally { Zotero.UnresponsiveScriptIndicator.enable(); } } } this.getItemGroup = function () { return this.collectionsView._getItemAtRow(this.collectionsView.selection.currentIndex); } function itemSelected() { if (!Zotero.stateCheck()) { this.displayErrorMessage(); return; } // Display restore button if items selected in Trash if (this.itemsView && this.itemsView.selection.count) { document.getElementById('zotero-item-restore-button').hidden = !this.itemsView._itemGroup.isTrash() || _nonDeletedItemsSelected(this.itemsView); } else { document.getElementById('zotero-item-restore-button').hidden = true; } var tabs = document.getElementById('zotero-view-tabbox'); // save note when switching from a note if(document.getElementById('zotero-item-pane-content').selectedIndex == 2) { document.getElementById('zotero-note-editor').save(); } // Single item selected if (this.itemsView && this.itemsView.selection.count == 1 && this.itemsView.selection.currentIndex != -1) { var item = this.itemsView._getItemAtRow(this.itemsView.selection.currentIndex); if(item.ref.isNote()) { var noteEditor = document.getElementById('zotero-note-editor'); noteEditor.mode = this.collectionsView.editable ? 'edit' : 'view'; // If loading new or different note, disable undo while we repopulate the text field // so Undo doesn't end up clearing the field. This also ensures that Undo doesn't // undo content from another note into the current one. if (!noteEditor.item || noteEditor.item.id != item.ref.id) { noteEditor.disableUndo(); } noteEditor.parent = null; noteEditor.item = item.ref; noteEditor.enableUndo(); var viewButton = document.getElementById('zotero-view-note-button'); if (this.collectionsView.editable) { viewButton.hidden = false; viewButton.setAttribute('noteID', item.ref.id); if (item.ref.getSource()) { viewButton.setAttribute('sourceID', item.ref.getSource()); } else { viewButton.removeAttribute('sourceID'); } } else { viewButton.hidden = true; } document.getElementById('zotero-item-pane-content').selectedIndex = 2; } else if(item.ref.isAttachment()) { var attachmentBox = document.getElementById('zotero-attachment-box'); attachmentBox.mode = this.collectionsView.editable ? 'edit' : 'view'; attachmentBox.item = item.ref; document.getElementById('zotero-item-pane-content').selectedIndex = 3; } // Regular item else { var isCommons = this.getItemGroup().isBucket(); document.getElementById('zotero-item-pane-content').selectedIndex = 1; var tabBox = document.getElementById('zotero-view-tabbox'); var pane = tabBox.selectedIndex; tabBox.firstChild.hidden = isCommons; var button = document.getElementById('zotero-item-show-original'); if (isCommons) { button.hidden = false; button.disabled = !this.getOriginalItem(); } else { button.hidden = true; } if (this.collectionsView.editable) { ZoteroItemPane.viewItem(item.ref, null, pane); tabs.selectedIndex = document.getElementById('zotero-view-item').selectedIndex; } else { ZoteroItemPane.viewItem(item.ref, 'view', pane); tabs.selectedIndex = document.getElementById('zotero-view-item').selectedIndex; } } } // Zero or multiple items selected else { document.getElementById('zotero-item-pane-content').selectedIndex = 0; var label = document.getElementById('zotero-view-selected-label'); if (this.itemsView && this.itemsView.selection.count) { label.value = Zotero.getString('pane.item.selected.multiple', this.itemsView.selection.count); } else { label.value = Zotero.getString('pane.item.selected.zero'); } } } /** * Check if any selected items in the passed (trash) treeview are not deleted * * @param {nsITreeView} * @return {Boolean} */ function _nonDeletedItemsSelected(itemsView) { var start = {}; var end = {}; for (var i=0, len=itemsView.selection.getRangeCount(); i<len; i++) { itemsView.selection.getRangeAt(i, start, end); for (var j=start.value; j<=end.value; j++) { if (!itemsView._getItemAtRow(j).ref.deleted) { return true; } } } return false; } this.updateNoteButtonMenu = function () { var items = ZoteroPane_Local.getSelectedItems(); var button = document.getElementById('zotero-tb-add-child-note'); button.disabled = !this.canEdit() || !(items.length == 1 && (items[0].isRegularItem() || !items[0].isTopLevelItem())); } this.updateAttachmentButtonMenu = function (popup) { var items = ZoteroPane_Local.getSelectedItems(); var disabled = !this.canEdit() || !(items.length == 1 && items[0].isRegularItem()); if (disabled) { for each(var node in popup.childNodes) { node.disabled = true; } return; } var itemgroup = this.collectionsView._getItemAtRow(this.collectionsView.selection.currentIndex); var canEditFiles = this.canEditFiles(); var prefix = "menuitem-iconic zotero-menuitem-attachments-"; for (var i=0; i<popup.childNodes.length; i++) { var node = popup.childNodes[i]; switch (node.className) { case prefix + 'link': node.disabled = itemgroup.isWithinGroup(); break; case prefix + 'snapshot': case prefix + 'file': node.disabled = !canEditFiles; break; case prefix + 'web-link': node.disabled = false; break; default: throw ("Invalid class name '" + node.className + "' in ZoteroPane_Local.updateAttachmentButtonMenu()"); } } } this.checkPDFConverter = function () { if (Zotero.Fulltext.pdfConverterIsRegistered()) { return true; } var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); var buttonFlags = (ps.BUTTON_POS_0) * (ps.BUTTON_TITLE_IS_STRING) + (ps.BUTTON_POS_1) * (ps.BUTTON_TITLE_CANCEL); var index = ps.confirmEx( null, // TODO: localize "PDF Tools Not Installed", "To use this feature, you must first install the PDF tools in " + "the Zotero preferences.", buttonFlags, "Open Preferences", null, null, null, {} ); if (index == 0) { ZoteroPane_Local.openPreferences('zotero-prefpane-search', 'pdftools-install'); } return false; } function reindexItem() { var items = this.getSelectedItems(); if (!items) { return; } var itemIDs = []; var checkPDF = false; for (var i=0; i<items.length; i++) { // If any PDFs, we need to make sure the converter is installed and // prompt for installation if not if (!checkPDF && items[i].attachmentMIMEType && items[i].attachmentMIMEType == "application/pdf") { checkPDF = true; } itemIDs.push(items[i].id); } if (checkPDF) { var installed = this.checkPDFConverter(); if (!installed) { document.getElementById('zotero-attachment-box').updateItemIndexedState(); return; } } Zotero.Fulltext.indexItems(itemIDs, true); document.getElementById('zotero-attachment-box').updateItemIndexedState(); } function duplicateSelectedItem() { if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } var item = this.getSelectedItems()[0]; Zotero.DB.beginTransaction(); // Create new unsaved clone item in target library var newItem = new Zotero.Item(item.itemTypeID); newItem.libraryID = item.libraryID; // DEBUG: save here because clone() doesn't currently work on unsaved tagged items var id = newItem.save(); var newItem = Zotero.Items.get(id); item.clone(false, newItem); newItem.save(); if (this.itemsView._itemGroup.isCollection() && !newItem.getSource()) { this.itemsView._itemGroup.ref.addItem(newItem.id); } Zotero.DB.commitTransaction(); this.selectItem(newItem.id); } this.deleteSelectedItem = function () { Zotero.debug("ZoteroPane_Local.deleteSelectedItem() is deprecated -- use ZoteroPane_Local.deleteSelectedItems()"); this.deleteSelectedItems(); } /* * Remove, trash, or delete item(s), depending on context * * @param {Boolean} [force=false] Trash or delete even if in a collection or search, * or trash without prompt in library */ this.deleteSelectedItems = function (force) { if (!this.itemsView || !this.itemsView.selection.count) { return; } var itemGroup = this.itemsView._itemGroup; if (!itemGroup.isTrash() && !itemGroup.isBucket() && !this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } var toTrash = { title: Zotero.getString('pane.items.trash.title'), text: Zotero.getString( 'pane.items.trash' + (this.itemsView.selection.count > 1 ? '.multiple' : '') ) }; var toDelete = { title: Zotero.getString('pane.items.delete.title'), text: Zotero.getString( 'pane.items.delete' + (this.itemsView.selection.count > 1 ? '.multiple' : '') ) }; if (itemGroup.isLibrary()) { // In library, don't prompt if meta key was pressed var prompt = force ? false : toTrash; } else if (itemGroup.isCollection()) { // In collection, only prompt if trashing var prompt = force ? (itemGroup.isWithinGroup() ? toDelete : toTrash) : false; } // This should be changed if/when groups get trash else if (itemGroup.isGroup()) { var prompt = toDelete; } else if (itemGroup.isSearch()) { if (!force) { return; } var prompt = toTrash; } // Do nothing in share views else if (itemGroup.isShare()) { return; } else if (itemGroup.isBucket()) { var prompt = toDelete; } // Do nothing in trash view if any non-deleted items are selected else if (itemGroup.isTrash()) { var start = {}; var end = {}; for (var i=0, len=this.itemsView.selection.getRangeCount(); i<len; i++) { this.itemsView.selection.getRangeAt(i, start, end); for (var j=start.value; j<=end.value; j++) { if (!this.itemsView._getItemAtRow(j).ref.deleted) { return; } } } var prompt = toDelete; } var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); if (!prompt || promptService.confirm(window, prompt.title, prompt.text)) { this.itemsView.deleteSelection(force); } } this.deleteSelectedCollection = function () { // Remove virtual Unfiled search var row = this.collectionsView._getItemAtRow(this.collectionsView.selection.currentIndex); if (row.isSearch() && (row.ref.id + "").match(/^8634533000/)) { // 'UNFILED000' this.setUnfiled(row.ref.libraryID, false); return; } if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } if (this.collectionsView.selection.count == 1) { if (row.isCollection()) { if (confirm(Zotero.getString('pane.collections.delete'))) { this.collectionsView.deleteSelection(); } } else if (row.isSearch()) { if (confirm(Zotero.getString('pane.collections.deleteSearch'))) { this.collectionsView.deleteSelection(); } } } } // Currently used only for Commons to find original linked item this.getOriginalItem = function () { var item = this.getSelectedItems()[0]; var itemGroup = this.getItemGroup(); // TEMP: Commons buckets only return itemGroup.ref.getLocalItem(item); } this.showOriginalItem = function () { var item = this.getOriginalItem(); if (!item) { Zotero.debug("Original item not found"); return; } this.selectItem(item.id); } this.restoreSelectedItems = function () { var items = this.getSelectedItems(); if (!items) { return; } Zotero.DB.beginTransaction(); for (var i=0; i<items.length; i++) { items[i].deleted = false; items[i].save(); } Zotero.DB.commitTransaction(); } this.emptyTrash = function () { var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); var result = ps.confirm( null, "", Zotero.getString('pane.collections.emptyTrash') + "\n\n" + Zotero.getString('general.actionCannotBeUndone') ); if (result) { Zotero.Items.emptyTrash(); Zotero.purgeDataObjects(true); } } this.createCommonsBucket = function () { var self = this; Zotero.Commons.getBuckets(function () { var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); var invalid = false; while (true) { if (invalid) { // TODO: localize ps.alert(null, "", "Invalid title. Please try again."); invalid = false; } var newTitle = {}; var result = prompt.prompt( null, "", // TODO: localize "Enter a title for this Zotero Commons collection:", newTitle, "", {} ); if (!result) { return; } var title = Zotero.Utilities.trim(newTitle.value); if (!title) { return; } if (!Zotero.Commons.isValidBucketTitle(title)) { invalid = true; continue; } break; } invalid = false; var origName = title.toLowerCase(); origName = origName.replace(/[^a-z0-9 ._-]/g, ''); origName = origName.replace(/ /g, '-'); origName = origName.substr(0, 32); while (true) { if (invalid) { // TODO: localize var msg = "'" + testName + "' is not a valid Zotero Commons collection identifier.\n\n" + "Collection identifiers can contain basic Latin letters, numbers, " + "hyphens, and underscores and must be no longer than 32 characters. " + "Spaces and other characters are not allowed."; ps.alert(null, "", msg); invalid = false; } var newName = { value: origName }; var result = ps.prompt( null, "", // TODO: localize "Enter an identifier for the collection '" + title + "'.\n\n" + "The identifier will form the collection's URL on archive.org. " + "Identifiers can contain basic Latin letters, numbers, hyphens, and underscores " + "and must be no longer than 32 characters. " + "Spaces and other characters are not allowed.\n\n" + '"' + Zotero.Commons.userNameSlug + '-" ' + "will be automatically prepended to your entry.", newName, "", {} ); if (!result) { return; } var name = Zotero.Utilities.trim(newName.value); if (!name) { return; } var testName = Zotero.Commons.userNameSlug + '-' + name; if (!Zotero.Commons.isValidBucketName(testName)) { invalid = true; continue; } break; } // TODO: localize var progressWin = new Zotero.ProgressWindow(); progressWin.changeHeadline("Creating Zotero Commons Collection"); var icon = self.collectionsView.getImageSrc(self.collectionsView.selection.currentIndex); progressWin.addLines(title, icon) progressWin.show(); Zotero.Commons.createBucket(name, title, function () { progressWin.startCloseTimer(); }); }); } this.refreshCommonsBucket = function() { if (!this.collectionsView || !this.collectionsView.selection || this.collectionsView.selection.count != 1 || this.collectionsView.selection.currentIndex == -1) { return false; } var itemGroup = this.collectionsView._getItemAtRow(this.collectionsView.selection.currentIndex); if (itemGroup && itemGroup.isBucket()) { var self = this; itemGroup.ref.refreshItems(function () { self.itemsView.refresh(); self.itemsView.sort(); // On a manual refresh, also check for new OCRed files //Zotero.Commons.syncFiles(); }); } } function editSelectedCollection() { if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } if (this.collectionsView.selection.count > 0) { var row = this.collectionsView._getItemAtRow(this.collectionsView.selection.currentIndex); if (row.isCollection()) { var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); var newName = { value: row.getName() }; var result = promptService.prompt(window, "", Zotero.getString('pane.collections.rename'), newName, "", {}); if (result && newName.value) { row.ref.name = newName.value; row.ref.save(); } } else { var s = new Zotero.Search(); s.id = row.ref.id; var io = {dataIn: {search: s, name: row.getName()}, dataOut: null}; window.openDialog('chrome://zotero/content/searchDialog.xul','','chrome,modal',io); if (io.dataOut) { this.onCollectionSelected(); //reload itemsView } } } } function copySelectedItemsToClipboard(asCitations) { var items = this.getSelectedItems(); if (!items.length) { return; } // Make sure at least one item is a regular item // // DEBUG: We could copy notes via keyboard shortcut if we altered // Z_F_I.copyItemsToClipboard() to use Z.QuickCopy.getContentFromItems(), // but 1) we'd need to override that function's drag limit and 2) when I // tried it the OS X clipboard seemed to be getting text vs. HTML wrong, // automatically converting text/html to plaintext rather than using // text/unicode. (That may be fixable, however.) var canCopy = false; for each(var item in items) { if (item.isRegularItem()) { canCopy = true; break; } } if (!canCopy) { var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); ps.alert(null, "", Zotero.getString("fileInterface.noReferencesError")); return; } var url = window.content.location.href; var [mode, format] = Zotero.QuickCopy.getFormatFromURL(url).split('='); var [mode, contentType] = mode.split('/'); if (mode == 'bibliography') { if (asCitations) { Zotero_File_Interface.copyCitationToClipboard(items, format, contentType == 'html'); } else { Zotero_File_Interface.copyItemsToClipboard(items, format, contentType == 'html'); } } else if (mode == 'export') { // Copy citations doesn't work in export mode if (asCitations) { return; } else { Zotero_File_Interface.exportItemsToClipboard(items, format); } } } function clearQuicksearch() { var search = document.getElementById('zotero-tb-search'); if (search.value != '') { search.value = ''; ZoteroPane_Local.search(); } } function handleSearchKeypress(textbox, event) { // Events that turn find-as-you-type on if (event.keyCode == event.DOM_VK_ESCAPE) { textbox.value = ''; ZoteroPane_Local.setItemsPaneMessage(Zotero.getString('searchInProgress')); setTimeout(function () { ZoteroPane_Local.search(); ZoteroPane_Local.clearItemsPaneMessage(); }, 1); } else if (event.keyCode == event.DOM_VK_RETURN || event.keyCode == event.DOM_VK_ENTER) { ZoteroPane_Local.setItemsPaneMessage(Zotero.getString('searchInProgress')); setTimeout(function () { ZoteroPane_Local.search(true); ZoteroPane_Local.clearItemsPaneMessage(); }, 1); } } function handleSearchInput(textbox, event) { // This is the new length, except, it seems, when the change is a // result of Undo or Redo if (!textbox.value.length) { ZoteroPane_Local.setItemsPaneMessage(Zotero.getString('searchInProgress')); setTimeout(function () { ZoteroPane_Local.search(); ZoteroPane_Local.clearItemsPaneMessage(); }, 1); } else if (textbox.value.indexOf('"') != -1) { ZoteroPane_Local.setItemsPaneMessage(Zotero.getString('advancedSearchMode')); } } function search(runAdvanced) { if (this.itemsView) { var search = document.getElementById('zotero-tb-search'); if (!runAdvanced && search.value.indexOf('"') != -1) { return; } var searchVal = search.value; this.itemsView.setFilter('search', searchVal); } } /* * Select item in current collection or, if not there, in Library * * If _inLibrary_, force switch to Library * If _expand_, open item if it's a container */ function selectItem(itemID, inLibrary, expand) { if (!itemID) { return false; } var item = Zotero.Items.get(itemID); if (!item) { return false; } if (!this.itemsView) { Components.utils.reportError("Items view not set in ZoteroPane_Local.selectItem()"); return false; } var currentLibraryID = this.getSelectedLibraryID(); // If in a different library if (item.libraryID != currentLibraryID) { Zotero.debug("Library ID differs; switching library"); this.collectionsView.selectLibrary(item.libraryID); } // Force switch to library view else if (!this.itemsView._itemGroup.isLibrary() && inLibrary) { Zotero.debug("Told to select in library; switching to library"); this.collectionsView.selectLibrary(item.libraryID); } var selected = this.itemsView.selectItem(itemID, expand); if (!selected) { Zotero.debug("Item was not selected; switching to library"); this.collectionsView.selectLibrary(item.libraryID); this.itemsView.selectItem(itemID, expand); } return true; } this.getSelectedLibraryID = function () { var group = this.getSelectedGroup(); if (group) { return group.libraryID; } var collection = this.getSelectedCollection(); if (collection) { return collection.libraryID; } return null; } function getSelectedCollection(asID) { if (this.collectionsView) { return this.collectionsView.getSelectedCollection(asID); } return false; } function getSelectedSavedSearch(asID) { if (this.collectionsView.selection.count > 0 && this.collectionsView.selection.currentIndex != -1) { var collection = this.collectionsView._getItemAtRow(this.collectionsView.selection.currentIndex); if (collection && collection.isSearch()) { return asID ? collection.ref.id : collection.ref; } } return false; } /* * Return an array of Item objects for selected items * * If asIDs is true, return an array of itemIDs instead */ function getSelectedItems(asIDs) { if (!this.itemsView) { return []; } return this.itemsView.getSelectedItems(asIDs); } this.getSelectedGroup = function (asID) { if (this.collectionsView.selection && this.collectionsView.selection.count > 0 && this.collectionsView.selection.currentIndex != -1) { var itemGroup = this.collectionsView._getItemAtRow(this.collectionsView.selection.currentIndex); if (itemGroup && itemGroup.isGroup()) { return asID ? itemGroup.ref.id : itemGroup.ref; } } return false; } /* * Returns an array of Zotero.Item objects of visible items in current sort order * * If asIDs is true, return an array of itemIDs instead */ function getSortedItems(asIDs) { if (!this.itemsView) { return []; } return this.itemsView.getSortedItems(asIDs); } function getSortField() { if (!this.itemsView) { return false; } return this.itemsView.getSortField(); } function getSortDirection() { if (!this.itemsView) { return false; } return this.itemsView.getSortDirection(); } this.buildCollectionContextMenu = function buildCollectionContextMenu() { var menu = document.getElementById('zotero-collectionmenu'); var m = { newCollection: 0, newSavedSearch: 1, newSubcollection: 2, sep1: 3, showUnfiled: 4, editSelectedCollection: 5, removeCollection: 6, sep2: 7, exportCollection: 8, createBibCollection: 9, exportFile: 10, loadReport: 11, emptyTrash: 12, createCommonsBucket: 13, refreshCommonsBucket: 14 }; var itemGroup = this.collectionsView._getItemAtRow(this.collectionsView.selection.currentIndex); var enable = [], disable = [], show = []; // Collection if (itemGroup.isCollection()) { show = [ m.newSubcollection, m.sep1, m.editSelectedCollection, m.removeCollection, m.sep2, m.exportCollection, m.createBibCollection, m.loadReport ]; var s = [m.exportCollection, m.createBibCollection, m.loadReport]; if (this.itemsView.rowCount>0) { enable = s; } else if (!this.collectionsView.isContainerEmpty(this.collectionsView.selection.currentIndex)) { enable = [m.exportCollection]; disable = [m.createBibCollection, m.loadReport]; } else { disable = s; } // Adjust labels menu.childNodes[m.editSelectedCollection].setAttribute('label', Zotero.getString('pane.collections.menu.rename.collection')); menu.childNodes[m.removeCollection].setAttribute('label', Zotero.getString('pane.collections.menu.remove.collection')); menu.childNodes[m.exportCollection].setAttribute('label', Zotero.getString('pane.collections.menu.export.collection')); menu.childNodes[m.createBibCollection].setAttribute('label', Zotero.getString('pane.collections.menu.createBib.collection')); menu.childNodes[m.loadReport].setAttribute('label', Zotero.getString('pane.collections.menu.generateReport.collection')); } // Saved Search else if (itemGroup.isSearch()) { // Unfiled items view if ((itemGroup.ref.id + "").match(/^8634533000/)) { // 'UNFILED000' show = [ m.removeCollection ]; menu.childNodes[m.removeCollection].setAttribute('label', Zotero.getString('general.remove')); } // Normal search view else { show = [ m.editSelectedCollection, m.removeCollection, m.sep2, m.exportCollection, m.createBibCollection, m.loadReport ]; menu.childNodes[m.removeCollection].setAttribute('label', Zotero.getString('pane.collections.menu.remove.savedSearch')); } var s = [m.exportCollection, m.createBibCollection, m.loadReport]; if (this.itemsView.rowCount>0) { enable = s; } else { disable = s; } // Adjust labels menu.childNodes[m.editSelectedCollection].setAttribute('label', Zotero.getString('pane.collections.menu.edit.savedSearch')); menu.childNodes[m.exportCollection].setAttribute('label', Zotero.getString('pane.collections.menu.export.savedSearch')); menu.childNodes[m.createBibCollection].setAttribute('label', Zotero.getString('pane.collections.menu.createBib.savedSearch')); menu.childNodes[m.loadReport].setAttribute('label', Zotero.getString('pane.collections.menu.generateReport.savedSearch')); } // Trash else if (itemGroup.isTrash()) { show = [m.emptyTrash]; } else if (itemGroup.isHeader()) { if (itemGroup.ref.id == 'commons-header') { show = [m.createCommonsBucket]; } } else if (itemGroup.isBucket()) { show = [m.refreshCommonsBucket]; } // Group else if (itemGroup.isGroup()) { show = [m.newCollection, m.newSavedSearch, m.sep1, m.showUnfiled]; } // Library else { show = [m.newCollection, m.newSavedSearch, m.sep1, m.showUnfiled, m.sep2, m.exportFile]; } // Disable some actions if user doesn't have write access var s = [m.editSelectedCollection, m.removeCollection, m.newCollection, m.newSavedSearch, m.newSubcollection]; if (itemGroup.isWithinGroup() && !itemGroup.editable) { disable = disable.concat(s); } else { enable = enable.concat(s); } for (var i in disable) { menu.childNodes[disable[i]].setAttribute('disabled', true); } for (var i in enable) { menu.childNodes[enable[i]].setAttribute('disabled', false); } // Hide all items by default for each(var pos in m) { menu.childNodes[pos].setAttribute('hidden', true); } for (var i in show) { menu.childNodes[show[i]].setAttribute('hidden', false); } } function buildItemContextMenu() { var m = { showInLibrary: 0, sep1: 1, addNote: 2, addAttachments: 3, sep2: 4, duplicateItem: 5, deleteItem: 6, deleteFromLibrary: 7, sep3: 8, exportItems: 9, createBib: 10, loadReport: 11, sep4: 12, createParent: 13, recognizePDF: 14, renameAttachments: 15, reindexItem: 16 }; var menu = document.getElementById('zotero-itemmenu'); // remove old locate menu items while(menu.firstChild && menu.firstChild.getAttribute("zotero-locate")) { menu.removeChild(menu.firstChild); } var enable = [], disable = [], show = [], hide = [], multiple = ''; if (!this.itemsView) { return; } if (this.itemsView.selection.count > 0) { var itemGroup = this.itemsView._itemGroup; enable.push(m.showInLibrary, m.addNote, m.addAttachments, m.sep2, m.duplicateItem, m.deleteItem, m.deleteFromLibrary, m.exportItems, m.createBib, m.loadReport); // Multiple items selected if (this.itemsView.selection.count > 1) { var multiple = '.multiple'; hide.push(m.showInLibrary, m.sep1, m.addNote, m.addAttachments, m.sep2, m.duplicateItem); // If all items can be reindexed, or all items can be recognized, show option var items = this.getSelectedItems(); var canIndex = true; var canRecognize = true; if (!Zotero.Fulltext.pdfConverterIsRegistered()) { canIndex = false; } for (var i=0; i<items.length; i++) { if (canIndex && !Zotero.Fulltext.canReindex(items[i].id)) { canIndex = false; } if (canRecognize && !Zotero_RecognizePDF.canRecognize(items[i])) { canRecognize = false; } if (!canIndex && !canRecognize) { break; } } if (canIndex) { show.push(m.reindexItem); } else { hide.push(m.reindexItem); } if (canRecognize) { show.push(m.recognizePDF); hide.push(m.createParent); } else { hide.push(m.recognizePDF); var canCreateParent = true; for (var i=0; i<items.length; i++) { if (!items[i].isTopLevelItem() || items[i].isRegularItem() || Zotero_RecognizePDF.canRecognize(items[i])) { canCreateParent = false; break; } } if (canCreateParent) { show.push(m.createParent); } else { hide.push(m.createParent); } } // If all items are child attachments, show rename option var canRename = true; for (var i=0; i<items.length; i++) { var item = items[i]; // Same check as in rename function if (!item.isAttachment() || !item.getSource() || item.attachmentLinkMode == Zotero.Attachments.LINK_MODE_LINKED_URL) { canRename = false; break; } } if (canRename) { show.push(m.renameAttachments); } else { hide.push(m.renameAttachments); } // Add in attachment separator if (canCreateParent || canRecognize || canRename || canIndex) { show.push(m.sep4); } else { hide.push(m.sep4); } // Block certain actions on files if no access and at least one item // is an imported attachment if (!itemGroup.filesEditable) { var hasImportedAttachment = false; for (var i=0; i<items.length; i++) { var item = items[i]; if (item.isImportedAttachment()) { hasImportedAttachment = true; break; } } if (hasImportedAttachment) { var d = [m.deleteFromLibrary, m.createParent, m.renameAttachments]; for each(var val in d) { disable.push(val); var index = enable.indexOf(val); if (index != -1) { enable.splice(index, 1); } } } } } // Single item selected else { var item = this.itemsView._getItemAtRow(this.itemsView.selection.currentIndex).ref; var itemID = item.id; menu.setAttribute('itemID', itemID); // Show in Library if (!itemGroup.isLibrary() && !itemGroup.isWithinGroup()) { show.push(m.showInLibrary, m.sep1); } else { hide.push(m.showInLibrary, m.sep1); } if (item.isRegularItem()) { show.push(m.addNote, m.addAttachments, m.sep2); } else { hide.push(m.addNote, m.addAttachments, m.sep2); } if (item.isAttachment()) { var showSep4 = false; hide.push(m.duplicateItem); if (Zotero_RecognizePDF.canRecognize(item)) { show.push(m.recognizePDF); hide.push(m.createParent); showSep4 = true; } else { hide.push(m.recognizePDF); // If not a PDF, allow parent item creation if (item.isTopLevelItem()) { show.push(m.createParent); showSep4 = true; } else { hide.push(m.createParent); } } // Attachment rename option if (item.getSource() && item.attachmentLinkMode != Zotero.Attachments.LINK_MODE_LINKED_URL) { show.push(m.renameAttachments); showSep4 = true; } else { hide.push(m.renameAttachments); } if (showSep4) { show.push(m.sep4); } else { hide.push(m.sep4); } // If not linked URL, show reindex line if (Zotero.Fulltext.pdfConverterIsRegistered() && Zotero.Fulltext.canReindex(item.id)) { show.push(m.reindexItem); showSep4 = true; } else { hide.push(m.reindexItem); } } else { if (item.isNote() && item.isTopLevelItem()) { show.push(m.sep4, m.createParent); } else { hide.push(m.sep4, m.createParent); } show.push(m.duplicateItem); hide.push(m.recognizePDF, m.renameAttachments, m.reindexItem); } // Update attachment submenu var popup = document.getElementById('zotero-add-attachment-popup') this.updateAttachmentButtonMenu(popup); // Block certain actions on files if no access if (item.isImportedAttachment() && !itemGroup.filesEditable) { var d = [m.deleteFromLibrary, m.createParent, m.renameAttachments]; for each(var val in d) { disable.push(val); var index = enable.indexOf(val); if (index != -1) { enable.splice(index, 1); } } } } } // No items selected else { // Show in Library if (!itemGroup.isLibrary()) { show.push(m.showInLibrary, m.sep1); } else { hide.push(m.showInLibrary, m.sep1); } disable.push(m.showInLibrary, m.duplicateItem, m.deleteItem, m.deleteFromLibrary, m.exportItems, m.createBib, m.loadReport); hide.push(m.addNote, m.addAttachments, m.sep2, m.sep4, m.reindexItem, m.createParent, m.recognizePDF, m.renameAttachments); } // TODO: implement menu for remote items if (!itemGroup.editable) { for (var i in m) { // Still show export/bib/report for non-editable views // (other than Commons buckets, which aren't real items) if (!itemGroup.isBucket()) { switch (i) { case 'exportItems': case 'createBib': case 'loadReport': continue; } } disable.push(m[i]); var index = enable.indexOf(m[i]); if (index != -1) { enable.splice(index, 1); } } } // Remove from collection if (this.itemsView._itemGroup.isCollection() && !(item && item.getSource())) { menu.childNodes[m.deleteItem].setAttribute('label', Zotero.getString('pane.items.menu.remove' + multiple)); show.push(m.deleteItem); } else { hide.push(m.deleteItem); } // Plural if necessary menu.childNodes[m.deleteFromLibrary].setAttribute('label', Zotero.getString('pane.items.menu.erase' + multiple)); menu.childNodes[m.exportItems].setAttribute('label', Zotero.getString('pane.items.menu.export' + multiple)); menu.childNodes[m.createBib].setAttribute('label', Zotero.getString('pane.items.menu.createBib' + multiple)); menu.childNodes[m.loadReport].setAttribute('label', Zotero.getString('pane.items.menu.generateReport' + multiple)); menu.childNodes[m.createParent].setAttribute('label', Zotero.getString('pane.items.menu.createParent' + multiple)); menu.childNodes[m.recognizePDF].setAttribute('label', Zotero.getString('pane.items.menu.recognizePDF' + multiple)); menu.childNodes[m.renameAttachments].setAttribute('label', Zotero.getString('pane.items.menu.renameAttachments' + multiple)); menu.childNodes[m.reindexItem].setAttribute('label', Zotero.getString('pane.items.menu.reindexItem' + multiple)); for (var i in disable) { menu.childNodes[disable[i]].setAttribute('disabled', true); } for (var i in enable) { menu.childNodes[enable[i]].setAttribute('disabled', false); } for (var i in hide) { menu.childNodes[hide[i]].setAttribute('hidden', true); } for (var i in show) { menu.childNodes[show[i]].setAttribute('hidden', false); } // add locate menu options Zotero_LocateMenu.buildContextMenu(menu); } // Adapted from: http://www.xulplanet.com/references/elemref/ref_tree.html#cmnote-9 this.onTreeClick = function (event) { // We only care about primary button double and triple clicks if (!event || (event.detail != 2 && event.detail != 3) || event.button != 0) { return; } var t = event.originalTarget; if (t.localName != 'treechildren') { return; } var tree = t.parentNode; var row = {}, col = {}, obj = {}; tree.treeBoxObject.getCellAt(event.clientX, event.clientY, row, col, obj); // obj.value == 'cell'/'text'/'image' if (!obj.value) { return; } if (tree.id == 'zotero-collections-tree') { // Ignore triple clicks for collections if (event.detail != 2) { return; } var itemGroup = ZoteroPane_Local.collectionsView._getItemAtRow(tree.view.selection.currentIndex); if (itemGroup.isLibrary()) { var uri = Zotero.URI.getCurrentUserLibraryURI(); if (uri) { ZoteroPane_Local.loadURI(uri); event.stopPropagation(); } return; } if (itemGroup.isSearch()) { // Don't do anything on double-click of Unfiled Items if ((itemGroup.ref.id + "").match(/^8634533000/)) { // 'UNFILED000' return; } ZoteroPane_Local.editSelectedCollection(); return; } if (itemGroup.isGroup()) { var uri = Zotero.URI.getGroupURI(itemGroup.ref, true); ZoteroPane_Local.loadURI(uri); event.stopPropagation(); return; } if (itemGroup.isHeader()) { if (itemGroup.ref.id == 'group-libraries-header') { var uri = Zotero.URI.getGroupsURL(); ZoteroPane_Local.loadURI(uri); event.stopPropagation(); } return; } if (itemGroup.isBucket()) { ZoteroPane_Local.loadURI(itemGroup.ref.uri); event.stopPropagation(); } } else if (tree.id == 'zotero-items-tree') { var viewOnDoubleClick = Zotero.Prefs.get('viewOnDoubleClick'); // Expand/collapse on triple-click if (viewOnDoubleClick) { if (event.detail == 3) { tree.view.toggleOpenState(tree.view.selection.currentIndex); return; } // Don't expand/collapse on double-click event.stopPropagation(); } if (tree.view && tree.view.selection.currentIndex > -1) { var item = ZoteroPane_Local.getSelectedItems()[0]; if (item) { if (item.isRegularItem()) { // Double-click on Commons item should load IA page var itemGroup = ZoteroPane_Local.collectionsView._getItemAtRow( ZoteroPane_Local.collectionsView.selection.currentIndex ); if (itemGroup.isBucket()) { var uri = itemGroup.ref.getItemURI(item); ZoteroPane_Local.loadURI(uri); event.stopPropagation(); return; } if (!viewOnDoubleClick) { return; } var uri = Components.classes["@mozilla.org/network/standard-url;1"]. createInstance(Components.interfaces.nsIURI); var snapID = item.getBestAttachment(); if (snapID) { spec = Zotero.Items.get(snapID).getLocalFileURL(); if (spec) { uri.spec = spec; if (uri.scheme && uri.scheme == 'file') { ZoteroPane_Local.viewAttachment(snapID, event); return; } } } var uri = item.getField('url'); if (!uri) { var doi = item.getField('DOI'); if (doi) { // Pull out DOI, in case there's a prefix doi = Zotero.Utilities.cleanDOI(doi); if (doi) { uri = "http://dx.doi.org/" + encodeURIComponent(doi); } } } if (uri) { ZoteroPane_Local.loadURI(uri); } } else if (item.isNote()) { if (!ZoteroPane_Local.collectionsView.editable) { return; } document.getElementById('zotero-view-note-button').doCommand(); } else if (item.isAttachment()) { ZoteroPane_Local.viewSelectedAttachment(event); } } } } } this.openPreferences = function (paneID, action) { var io = { pane: paneID, action: action }; window.openDialog('chrome://zotero/content/preferences/preferences.xul', 'zotero-prefs', 'chrome,titlebar,toolbar,centerscreen,' + Zotero.Prefs.get('browser.preferences.instantApply', true) ? 'dialog=no' : 'modal', io ); } /* * Loads a URL following the standard modifier key behavior * (e.g. meta-click == new background tab, meta-shift-click == new front tab, * shift-click == new window, no modifier == frontmost tab */ function loadURI(uris, event, data) { if(typeof uris === "string") { uris = [uris]; } for each(var uri in uris) { // Ignore javascript: and data: URIs if (uri.match(/^(javascript|data):/)) { return; } if (Zotero.isStandalone && uri.match(/^https?/)) { var io = Components.classes['@mozilla.org/network/io-service;1'] .getService(Components.interfaces.nsIIOService); var uri = io.newURI(uri, null, null); var handler = Components.classes['@mozilla.org/uriloader/external-protocol-service;1'] .getService(Components.interfaces.nsIExternalProtocolService) .getProtocolHandlerInfo('http'); handler.preferredAction = Components.interfaces.nsIHandlerInfo.useSystemDefault; handler.launchWithURI(uri, null); return; } // Open in new tab var openInNewTab = event && (event.metaKey || (!Zotero.isMac && event.ctrlKey)); if (event && event.shiftKey && !openInNewTab) { window.open(uri, "zotero-loaded-page", "menubar=yes,location=yes,toolbar=yes,personalbar=yes,resizable=yes,scrollbars=yes,status=yes"); } else if (openInNewTab || !window.loadURI || uris.length > 1) { // if no gBrowser, find it if(!gBrowser) { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var browserWindow = wm.getMostRecentWindow("navigator:browser"); var gBrowser = browserWindow.gBrowser; } // load in a new tab var tab = gBrowser.addTab(uri); var browser = gBrowser.getBrowserForTab(tab); if (event && event.shiftKey || !openInNewTab) { // if shift key is down, or we are opening in a new tab because there is no loadURI, // select new tab gBrowser.selectedTab = tab; } } else { window.loadURI(uri); } } } function setItemsPaneMessage(msg, lock) { var elem = document.getElementById('zotero-items-pane-message-box'); if (elem.getAttribute('locked') == 'true') { return; } while (elem.hasChildNodes()) { elem.removeChild(elem.firstChild); } var msgParts = msg.split("\n\n"); for (var i=0; i<msgParts.length; i++) { var desc = document.createElement('description'); desc.appendChild(document.createTextNode(msgParts[i])); elem.appendChild(desc); } // Make message permanent if (lock) { elem.setAttribute('locked', true); } document.getElementById('zotero-items-pane-content').selectedIndex = 1; } function clearItemsPaneMessage() { // If message box is locked, don't clear var box = document.getElementById('zotero-items-pane-message-box'); if (box.getAttribute('locked') == 'true') { return; } document.getElementById('zotero-items-pane-content').selectedIndex = 0; } // Updates browser context menu options function contextPopupShowing() { if (!Zotero.Prefs.get('browserContentContextMenu')) { return; } var menuitem = document.getElementById("zotero-context-add-to-current-note"); var showing = false; if (menuitem){ var items = ZoteroPane_Local.getSelectedItems(); if (ZoteroPane_Local.itemsView.selection && ZoteroPane_Local.itemsView.selection.count==1 && items[0] && items[0].isNote() && window.gContextMenu.isTextSelected) { menuitem.hidden = false; showing = true; } else { menuitem.hidden = true; } } var menuitem = document.getElementById("zotero-context-add-to-new-note"); if (menuitem){ if (window.gContextMenu.isTextSelected) { menuitem.hidden = false; showing = true; } else { menuitem.hidden = true; } } var menuitem = document.getElementById("zotero-context-save-link-as-item"); if (menuitem) { if (window.gContextMenu.onLink) { menuitem.hidden = false; showing = true; } else { menuitem.hidden = true; } } var menuitem = document.getElementById("zotero-context-save-image-as-item"); if (menuitem) { // Not using window.gContextMenu.hasBGImage -- if the user wants it, // they can use the Firefox option to view and then import from there if (window.gContextMenu.onImage) { menuitem.hidden = false; showing = true; } else { menuitem.hidden = true; } } // If Zotero is locked or library is read-only, disable menu items var menu = document.getElementById('zotero-content-area-context-menu'); menu.hidden = !showing; var disabled = Zotero.locked; if (!disabled && self.collectionsView.selection && self.collectionsView.selection.count) { var itemGroup = self.collectionsView._getItemAtRow(self.collectionsView.selection.currentIndex); disabled = !itemGroup.editable; } for each(var menuitem in menu.firstChild.childNodes) { menuitem.disabled = disabled; } } this.newNote = function (popup, parent, text, citeURI) { if (!Zotero.stateCheck()) { this.displayErrorMessage(true); return; } if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } if (!popup) { if (!text) { text = ''; } text = Zotero.Utilities.trim(text); if (text) { text = '<blockquote' + (citeURI ? ' cite="' + citeURI + '"' : '') + '>' + Zotero.Utilities.text2html(text) + "</blockquote>"; } var item = new Zotero.Item('note'); item.libraryID = this.getSelectedLibraryID(); item.setNote(text); if (parent) { item.setSource(parent); } var itemID = item.save(); if (!parent && this.itemsView && this.itemsView._itemGroup.isCollection()) { this.itemsView._itemGroup.ref.addItem(itemID); } this.selectItem(itemID); document.getElementById('zotero-note-editor').focus(); } else { // TODO: _text_ var c = this.getSelectedCollection(); if (c) { this.openNoteWindow(null, c.id, parent); } else { this.openNoteWindow(null, null, parent); } } } function addTextToNote(text, citeURI) { if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } if (!text) { return false; } text = Zotero.Utilities.trim(text); if (!text.length) { return false; } text = '<blockquote' + (citeURI ? ' cite="' + citeURI + '"' : '') + '>' + Zotero.Utilities.text2html(text) + "</blockquote>"; var items = this.getSelectedItems(); if (this.itemsView.selection.count == 1 && items[0] && items[0].isNote()) { var note = items[0].getNote() items[0].setNote(note + text); items[0].save(); var noteElem = document.getElementById('zotero-note-editor') noteElem.focus(); return true; } return false; } function openNoteWindow(itemID, col, parentItemID) { if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } var name = null; if (itemID) { // Create a name for this window so we can focus it later // // Collection is only used on new notes, so we don't need to // include it in the name name = 'zotero-note-' + itemID; var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var e = wm.getEnumerator(''); while (e.hasMoreElements()) { var w = e.getNext(); if (w.name == name) { w.focus(); return; } } } window.open('chrome://zotero/content/note.xul?v=1' + (itemID ? '&id=' + itemID : '') + (col ? '&coll=' + col : '') + (parentItemID ? '&p=' + parentItemID : ''), name, 'chrome,resizable,centerscreen'); } this.addAttachmentFromURI = function (link, itemID) { if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); var input = {}; var check = {value : false}; // TODO: Localize // TODO: Allow title to be specified? var result = ps.prompt(null, "Attach Link to URI", "Enter a URI:", input, "", {}); if (!result || !input.value) return false; // Create a new attachment Zotero.Attachments.linkFromURL(input.value, itemID); } function addAttachmentFromDialog(link, id) { if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } var itemGroup = ZoteroPane_Local.collectionsView._getItemAtRow(this.collectionsView.selection.currentIndex); if (link && itemGroup.isWithinGroup()) { var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); ps.alert(null, "", "Linked files cannot be added to group libraries."); return; } // TODO: disable in menu if (!this.canEditFiles()) { this.displayCannotEditLibraryFilesMessage(); return; } var libraryID = itemGroup.ref.libraryID; var nsIFilePicker = Components.interfaces.nsIFilePicker; var fp = Components.classes["@mozilla.org/filepicker;1"] .createInstance(nsIFilePicker); fp.init(window, Zotero.getString('pane.item.attachments.select'), nsIFilePicker.modeOpenMultiple); fp.appendFilters(Components.interfaces.nsIFilePicker.filterAll); if(fp.show() == nsIFilePicker.returnOK) { var files = fp.files; while (files.hasMoreElements()){ var file = files.getNext(); file.QueryInterface(Components.interfaces.nsILocalFile); var attachmentID; if(link) attachmentID = Zotero.Attachments.linkFromFile(file, id); else attachmentID = Zotero.Attachments.importFromFile(file, id, libraryID); if(attachmentID && !id) { var c = this.getSelectedCollection(); if(c) c.addItem(attachmentID); } } } } this.addItemFromPage = function (itemType, saveSnapshot, row) { if (!this.canEdit(row)) { this.displayCannotEditLibraryMessage(); return; } return this.addItemFromDocument(window.content.document, itemType, saveSnapshot, row); } /** * @param {Document} doc * @param {String|Integer} [itemType='webpage'] Item type id or name * @param {Boolean} [saveSnapshot] Force saving or non-saving of a snapshot, * regardless of automaticSnapshots pref */ this.addItemFromDocument = function (doc, itemType, saveSnapshot, row) { var progressWin = new Zotero.ProgressWindow(); progressWin.changeHeadline(Zotero.getString('ingester.scraping')); var icon = 'chrome://zotero/skin/treeitem-webpage.png'; progressWin.addLines(doc.title, icon) progressWin.show(); progressWin.startCloseTimer(); // Save snapshot if explicitly enabled or automatically pref is set and not explicitly disabled saveSnapshot = saveSnapshot || (saveSnapshot !== false && Zotero.Prefs.get('automaticSnapshots')); // TODO: this, needless to say, is a temporary hack if (itemType == 'temporaryPDFHack') { itemType = null; var isPDF = false; if (doc.title.indexOf('application/pdf') != -1) { isPDF = true; } else { var ios = Components.classes["@mozilla.org/network/io-service;1"]. getService(Components.interfaces.nsIIOService); try { var uri = ios.newURI(doc.location, null, null); if (uri.fileName && uri.fileName.match(/pdf$/)) { isPDF = true; } } catch (e) { Zotero.debug(e); Components.utils.reportError(e); } } if (isPDF && saveSnapshot) { // // Duplicate newItem() checks here // if (!Zotero.stateCheck()) { this.displayErrorMessage(true); return false; } // Currently selected row if (row === undefined) { row = this.collectionsView.selection.currentIndex; } if (!this.canEdit(row)) { this.displayCannotEditLibraryMessage(); return; } if (row !== undefined) { var itemGroup = this.collectionsView._getItemAtRow(row); var libraryID = itemGroup.ref.libraryID; } else { var libraryID = null; var itemGroup = null; } // // // if (!this.canEditFiles(row)) { this.displayCannotEditLibraryFilesMessage(); return; } if (itemGroup && itemGroup.isCollection()) { var collectionID = itemGroup.ref.id; } else { var collectionID = false; } var itemID = Zotero.Attachments.importFromDocument(doc, false, false, collectionID, null, libraryID); // importFromDocument() doesn't trigger the notifier for a second // // The one-second delay is weird but better than nothing var self = this; setTimeout(function () { self.selectItem(itemID); }, 1001); return; } } // Save web page item by default if (!itemType) { itemType = 'webpage'; } var data = { title: doc.title, url: doc.location.href, accessDate: "CURRENT_TIMESTAMP" } itemType = Zotero.ItemTypes.getID(itemType); var item = this.newItem(itemType, data, row); if (item.libraryID) { var group = Zotero.Groups.getByLibraryID(item.libraryID); filesEditable = group.filesEditable; } else { filesEditable = true; } if (saveSnapshot) { var link = false; if (link) { Zotero.Attachments.linkFromDocument(doc, item.id); } else if (filesEditable) { Zotero.Attachments.importFromDocument(doc, item.id); } } return item.id; } this.addItemFromURL = function (url, itemType, saveSnapshot, row) { if (url == window.content.document.location.href) { return this.addItemFromPage(itemType, saveSnapshot, row); } var self = this; Zotero.MIME.getMIMETypeFromURL(url, function (mimeType, hasNativeHandler) { // If native type, save using a hidden browser if (hasNativeHandler) { var processor = function (doc) { ZoteroPane_Local.addItemFromDocument(doc, itemType, saveSnapshot, row); }; var done = function () {} var exception = function (e) { Zotero.debug(e); } Zotero.HTTP.processDocuments([url], processor, done, exception); } // Otherwise create placeholder item, attach attachment, and update from that else { // TODO: this, needless to say, is a temporary hack if (itemType == 'temporaryPDFHack') { itemType = null; if (mimeType == 'application/pdf') { // // Duplicate newItem() checks here // if (!Zotero.stateCheck()) { ZoteroPane_Local.displayErrorMessage(true); return false; } // Currently selected row if (row === undefined) { row = ZoteroPane_Local.collectionsView.selection.currentIndex; } if (!ZoteroPane_Local.canEdit(row)) { ZoteroPane_Local.displayCannotEditLibraryMessage(); return; } if (row !== undefined) { var itemGroup = ZoteroPane_Local.collectionsView._getItemAtRow(row); var libraryID = itemGroup.ref.libraryID; } else { var libraryID = null; var itemGroup = null; } // // // if (!ZoteroPane_Local.canEditFiles(row)) { ZoteroPane_Local.displayCannotEditLibraryFilesMessage(); return; } if (itemGroup && itemGroup.isCollection()) { var collectionID = itemGroup.ref.id; } else { var collectionID = false; } var attachmentItem = Zotero.Attachments.importFromURL(url, false, false, false, collectionID, mimeType, libraryID); // importFromURL() doesn't trigger the notifier until // after download is complete // // TODO: add a callback to importFromURL() setTimeout(function () { self.selectItem(attachmentItem.id); }, 1001); return; } } if (!itemType) { itemType = 'webpage'; } var item = ZoteroPane_Local.newItem(itemType, {}, row); if (item.libraryID) { var group = Zotero.Groups.getByLibraryID(item.libraryID); filesEditable = group.filesEditable; } else { filesEditable = true; } // Save snapshot if explicitly enabled or automatically pref is set and not explicitly disabled if (saveSnapshot || (saveSnapshot !== false && Zotero.Prefs.get('automaticSnapshots'))) { var link = false; if (link) { //Zotero.Attachments.linkFromURL(doc, item.id); } else if (filesEditable) { var attachmentItem = Zotero.Attachments.importFromURL(url, item.id, false, false, false, mimeType); if (attachmentItem) { item.setField('title', attachmentItem.getField('title')); item.setField('url', attachmentItem.getField('url')); item.setField('accessDate', attachmentItem.getField('accessDate')); item.save(); } } } return item.id; } }); } /* * Create an attachment from the current page * * |itemID| -- itemID of parent item * |link| -- create web link instead of snapshot */ this.addAttachmentFromPage = function (link, itemID) { if (!Zotero.stateCheck()) { this.displayErrorMessage(true); return; } if (typeof itemID != 'number') { throw ("itemID must be an integer in ZoteroPane_Local.addAttachmentFromPage()"); } var progressWin = new Zotero.ProgressWindow(); progressWin.changeHeadline(Zotero.getString('save.' + (link ? 'link' : 'attachment'))); var type = link ? 'web-link' : 'snapshot'; var icon = 'chrome://zotero/skin/treeitem-attachment-' + type + '.png'; progressWin.addLines(window.content.document.title, icon) progressWin.show(); progressWin.startCloseTimer(); if (link) { Zotero.Attachments.linkFromDocument(window.content.document, itemID); } else { Zotero.Attachments.importFromDocument(window.content.document, itemID); } } function viewAttachment(itemID, event, noLocateOnMissing, forceExternalViewer) { var attachment = Zotero.Items.get(itemID); if (!attachment.isAttachment()) { throw ("Item " + itemID + " is not an attachment in ZoteroPane_Local.viewAttachment()"); } if (attachment.attachmentLinkMode == Zotero.Attachments.LINK_MODE_LINKED_URL) { this.loadURI(attachment.getField('url'), event); return; } var file = attachment.getFile(); if (file) { if(forceExternalViewer !== undefined) { var externalViewer = forceExternalViewer; } else { var mimeType = attachment.attachmentMIMEType; // If no MIME type specified, try to detect again (I guess in case // we've gotten smarter since the file was imported?) if (!mimeType) { mimeType = Zotero.MIME.getMIMETypeFromFile(file); // TODO: update DB with new info } var ext = Zotero.File.getExtension(file); var externalViewer = Zotero.isStandalone || (!Zotero.MIME.hasNativeHandler(mimeType, ext) && (!Zotero.MIME.hasInternalHandler(mimeType, ext) || Zotero.Prefs.get('launchNonNativeFiles'))); } if (!externalViewer) { var url = 'zotero://attachment/' + itemID + '/'; this.loadURI(url, event, { attachmentID: itemID}); } else { // Some platforms don't have nsILocalFile.launch, so we just load it and // let the Firefox external helper app window handle it try { file.launch(); } catch (e) { Zotero.debug("launch() not supported -- passing file to loadURI()"); var fileURL = attachment.getLocalFileURL(); this.loadURI(fileURL); } } } else { this.showAttachmentNotFoundDialog(itemID, noLocateOnMissing); } } function viewSelectedAttachment(event, noLocateOnMissing) { if (this.itemsView && this.itemsView.selection.count == 1) { this.viewAttachment(this.getSelectedItems(true)[0], event, noLocateOnMissing); } } this.showAttachmentInFilesystem = function (itemID, noLocateOnMissing) { var attachment = Zotero.Items.get(itemID) if (attachment.attachmentLinkMode != Zotero.Attachments.LINK_MODE_LINKED_URL) { var file = attachment.getFile(); if (file){ try { file.reveal(); } catch (e) { // On platforms that don't support nsILocalFile.reveal() (e.g. Linux), // "double-click" the parent directory try { var parent = file.parent.QueryInterface(Components.interfaces.nsILocalFile); parent.launch(); } // If launch also fails, try the OS handler catch (e) { var uri = Components.classes["@mozilla.org/network/io-service;1"]. getService(Components.interfaces.nsIIOService). newFileURI(parent); var protocolService = Components.classes["@mozilla.org/uriloader/external-protocol-service;1"]. getService(Components.interfaces.nsIExternalProtocolService); protocolService.loadUrl(uri); } } } else { this.showAttachmentNotFoundDialog(attachment.id, noLocateOnMissing) } } } /** * Test if the user can edit the currently selected library/collection, * and display an error if not * * @param {Integer} [row] * * @return {Boolean} TRUE if user can edit, FALSE if not */ this.canEdit = function (row) { // Currently selected row if (row === undefined) { row = this.collectionsView.selection.currentIndex; } var itemGroup = this.collectionsView._getItemAtRow(row); return itemGroup.editable; } /** * Test if the user can edit the currently selected library/collection, * and display an error if not * * @param {Integer} [row] * * @return {Boolean} TRUE if user can edit, FALSE if not */ this.canEditFiles = function (row) { // Currently selected row if (row === undefined) { row = this.collectionsView.selection.currentIndex; } var itemGroup = this.collectionsView._getItemAtRow(row); return itemGroup.filesEditable; } this.displayCannotEditLibraryMessage = function () { var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); ps.alert(null, "", "You cannot make changes to the currently selected library."); } this.displayCannotEditLibraryFilesMessage = function () { var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); ps.alert(null, "", "You cannot add files to the currently selected library."); } function showAttachmentNotFoundDialog(itemID, noLocate) { var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]. createInstance(Components.interfaces.nsIPromptService); // Don't show Locate button if (noLocate) { var index = ps.alert(null, Zotero.getString('pane.item.attachments.fileNotFound.title'), Zotero.getString('pane.item.attachments.fileNotFound.text') ); return; } var buttonFlags = (ps.BUTTON_POS_0) * (ps.BUTTON_TITLE_IS_STRING) + (ps.BUTTON_POS_1) * (ps.BUTTON_TITLE_CANCEL); var index = ps.confirmEx(null, Zotero.getString('pane.item.attachments.fileNotFound.title'), Zotero.getString('pane.item.attachments.fileNotFound.text'), buttonFlags, Zotero.getString('general.locate'), null, null, null, {}); if (index == 0) { this.relinkAttachment(itemID); } } this.createParentItemsFromSelected = function () { if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } var items = this.getSelectedItems(); for (var i=0; i<items.length; i++) { var item = items[i]; if (!item.isTopLevelItem() || item.isRegularItem()) { throw('Item ' + itemID + ' is not a top-level attachment or note in ZoteroPane_Local.createParentItemsFromSelected()'); } Zotero.DB.beginTransaction(); // TODO: remove once there are no top-level web attachments if (item.isWebAttachment()) { var parent = new Zotero.Item('webpage'); } else { var parent = new Zotero.Item('document'); } parent.libraryID = item.libraryID; parent.setField('title', item.getField('title')); if (item.isWebAttachment()) { parent.setField('accessDate', item.getField('accessDate')); parent.setField('url', item.getField('url')); } var itemID = parent.save(); item.setSource(itemID); item.save(); Zotero.DB.commitTransaction(); } } this.renameSelectedAttachmentsFromParents = function () { if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } var items = this.getSelectedItems(); for (var i=0; i<items.length; i++) { var item = items[i]; if (!item.isAttachment() || !item.getSource() || item.attachmentLinkMode == Zotero.Attachments.LINK_MODE_LINKED_URL) { throw('Item ' + itemID + ' is not a child file attachment in ZoteroPane_Local.renameAttachmentFromParent()'); } var file = item.getFile(); if (!file) { continue; } var parentItemID = item.getSource(); var newName = Zotero.Attachments.getFileBaseNameFromItem(parentItemID); var ext = file.leafName.match(/[^\.]+$/); if (ext) { newName = newName + '.' + ext; } var renamed = item.renameAttachmentFile(newName); if (renamed !== true) { Zotero.debug("Could not rename file (" + renamed + ")"); continue; } item.setField('title', newName); item.save(); } return true; } function relinkAttachment(itemID) { if (!this.canEdit()) { this.displayCannotEditLibraryMessage(); return; } var item = Zotero.Items.get(itemID); if (!item) { throw('Item ' + itemID + ' not found in ZoteroPane_Local.relinkAttachment()'); } var nsIFilePicker = Components.interfaces.nsIFilePicker; var fp = Components.classes["@mozilla.org/filepicker;1"] .createInstance(nsIFilePicker); fp.init(window, Zotero.getString('pane.item.attachments.select'), nsIFilePicker.modeOpen); var file = item.getFile(false, true); var dir = Zotero.File.getClosestDirectory(file); if (dir) { dir.QueryInterface(Components.interfaces.nsILocalFile); fp.displayDirectory = dir; } fp.appendFilters(Components.interfaces.nsIFilePicker.filterAll); if (fp.show() == nsIFilePicker.returnOK) { var file = fp.file; file.QueryInterface(Components.interfaces.nsILocalFile); item.relinkAttachmentFile(file); } } function reportErrors() { var errors = Zotero.getErrors(true); var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"] .getService(Components.interfaces.nsIWindowWatcher); var data = { msg: Zotero.getString('errorReport.followingErrors', Zotero.appName), e: errors.join('\n\n'), askForSteps: true }; var io = { wrappedJSObject: { Zotero: Zotero, data: data } }; var win = ww.openWindow(null, "chrome://zotero/content/errorReport.xul", "zotero-error-report", "chrome,centerscreen,modal", io); } /* * Display an error message saying that an error has occurred and Firefox * needs to be restarted. * * If |popup| is TRUE, display in popup progress window; otherwise, display * as items pane message */ function displayErrorMessage(popup) { var reportErrorsStr = Zotero.getString('errorReport.reportErrors'); var reportInstructions = Zotero.getString('errorReport.reportInstructions', reportErrorsStr) // Display as popup progress window if (popup) { var pw = new Zotero.ProgressWindow(); pw.changeHeadline(Zotero.getString('general.errorHasOccurred')); var msg = Zotero.getString('general.restartFirefox') + ' ' + reportInstructions; pw.addDescription(msg); pw.show(); pw.startCloseTimer(8000); } // Display as items pane message else { var msg = Zotero.getString('general.errorHasOccurred') + ' ' + Zotero.getString('general.restartFirefox') + '\n\n' + reportInstructions; self.setItemsPaneMessage(msg, true); } Zotero.debug(msg, 1); } this.displayStartupError = function(asPaneMessage) { if(!Zotero || !Zotero.initialized) { if (Zotero) { var errMsg = Zotero.startupError; var errFunc = Zotero.startupErrorHandler; } if (!errMsg) { // Get the stringbundle manually var src = 'chrome://zotero/locale/zotero.properties'; var localeService = Components.classes['@mozilla.org/intl/nslocaleservice;1']. getService(Components.interfaces.nsILocaleService); var appLocale = localeService.getApplicationLocale(); var stringBundleService = Components.classes["@mozilla.org/intl/stringbundle;1"] .getService(Components.interfaces.nsIStringBundleService); var stringBundle = stringBundleService.createBundle(src, appLocale); var errMsg = stringBundle.GetStringFromName('startupError'); } if (errFunc) { errFunc(); } else { // TODO: Add a better error page/window here with reporting // instructions // window.loadURI('chrome://zotero/content/error.xul'); //if(asPaneMessage) { // ZoteroPane_Local.setItemsPaneMessage(errMsg, true); //} else { var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); ps.alert(null, "", errMsg); //} } } } /** * Toggles Zotero-as-a-tab by passing off the request to the ZoteroOverlay object associated * with the present window */ this.toggleTab = function() { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var browserWindow = wm.getMostRecentWindow("navigator:browser"); if(browserWindow.ZoteroOverlay) browserWindow.ZoteroOverlay.toggleTab(); } /** * Shows the Zotero pane, making it visible if it is not and switching to the appropriate tab * if necessary. */ this.show = function() { if(window.ZoteroOverlay) { if(ZoteroOverlay.isTab) { ZoteroOverlay.loadZoteroTab(); } else if(!this.isShowing()) { ZoteroOverlay.toggleDisplay(); } } } /** * Unserializes zotero-persist elements from preferences */ this.unserializePersist = function() { var serializedValues = Zotero.Prefs.get("pane.persist"); if(!serializedValues) return; serializedValues = JSON.parse(serializedValues); for(var id in serializedValues) { var el = document.getElementById(id); if(!el) return; var elValues = serializedValues[id]; for(var attr in elValues) { el.setAttribute(attr, elValues[attr]); } } if(this.itemsView) { // may not yet be initialized try { this.itemsView.sort(); } catch(e) {}; } } /** * Serializes zotero-persist elements to preferences */ this.serializePersist = function() { var serializedValues = {}; for each(var el in document.getElementsByAttribute("zotero-persist", "*")) { if(!el.getAttribute) continue; var id = el.getAttribute("id"); if(!id) continue; var elValues = {}; for each(var attr in el.getAttribute("zotero-persist").split(/[\s,]+/)) { var attrValue = el.getAttribute(attr); elValues[attr] = attrValue; } serializedValues[id] = elValues; } Zotero.Prefs.set("pane.persist", JSON.stringify(serializedValues)); } /** * Moves around the toolbar when the user moves around the pane */ this.updateToolbarPosition = function() { if(document.getElementById("zotero-pane-stack").hidden) return; const PANES = ["collections", "items"]; for each(var paneName in PANES) { var pane = document.getElementById("zotero-"+paneName+"-pane"); var splitter = document.getElementById("zotero-"+paneName+"-splitter"); var toolbar = document.getElementById("zotero-"+paneName+"-toolbar"); var paneComputedStyle = window.getComputedStyle(pane, null); var splitterComputedStyle = window.getComputedStyle(splitter, null); toolbar.style.width = paneComputedStyle.getPropertyValue("width"); toolbar.style.marginRight = splitterComputedStyle.getPropertyValue("width"); } } /** * Opens the about dialog */ this.openAboutDialog = function() { window.openDialog('chrome://zotero/content/about.xul', 'about', 'chrome'); } /** * Adds or removes a function to be called when Zotero is reloaded by switching into or out of * the connector */ this.addReloadListener = function(/** @param {Function} **/func) { if(_reloadFunctions.indexOf(func) === -1) _reloadFunctions.push(func); } /** * Called when Zotero is reloaded (i.e., if it is switched into or out of connector mode) */ function _reload() { Zotero.debug("Reloading Zotero pane"); for each(var func in _reloadFunctions) func(); } } /** * Keep track of which ZoteroPane was local (since ZoteroPane object might get swapped out for a * tab's ZoteroPane) */ var ZoteroPane_Local = ZoteroPane;
Fixes #1826, Quick Copy does not work in Standalone
chrome/content/zotero/zoteroPane.js
Fixes #1826, Quick Copy does not work in Standalone
<ide><path>hrome/content/zotero/zoteroPane.js <ide> return; <ide> } <ide> <del> var url = window.content.location.href; <add> var url = (window.content && window.content.location ? window.content.location.href : null); <ide> var [mode, format] = Zotero.QuickCopy.getFormatFromURL(url).split('='); <ide> var [mode, contentType] = mode.split('/'); <ide>
Java
epl-1.0
38ee40a33aa686a584c482239e5600fc96cf5a9e
0
mandeepdhami/controller,mandeepdhami/controller,Johnson-Chou/test,aryantaheri/monitoring-controller,my76128/controller,Sushma7785/OpenDayLight-Load-Balancer,inocybe/odl-controller,Johnson-Chou/test,my76128/controller,522986491/controller,mandeepdhami/controller,opendaylight/controller,inocybe/odl-controller,Sushma7785/OpenDayLight-Load-Balancer,tx1103mark/controller,522986491/controller,my76128/controller,aryantaheri/monitoring-controller,mandeepdhami/controller,aryantaheri/monitoring-controller,tx1103mark/controller,my76128/controller,tx1103mark/controller,aryantaheri/monitoring-controller,tx1103mark/controller
package org.opendaylight.controller.cluster.raft; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.PoisonPill; import akka.actor.Props; import akka.actor.Terminated; import akka.event.Logging; import akka.japi.Creator; import akka.persistence.RecoveryCompleted; import akka.persistence.SaveSnapshotSuccess; import akka.persistence.SnapshotMetadata; import akka.persistence.SnapshotOffer; import akka.testkit.JavaTestKit; import akka.testkit.TestActorRef; import com.google.common.base.Optional; import com.google.common.collect.Lists; import com.google.protobuf.ByteString; import org.junit.After; import org.junit.Test; import org.opendaylight.controller.cluster.DataPersistenceProvider; import org.opendaylight.controller.cluster.datastore.DataPersistenceProviderMonitor; import org.opendaylight.controller.cluster.raft.base.messages.ApplyLogEntries; import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot; import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply; import org.opendaylight.controller.cluster.raft.client.messages.FindLeader; import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply; import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload; import org.opendaylight.controller.cluster.raft.utils.MockAkkaJournal; import org.opendaylight.controller.cluster.raft.utils.MockSnapshotStore; import scala.concurrent.duration.FiniteDuration; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.mockito.Mockito.mock; public class RaftActorTest extends AbstractActorTest { @After public void tearDown() { MockAkkaJournal.clearJournal(); MockSnapshotStore.setMockSnapshot(null); } public static class MockRaftActor extends RaftActor { private final DataPersistenceProvider dataPersistenceProvider; public static final class MockRaftActorCreator implements Creator<MockRaftActor> { private final Map<String, String> peerAddresses; private final String id; private final Optional<ConfigParams> config; private final DataPersistenceProvider dataPersistenceProvider; private MockRaftActorCreator(Map<String, String> peerAddresses, String id, Optional<ConfigParams> config, DataPersistenceProvider dataPersistenceProvider) { this.peerAddresses = peerAddresses; this.id = id; this.config = config; this.dataPersistenceProvider = dataPersistenceProvider; } @Override public MockRaftActor create() throws Exception { return new MockRaftActor(id, peerAddresses, config, dataPersistenceProvider); } } private final CountDownLatch recoveryComplete = new CountDownLatch(1); private final CountDownLatch applyRecoverySnapshot = new CountDownLatch(1); private final CountDownLatch applyStateLatch = new CountDownLatch(1); private final List<Object> state; public MockRaftActor(String id, Map<String, String> peerAddresses, Optional<ConfigParams> config, DataPersistenceProvider dataPersistenceProvider) { super(id, peerAddresses, config); state = new ArrayList<>(); if(dataPersistenceProvider == null){ this.dataPersistenceProvider = new PersistentDataProvider(); } else { this.dataPersistenceProvider = dataPersistenceProvider; } } public void waitForRecoveryComplete() { try { assertEquals("Recovery complete", true, recoveryComplete.await(5, TimeUnit.SECONDS)); } catch (InterruptedException e) { e.printStackTrace(); } } public CountDownLatch getApplyRecoverySnapshotLatch(){ return applyRecoverySnapshot; } public List<Object> getState() { return state; } public static Props props(final String id, final Map<String, String> peerAddresses, Optional<ConfigParams> config){ return Props.create(new MockRaftActorCreator(peerAddresses, id, config, null)); } public static Props props(final String id, final Map<String, String> peerAddresses, Optional<ConfigParams> config, DataPersistenceProvider dataPersistenceProvider){ return Props.create(new MockRaftActorCreator(peerAddresses, id, config, dataPersistenceProvider)); } @Override protected void applyState(ActorRef clientActor, String identifier, Object data) { applyStateLatch.countDown(); } @Override protected void startLogRecoveryBatch(int maxBatchSize) { } @Override protected void appendRecoveredLogEntry(Payload data) { state.add(data); } @Override protected void applyCurrentLogRecoveryBatch() { } @Override protected void onRecoveryComplete() { recoveryComplete.countDown(); } @Override protected void applyRecoverySnapshot(ByteString snapshot) { applyRecoverySnapshot.countDown(); try { Object data = toObject(snapshot); System.out.println("!!!!!applyRecoverySnapshot: "+data); if (data instanceof List) { state.addAll((List) data); } } catch (Exception e) { e.printStackTrace(); } } @Override protected void createSnapshot() { } @Override protected void applySnapshot(ByteString snapshot) { } @Override protected void onStateChanged() { } @Override protected DataPersistenceProvider persistence() { return this.dataPersistenceProvider; } @Override public String persistenceId() { return this.getId(); } private Object toObject(ByteString bs) throws ClassNotFoundException, IOException { Object obj = null; ByteArrayInputStream bis = null; ObjectInputStream ois = null; try { bis = new ByteArrayInputStream(bs.toByteArray()); ois = new ObjectInputStream(bis); obj = ois.readObject(); } finally { if (bis != null) { bis.close(); } if (ois != null) { ois.close(); } } return obj; } public ReplicatedLog getReplicatedLog(){ return this.getRaftActorContext().getReplicatedLog(); } } private static class RaftActorTestKit extends JavaTestKit { private final ActorRef raftActor; public RaftActorTestKit(ActorSystem actorSystem, String actorName) { super(actorSystem); raftActor = this.getSystem().actorOf(MockRaftActor.props(actorName, Collections.EMPTY_MAP, Optional.<ConfigParams>absent()), actorName); } public boolean waitForStartup(){ // Wait for a specific log message to show up return new JavaTestKit.EventFilter<Boolean>(Logging.Info.class ) { @Override protected Boolean run() { return true; } }.from(raftActor.path().toString()) .message("Switching from behavior Candidate to Leader") .occurrences(1).exec(); } public void findLeader(final String expectedLeader){ raftActor.tell(new FindLeader(), getRef()); FindLeaderReply reply = expectMsgClass(duration("5 seconds"), FindLeaderReply.class); assertEquals("getLeaderActor", expectedLeader, reply.getLeaderActor()); } public ActorRef getRaftActor() { return raftActor; } } @Test public void testConstruction() { boolean started = new RaftActorTestKit(getSystem(), "testConstruction").waitForStartup(); assertEquals(true, started); } @Test public void testFindLeaderWhenLeaderIsSelf(){ RaftActorTestKit kit = new RaftActorTestKit(getSystem(), "testFindLeader"); kit.waitForStartup(); kit.findLeader(kit.getRaftActor().path().toString()); } @Test public void testRaftActorRecovery() throws Exception { new JavaTestKit(getSystem()) {{ String persistenceId = "follower10"; DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); // Set the heartbeat interval high to essentially disable election otherwise the test // may fail if the actor is switched to Leader and the commitIndex is set to the last // log entry. config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); ActorRef followerActor = getSystem().actorOf(MockRaftActor.props(persistenceId, Collections.EMPTY_MAP, Optional.<ConfigParams>of(config)), persistenceId); watch(followerActor); List<ReplicatedLogEntry> snapshotUnappliedEntries = new ArrayList<>(); ReplicatedLogEntry entry1 = new MockRaftActorContext.MockReplicatedLogEntry(1, 4, new MockRaftActorContext.MockPayload("E")); snapshotUnappliedEntries.add(entry1); int lastAppliedDuringSnapshotCapture = 3; int lastIndexDuringSnapshotCapture = 4; // 4 messages as part of snapshot, which are applied to state ByteString snapshotBytes = fromObject(Arrays.asList( new MockRaftActorContext.MockPayload("A"), new MockRaftActorContext.MockPayload("B"), new MockRaftActorContext.MockPayload("C"), new MockRaftActorContext.MockPayload("D"))); Snapshot snapshot = Snapshot.create(snapshotBytes.toByteArray(), snapshotUnappliedEntries, lastIndexDuringSnapshotCapture, 1 , lastAppliedDuringSnapshotCapture, 1); MockSnapshotStore.setMockSnapshot(snapshot); MockSnapshotStore.setPersistenceId(persistenceId); // add more entries after snapshot is taken List<ReplicatedLogEntry> entries = new ArrayList<>(); ReplicatedLogEntry entry2 = new MockRaftActorContext.MockReplicatedLogEntry(1, 5, new MockRaftActorContext.MockPayload("F")); ReplicatedLogEntry entry3 = new MockRaftActorContext.MockReplicatedLogEntry(1, 6, new MockRaftActorContext.MockPayload("G")); ReplicatedLogEntry entry4 = new MockRaftActorContext.MockReplicatedLogEntry(1, 7, new MockRaftActorContext.MockPayload("H")); entries.add(entry2); entries.add(entry3); entries.add(entry4); int lastAppliedToState = 5; int lastIndex = 7; MockAkkaJournal.addToJournal(5, entry2); // 2 entries are applied to state besides the 4 entries in snapshot MockAkkaJournal.addToJournal(6, new ApplyLogEntries(lastAppliedToState)); MockAkkaJournal.addToJournal(7, entry3); MockAkkaJournal.addToJournal(8, entry4); // kill the actor followerActor.tell(PoisonPill.getInstance(), null); expectMsgClass(duration("5 seconds"), Terminated.class); unwatch(followerActor); //reinstate the actor TestActorRef<MockRaftActor> ref = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, Collections.EMPTY_MAP, Optional.<ConfigParams>of(config))); ref.underlyingActor().waitForRecoveryComplete(); RaftActorContext context = ref.underlyingActor().getRaftActorContext(); assertEquals("Journal log size", snapshotUnappliedEntries.size() + entries.size(), context.getReplicatedLog().size()); assertEquals("Last index", lastIndex, context.getReplicatedLog().lastIndex()); assertEquals("Last applied", lastAppliedToState, context.getLastApplied()); assertEquals("Commit index", lastAppliedToState, context.getCommitIndex()); assertEquals("Recovered state size", 6, ref.underlyingActor().getState().size()); }}; } /** * This test verifies that when recovery is applicable (typically when persistence is true) the RaftActor does * process recovery messages * * @throws Exception */ @Test public void testHandleRecoveryWhenDataPersistenceRecoveryApplicable() throws Exception { new JavaTestKit(getSystem()) { { String persistenceId = "testHandleRecoveryWhenDataPersistenceRecoveryApplicable"; DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); TestActorRef<MockRaftActor> mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, Collections.EMPTY_MAP, Optional.<ConfigParams>of(config)), persistenceId); MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); // Wait for akka's recovery to complete so it doesn't interfere. mockRaftActor.waitForRecoveryComplete(); ByteString snapshotBytes = fromObject(Arrays.asList( new MockRaftActorContext.MockPayload("A"), new MockRaftActorContext.MockPayload("B"), new MockRaftActorContext.MockPayload("C"), new MockRaftActorContext.MockPayload("D"))); Snapshot snapshot = Snapshot.create(snapshotBytes.toByteArray(), Lists.<ReplicatedLogEntry>newArrayList(), 3, 1 ,3, 1); mockRaftActor.onReceiveRecover(new SnapshotOffer(new SnapshotMetadata(persistenceId, 100, 100), snapshot)); CountDownLatch applyRecoverySnapshotLatch = mockRaftActor.getApplyRecoverySnapshotLatch(); assertEquals("apply recovery snapshot", true, applyRecoverySnapshotLatch.await(5, TimeUnit.SECONDS)); mockRaftActor.onReceiveRecover(new ReplicatedLogImplEntry(0, 1, new MockRaftActorContext.MockPayload("A"))); ReplicatedLog replicatedLog = mockRaftActor.getReplicatedLog(); assertEquals("add replicated log entry", 1, replicatedLog.size()); mockRaftActor.onReceiveRecover(new ReplicatedLogImplEntry(1, 1, new MockRaftActorContext.MockPayload("A"))); assertEquals("add replicated log entry", 2, replicatedLog.size()); mockRaftActor.onReceiveRecover(new ApplyLogEntries(1)); assertEquals("commit index 1", 1, mockRaftActor.getRaftActorContext().getCommitIndex()); // The snapshot had 4 items + we added 2 more items during the test // We start removing from 5 and we should get 1 item in the replicated log mockRaftActor.onReceiveRecover(new RaftActor.DeleteEntries(5)); assertEquals("remove log entries", 1, replicatedLog.size()); mockRaftActor.onReceiveRecover(new RaftActor.UpdateElectionTerm(10, "foobar")); assertEquals("election term", 10, mockRaftActor.getRaftActorContext().getTermInformation().getCurrentTerm()); assertEquals("voted for", "foobar", mockRaftActor.getRaftActorContext().getTermInformation().getVotedFor()); mockRaftActor.onReceiveRecover(mock(RecoveryCompleted.class)); mockActorRef.tell(PoisonPill.getInstance(), getRef()); }}; } /** * This test verifies that when recovery is not applicable (typically when persistence is false) the RaftActor does * not process recovery messages * * @throws Exception */ @Test public void testHandleRecoveryWhenDataPersistenceRecoveryNotApplicable() throws Exception { new JavaTestKit(getSystem()) { { String persistenceId = "testHandleRecoveryWhenDataPersistenceRecoveryNotApplicable"; DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); TestActorRef<MockRaftActor> mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, Collections.EMPTY_MAP, Optional.<ConfigParams>of(config), new DataPersistenceProviderMonitor()), persistenceId); MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); // Wait for akka's recovery to complete so it doesn't interfere. mockRaftActor.waitForRecoveryComplete(); ByteString snapshotBytes = fromObject(Arrays.asList( new MockRaftActorContext.MockPayload("A"), new MockRaftActorContext.MockPayload("B"), new MockRaftActorContext.MockPayload("C"), new MockRaftActorContext.MockPayload("D"))); Snapshot snapshot = Snapshot.create(snapshotBytes.toByteArray(), Lists.<ReplicatedLogEntry>newArrayList(), 3, 1 ,3, 1); mockRaftActor.onReceiveRecover(new SnapshotOffer(new SnapshotMetadata(persistenceId, 100, 100), snapshot)); CountDownLatch applyRecoverySnapshotLatch = mockRaftActor.getApplyRecoverySnapshotLatch(); assertEquals("apply recovery snapshot", false, applyRecoverySnapshotLatch.await(1, TimeUnit.SECONDS)); mockRaftActor.onReceiveRecover(new ReplicatedLogImplEntry(0, 1, new MockRaftActorContext.MockPayload("A"))); ReplicatedLog replicatedLog = mockRaftActor.getReplicatedLog(); assertEquals("add replicated log entry", 0, replicatedLog.size()); mockRaftActor.onReceiveRecover(new ReplicatedLogImplEntry(1, 1, new MockRaftActorContext.MockPayload("A"))); assertEquals("add replicated log entry", 0, replicatedLog.size()); mockRaftActor.onReceiveRecover(new ApplyLogEntries(1)); assertEquals("commit index -1", -1, mockRaftActor.getRaftActorContext().getCommitIndex()); mockRaftActor.onReceiveRecover(new RaftActor.DeleteEntries(2)); assertEquals("remove log entries", 0, replicatedLog.size()); mockRaftActor.onReceiveRecover(new RaftActor.UpdateElectionTerm(10, "foobar")); assertNotEquals("election term", 10, mockRaftActor.getRaftActorContext().getTermInformation().getCurrentTerm()); assertNotEquals("voted for", "foobar", mockRaftActor.getRaftActorContext().getTermInformation().getVotedFor()); mockRaftActor.onReceiveRecover(mock(RecoveryCompleted.class)); mockActorRef.tell(PoisonPill.getInstance(), getRef()); }}; } @Test public void testUpdatingElectionTermCallsDataPersistence() throws Exception { new JavaTestKit(getSystem()) { { String persistenceId = "testUpdatingElectionTermCallsDataPersistence"; DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); CountDownLatch persistLatch = new CountDownLatch(1); DataPersistenceProviderMonitor dataPersistenceProviderMonitor = new DataPersistenceProviderMonitor(); dataPersistenceProviderMonitor.setPersistLatch(persistLatch); TestActorRef<MockRaftActor> mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, Collections.EMPTY_MAP, Optional.<ConfigParams>of(config), dataPersistenceProviderMonitor), persistenceId); MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); mockRaftActor.getRaftActorContext().getTermInformation().updateAndPersist(10, "foobar"); assertEquals("Persist called", true, persistLatch.await(5, TimeUnit.SECONDS)); mockActorRef.tell(PoisonPill.getInstance(), getRef()); } }; } @Test public void testAddingReplicatedLogEntryCallsDataPersistence() throws Exception { new JavaTestKit(getSystem()) { { String persistenceId = "testAddingReplicatedLogEntryCallsDataPersistence"; DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); CountDownLatch persistLatch = new CountDownLatch(1); DataPersistenceProviderMonitor dataPersistenceProviderMonitor = new DataPersistenceProviderMonitor(); dataPersistenceProviderMonitor.setPersistLatch(persistLatch); TestActorRef<MockRaftActor> mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, Collections.EMPTY_MAP, Optional.<ConfigParams>of(config), dataPersistenceProviderMonitor), persistenceId); MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); mockRaftActor.getRaftActorContext().getReplicatedLog().appendAndPersist(new MockRaftActorContext.MockReplicatedLogEntry(10, 10, mock(Payload.class))); assertEquals("Persist called", true, persistLatch.await(5, TimeUnit.SECONDS)); mockActorRef.tell(PoisonPill.getInstance(), getRef()); } }; } @Test public void testRemovingReplicatedLogEntryCallsDataPersistence() throws Exception { new JavaTestKit(getSystem()) { { String persistenceId = "testRemovingReplicatedLogEntryCallsDataPersistence"; DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); CountDownLatch persistLatch = new CountDownLatch(2); DataPersistenceProviderMonitor dataPersistenceProviderMonitor = new DataPersistenceProviderMonitor(); dataPersistenceProviderMonitor.setPersistLatch(persistLatch); TestActorRef<MockRaftActor> mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, Collections.EMPTY_MAP, Optional.<ConfigParams>of(config), dataPersistenceProviderMonitor), persistenceId); MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); mockRaftActor.getReplicatedLog().appendAndPersist(new MockRaftActorContext.MockReplicatedLogEntry(1, 0, mock(Payload.class))); mockRaftActor.getRaftActorContext().getReplicatedLog().removeFromAndPersist(0); assertEquals("Persist called", true, persistLatch.await(5, TimeUnit.SECONDS)); mockActorRef.tell(PoisonPill.getInstance(), getRef()); } }; } @Test public void testApplyLogEntriesCallsDataPersistence() throws Exception { new JavaTestKit(getSystem()) { { String persistenceId = "testApplyLogEntriesCallsDataPersistence"; DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); CountDownLatch persistLatch = new CountDownLatch(1); DataPersistenceProviderMonitor dataPersistenceProviderMonitor = new DataPersistenceProviderMonitor(); dataPersistenceProviderMonitor.setPersistLatch(persistLatch); TestActorRef<MockRaftActor> mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, Collections.EMPTY_MAP, Optional.<ConfigParams>of(config), dataPersistenceProviderMonitor), persistenceId); MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); mockRaftActor.onReceiveCommand(new ApplyLogEntries(10)); assertEquals("Persist called", true, persistLatch.await(5, TimeUnit.SECONDS)); mockActorRef.tell(PoisonPill.getInstance(), getRef()); } }; } @Test public void testCaptureSnapshotReplyCallsDataPersistence() throws Exception { new JavaTestKit(getSystem()) { { String persistenceId = "testCaptureSnapshotReplyCallsDataPersistence"; DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); CountDownLatch persistLatch = new CountDownLatch(1); DataPersistenceProviderMonitor dataPersistenceProviderMonitor = new DataPersistenceProviderMonitor(); dataPersistenceProviderMonitor.setSaveSnapshotLatch(persistLatch); TestActorRef<MockRaftActor> mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, Collections.EMPTY_MAP, Optional.<ConfigParams>of(config), dataPersistenceProviderMonitor), persistenceId); MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); ByteString snapshotBytes = fromObject(Arrays.asList( new MockRaftActorContext.MockPayload("A"), new MockRaftActorContext.MockPayload("B"), new MockRaftActorContext.MockPayload("C"), new MockRaftActorContext.MockPayload("D"))); mockRaftActor.onReceiveCommand(new CaptureSnapshot(-1,1,-1,1)); mockRaftActor.onReceiveCommand(new CaptureSnapshotReply(snapshotBytes)); assertEquals("Save Snapshot called", true, persistLatch.await(5, TimeUnit.SECONDS)); mockActorRef.tell(PoisonPill.getInstance(), getRef()); } }; } @Test public void testSaveSnapshotSuccessCallsDataPersistence() throws Exception { new JavaTestKit(getSystem()) { { String persistenceId = "testSaveSnapshotSuccessCallsDataPersistence"; DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); CountDownLatch deleteMessagesLatch = new CountDownLatch(1); CountDownLatch deleteSnapshotsLatch = new CountDownLatch(1); DataPersistenceProviderMonitor dataPersistenceProviderMonitor = new DataPersistenceProviderMonitor(); dataPersistenceProviderMonitor.setDeleteMessagesLatch(deleteMessagesLatch); dataPersistenceProviderMonitor.setDeleteSnapshotsLatch(deleteSnapshotsLatch); TestActorRef<MockRaftActor> mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, Collections.EMPTY_MAP, Optional.<ConfigParams>of(config), dataPersistenceProviderMonitor), persistenceId); MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); ByteString snapshotBytes = fromObject(Arrays.asList( new MockRaftActorContext.MockPayload("A"), new MockRaftActorContext.MockPayload("B"), new MockRaftActorContext.MockPayload("C"), new MockRaftActorContext.MockPayload("D"))); mockRaftActor.onReceiveCommand(new CaptureSnapshot(-1,1,-1,1)); mockRaftActor.onReceiveCommand(new CaptureSnapshotReply(snapshotBytes)); mockRaftActor.onReceiveCommand(new SaveSnapshotSuccess(new SnapshotMetadata("foo", 100, 100))); assertEquals("Delete Messages called", true, deleteMessagesLatch.await(5, TimeUnit.SECONDS)); assertEquals("Delete Snapshots called", true, deleteSnapshotsLatch.await(5, TimeUnit.SECONDS)); mockActorRef.tell(PoisonPill.getInstance(), getRef()); } }; } private ByteString fromObject(Object snapshot) throws Exception { ByteArrayOutputStream b = null; ObjectOutputStream o = null; try { b = new ByteArrayOutputStream(); o = new ObjectOutputStream(b); o.writeObject(snapshot); byte[] snapshotBytes = b.toByteArray(); return ByteString.copyFrom(snapshotBytes); } finally { if (o != null) { o.flush(); o.close(); } if (b != null) { b.close(); } } } }
opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/RaftActorTest.java
package org.opendaylight.controller.cluster.raft; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.PoisonPill; import akka.actor.Props; import akka.actor.Terminated; import akka.event.Logging; import akka.japi.Creator; import akka.persistence.RecoveryCompleted; import akka.persistence.SaveSnapshotSuccess; import akka.persistence.SnapshotMetadata; import akka.persistence.SnapshotOffer; import akka.testkit.JavaTestKit; import akka.testkit.TestActorRef; import com.google.common.base.Optional; import com.google.common.collect.Lists; import com.google.protobuf.ByteString; import org.junit.After; import org.junit.Test; import org.opendaylight.controller.cluster.DataPersistenceProvider; import org.opendaylight.controller.cluster.datastore.DataPersistenceProviderMonitor; import org.opendaylight.controller.cluster.raft.base.messages.ApplyLogEntries; import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot; import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply; import org.opendaylight.controller.cluster.raft.client.messages.FindLeader; import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply; import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload; import org.opendaylight.controller.cluster.raft.utils.MockAkkaJournal; import org.opendaylight.controller.cluster.raft.utils.MockSnapshotStore; import scala.concurrent.duration.FiniteDuration; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.mockito.Mockito.mock; public class RaftActorTest extends AbstractActorTest { @After public void tearDown() { MockAkkaJournal.clearJournal(); MockSnapshotStore.setMockSnapshot(null); } public static class MockRaftActor extends RaftActor { private final DataPersistenceProvider dataPersistenceProvider; public static final class MockRaftActorCreator implements Creator<MockRaftActor> { private final Map<String, String> peerAddresses; private final String id; private final Optional<ConfigParams> config; private final DataPersistenceProvider dataPersistenceProvider; private MockRaftActorCreator(Map<String, String> peerAddresses, String id, Optional<ConfigParams> config, DataPersistenceProvider dataPersistenceProvider) { this.peerAddresses = peerAddresses; this.id = id; this.config = config; this.dataPersistenceProvider = dataPersistenceProvider; } @Override public MockRaftActor create() throws Exception { return new MockRaftActor(id, peerAddresses, config, dataPersistenceProvider); } } private final CountDownLatch recoveryComplete = new CountDownLatch(1); private final CountDownLatch applyRecoverySnapshot = new CountDownLatch(1); private final CountDownLatch applyStateLatch = new CountDownLatch(1); private final List<Object> state; public MockRaftActor(String id, Map<String, String> peerAddresses, Optional<ConfigParams> config, DataPersistenceProvider dataPersistenceProvider) { super(id, peerAddresses, config); state = new ArrayList<>(); if(dataPersistenceProvider == null){ this.dataPersistenceProvider = new PersistentDataProvider(); } else { this.dataPersistenceProvider = dataPersistenceProvider; } } public void waitForRecoveryComplete() { try { assertEquals("Recovery complete", true, recoveryComplete.await(5, TimeUnit.SECONDS)); } catch (InterruptedException e) { e.printStackTrace(); } } public CountDownLatch getApplyRecoverySnapshotLatch(){ return applyRecoverySnapshot; } public List<Object> getState() { return state; } public static Props props(final String id, final Map<String, String> peerAddresses, Optional<ConfigParams> config){ return Props.create(new MockRaftActorCreator(peerAddresses, id, config, null)); } public static Props props(final String id, final Map<String, String> peerAddresses, Optional<ConfigParams> config, DataPersistenceProvider dataPersistenceProvider){ return Props.create(new MockRaftActorCreator(peerAddresses, id, config, dataPersistenceProvider)); } @Override protected void applyState(ActorRef clientActor, String identifier, Object data) { applyStateLatch.countDown(); } @Override protected void startLogRecoveryBatch(int maxBatchSize) { } @Override protected void appendRecoveredLogEntry(Payload data) { state.add(data); } @Override protected void applyCurrentLogRecoveryBatch() { } @Override protected void onRecoveryComplete() { recoveryComplete.countDown(); } @Override protected void applyRecoverySnapshot(ByteString snapshot) { applyRecoverySnapshot.countDown(); try { Object data = toObject(snapshot); System.out.println("!!!!!applyRecoverySnapshot: "+data); if (data instanceof List) { state.addAll((List) data); } } catch (Exception e) { e.printStackTrace(); } } @Override protected void createSnapshot() { } @Override protected void applySnapshot(ByteString snapshot) { } @Override protected void onStateChanged() { } @Override protected DataPersistenceProvider persistence() { return this.dataPersistenceProvider; } @Override public String persistenceId() { return this.getId(); } private Object toObject(ByteString bs) throws ClassNotFoundException, IOException { Object obj = null; ByteArrayInputStream bis = null; ObjectInputStream ois = null; try { bis = new ByteArrayInputStream(bs.toByteArray()); ois = new ObjectInputStream(bis); obj = ois.readObject(); } finally { if (bis != null) { bis.close(); } if (ois != null) { ois.close(); } } return obj; } public ReplicatedLog getReplicatedLog(){ return this.getRaftActorContext().getReplicatedLog(); } } private static class RaftActorTestKit extends JavaTestKit { private final ActorRef raftActor; public RaftActorTestKit(ActorSystem actorSystem, String actorName) { super(actorSystem); raftActor = this.getSystem().actorOf(MockRaftActor.props(actorName, Collections.EMPTY_MAP, Optional.<ConfigParams>absent()), actorName); } public boolean waitForStartup(){ // Wait for a specific log message to show up return new JavaTestKit.EventFilter<Boolean>(Logging.Info.class ) { @Override protected Boolean run() { return true; } }.from(raftActor.path().toString()) .message("Switching from behavior Candidate to Leader") .occurrences(1).exec(); } public void findLeader(final String expectedLeader){ raftActor.tell(new FindLeader(), getRef()); FindLeaderReply reply = expectMsgClass(duration("5 seconds"), FindLeaderReply.class); assertEquals("getLeaderActor", expectedLeader, reply.getLeaderActor()); } public ActorRef getRaftActor() { return raftActor; } } @Test public void testConstruction() { boolean started = new RaftActorTestKit(getSystem(), "testConstruction").waitForStartup(); assertEquals(true, started); } @Test public void testFindLeaderWhenLeaderIsSelf(){ RaftActorTestKit kit = new RaftActorTestKit(getSystem(), "testFindLeader"); kit.waitForStartup(); kit.findLeader(kit.getRaftActor().path().toString()); } @Test public void testRaftActorRecovery() throws Exception { new JavaTestKit(getSystem()) {{ String persistenceId = "follower10"; DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); // Set the heartbeat interval high to essentially disable election otherwise the test // may fail if the actor is switched to Leader and the commitIndex is set to the last // log entry. config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); ActorRef followerActor = getSystem().actorOf(MockRaftActor.props(persistenceId, Collections.EMPTY_MAP, Optional.<ConfigParams>of(config)), persistenceId); watch(followerActor); List<ReplicatedLogEntry> snapshotUnappliedEntries = new ArrayList<>(); ReplicatedLogEntry entry1 = new MockRaftActorContext.MockReplicatedLogEntry(1, 4, new MockRaftActorContext.MockPayload("E")); snapshotUnappliedEntries.add(entry1); int lastAppliedDuringSnapshotCapture = 3; int lastIndexDuringSnapshotCapture = 4; // 4 messages as part of snapshot, which are applied to state ByteString snapshotBytes = fromObject(Arrays.asList( new MockRaftActorContext.MockPayload("A"), new MockRaftActorContext.MockPayload("B"), new MockRaftActorContext.MockPayload("C"), new MockRaftActorContext.MockPayload("D"))); Snapshot snapshot = Snapshot.create(snapshotBytes.toByteArray(), snapshotUnappliedEntries, lastIndexDuringSnapshotCapture, 1 , lastAppliedDuringSnapshotCapture, 1); MockSnapshotStore.setMockSnapshot(snapshot); MockSnapshotStore.setPersistenceId(persistenceId); // add more entries after snapshot is taken List<ReplicatedLogEntry> entries = new ArrayList<>(); ReplicatedLogEntry entry2 = new MockRaftActorContext.MockReplicatedLogEntry(1, 5, new MockRaftActorContext.MockPayload("F")); ReplicatedLogEntry entry3 = new MockRaftActorContext.MockReplicatedLogEntry(1, 6, new MockRaftActorContext.MockPayload("G")); ReplicatedLogEntry entry4 = new MockRaftActorContext.MockReplicatedLogEntry(1, 7, new MockRaftActorContext.MockPayload("H")); entries.add(entry2); entries.add(entry3); entries.add(entry4); int lastAppliedToState = 5; int lastIndex = 7; MockAkkaJournal.addToJournal(5, entry2); // 2 entries are applied to state besides the 4 entries in snapshot MockAkkaJournal.addToJournal(6, new ApplyLogEntries(lastAppliedToState)); MockAkkaJournal.addToJournal(7, entry3); MockAkkaJournal.addToJournal(8, entry4); // kill the actor followerActor.tell(PoisonPill.getInstance(), null); expectMsgClass(duration("5 seconds"), Terminated.class); unwatch(followerActor); //reinstate the actor TestActorRef<MockRaftActor> ref = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, Collections.EMPTY_MAP, Optional.<ConfigParams>of(config))); ref.underlyingActor().waitForRecoveryComplete(); RaftActorContext context = ref.underlyingActor().getRaftActorContext(); assertEquals("Journal log size", snapshotUnappliedEntries.size() + entries.size(), context.getReplicatedLog().size()); assertEquals("Last index", lastIndex, context.getReplicatedLog().lastIndex()); assertEquals("Last applied", lastAppliedToState, context.getLastApplied()); assertEquals("Commit index", lastAppliedToState, context.getCommitIndex()); assertEquals("Recovered state size", 6, ref.underlyingActor().getState().size()); }}; } /** * This test verifies that when recovery is applicable (typically when persistence is true) the RaftActor does * process recovery messages * * @throws Exception */ @Test public void testHandleRecoveryWhenDataPersistenceRecoveryApplicable() throws Exception { new JavaTestKit(getSystem()) { { String persistenceId = "testHandleRecoveryWhenDataPersistenceRecoveryApplicable"; DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); TestActorRef<MockRaftActor> mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, Collections.EMPTY_MAP, Optional.<ConfigParams>of(config)), persistenceId); ByteString snapshotBytes = fromObject(Arrays.asList( new MockRaftActorContext.MockPayload("A"), new MockRaftActorContext.MockPayload("B"), new MockRaftActorContext.MockPayload("C"), new MockRaftActorContext.MockPayload("D"))); Snapshot snapshot = Snapshot.create(snapshotBytes.toByteArray(), Lists.<ReplicatedLogEntry>newArrayList(), 3, 1 ,3, 1); MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); mockRaftActor.onReceiveRecover(new SnapshotOffer(new SnapshotMetadata(persistenceId, 100, 100), snapshot)); CountDownLatch applyRecoverySnapshotLatch = mockRaftActor.getApplyRecoverySnapshotLatch(); assertEquals("apply recovery snapshot", true, applyRecoverySnapshotLatch.await(5, TimeUnit.SECONDS)); mockRaftActor.onReceiveRecover(new ReplicatedLogImplEntry(0, 1, new MockRaftActorContext.MockPayload("A"))); ReplicatedLog replicatedLog = mockRaftActor.getReplicatedLog(); assertEquals("add replicated log entry", 1, replicatedLog.size()); mockRaftActor.onReceiveRecover(new ReplicatedLogImplEntry(1, 1, new MockRaftActorContext.MockPayload("A"))); assertEquals("add replicated log entry", 2, replicatedLog.size()); mockRaftActor.onReceiveRecover(new ApplyLogEntries(1)); assertEquals("commit index 1", 1, mockRaftActor.getRaftActorContext().getCommitIndex()); // The snapshot had 4 items + we added 2 more items during the test // We start removing from 5 and we should get 1 item in the replicated log mockRaftActor.onReceiveRecover(new RaftActor.DeleteEntries(5)); assertEquals("remove log entries", 1, replicatedLog.size()); mockRaftActor.onReceiveRecover(new RaftActor.UpdateElectionTerm(10, "foobar")); assertEquals("election term", 10, mockRaftActor.getRaftActorContext().getTermInformation().getCurrentTerm()); assertEquals("voted for", "foobar", mockRaftActor.getRaftActorContext().getTermInformation().getVotedFor()); mockRaftActor.onReceiveRecover(mock(RecoveryCompleted.class)); mockRaftActor.waitForRecoveryComplete(); mockActorRef.tell(PoisonPill.getInstance(), getRef()); }}; } /** * This test verifies that when recovery is not applicable (typically when persistence is false) the RaftActor does * not process recovery messages * * @throws Exception */ @Test public void testHandleRecoveryWhenDataPersistenceRecoveryNotApplicable() throws Exception { new JavaTestKit(getSystem()) { { String persistenceId = "testHandleRecoveryWhenDataPersistenceRecoveryNotApplicable"; DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); TestActorRef<MockRaftActor> mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, Collections.EMPTY_MAP, Optional.<ConfigParams>of(config), new DataPersistenceProviderMonitor()), persistenceId); MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); ByteString snapshotBytes = fromObject(Arrays.asList( new MockRaftActorContext.MockPayload("A"), new MockRaftActorContext.MockPayload("B"), new MockRaftActorContext.MockPayload("C"), new MockRaftActorContext.MockPayload("D"))); Snapshot snapshot = Snapshot.create(snapshotBytes.toByteArray(), Lists.<ReplicatedLogEntry>newArrayList(), 3, 1 ,3, 1); mockRaftActor.onReceiveRecover(new SnapshotOffer(new SnapshotMetadata(persistenceId, 100, 100), snapshot)); CountDownLatch applyRecoverySnapshotLatch = mockRaftActor.getApplyRecoverySnapshotLatch(); assertEquals("apply recovery snapshot", false, applyRecoverySnapshotLatch.await(1, TimeUnit.SECONDS)); mockRaftActor.onReceiveRecover(new ReplicatedLogImplEntry(0, 1, new MockRaftActorContext.MockPayload("A"))); ReplicatedLog replicatedLog = mockRaftActor.getReplicatedLog(); assertEquals("add replicated log entry", 0, replicatedLog.size()); mockRaftActor.onReceiveRecover(new ReplicatedLogImplEntry(1, 1, new MockRaftActorContext.MockPayload("A"))); assertEquals("add replicated log entry", 0, replicatedLog.size()); mockRaftActor.onReceiveRecover(new ApplyLogEntries(1)); assertEquals("commit index -1", -1, mockRaftActor.getRaftActorContext().getCommitIndex()); mockRaftActor.onReceiveRecover(new RaftActor.DeleteEntries(2)); assertEquals("remove log entries", 0, replicatedLog.size()); mockRaftActor.onReceiveRecover(new RaftActor.UpdateElectionTerm(10, "foobar")); assertNotEquals("election term", 10, mockRaftActor.getRaftActorContext().getTermInformation().getCurrentTerm()); assertNotEquals("voted for", "foobar", mockRaftActor.getRaftActorContext().getTermInformation().getVotedFor()); mockRaftActor.onReceiveRecover(mock(RecoveryCompleted.class)); mockRaftActor.waitForRecoveryComplete(); mockActorRef.tell(PoisonPill.getInstance(), getRef()); }}; } @Test public void testUpdatingElectionTermCallsDataPersistence() throws Exception { new JavaTestKit(getSystem()) { { String persistenceId = "testUpdatingElectionTermCallsDataPersistence"; DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); CountDownLatch persistLatch = new CountDownLatch(1); DataPersistenceProviderMonitor dataPersistenceProviderMonitor = new DataPersistenceProviderMonitor(); dataPersistenceProviderMonitor.setPersistLatch(persistLatch); TestActorRef<MockRaftActor> mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, Collections.EMPTY_MAP, Optional.<ConfigParams>of(config), dataPersistenceProviderMonitor), persistenceId); MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); mockRaftActor.getRaftActorContext().getTermInformation().updateAndPersist(10, "foobar"); assertEquals("Persist called", true, persistLatch.await(5, TimeUnit.SECONDS)); mockActorRef.tell(PoisonPill.getInstance(), getRef()); } }; } @Test public void testAddingReplicatedLogEntryCallsDataPersistence() throws Exception { new JavaTestKit(getSystem()) { { String persistenceId = "testAddingReplicatedLogEntryCallsDataPersistence"; DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); CountDownLatch persistLatch = new CountDownLatch(1); DataPersistenceProviderMonitor dataPersistenceProviderMonitor = new DataPersistenceProviderMonitor(); dataPersistenceProviderMonitor.setPersistLatch(persistLatch); TestActorRef<MockRaftActor> mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, Collections.EMPTY_MAP, Optional.<ConfigParams>of(config), dataPersistenceProviderMonitor), persistenceId); MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); mockRaftActor.getRaftActorContext().getReplicatedLog().appendAndPersist(new MockRaftActorContext.MockReplicatedLogEntry(10, 10, mock(Payload.class))); assertEquals("Persist called", true, persistLatch.await(5, TimeUnit.SECONDS)); mockActorRef.tell(PoisonPill.getInstance(), getRef()); } }; } @Test public void testRemovingReplicatedLogEntryCallsDataPersistence() throws Exception { new JavaTestKit(getSystem()) { { String persistenceId = "testRemovingReplicatedLogEntryCallsDataPersistence"; DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); CountDownLatch persistLatch = new CountDownLatch(2); DataPersistenceProviderMonitor dataPersistenceProviderMonitor = new DataPersistenceProviderMonitor(); dataPersistenceProviderMonitor.setPersistLatch(persistLatch); TestActorRef<MockRaftActor> mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, Collections.EMPTY_MAP, Optional.<ConfigParams>of(config), dataPersistenceProviderMonitor), persistenceId); MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); mockRaftActor.getReplicatedLog().appendAndPersist(new MockRaftActorContext.MockReplicatedLogEntry(1, 0, mock(Payload.class))); mockRaftActor.getRaftActorContext().getReplicatedLog().removeFromAndPersist(0); assertEquals("Persist called", true, persistLatch.await(5, TimeUnit.SECONDS)); mockActorRef.tell(PoisonPill.getInstance(), getRef()); } }; } @Test public void testApplyLogEntriesCallsDataPersistence() throws Exception { new JavaTestKit(getSystem()) { { String persistenceId = "testApplyLogEntriesCallsDataPersistence"; DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); CountDownLatch persistLatch = new CountDownLatch(1); DataPersistenceProviderMonitor dataPersistenceProviderMonitor = new DataPersistenceProviderMonitor(); dataPersistenceProviderMonitor.setPersistLatch(persistLatch); TestActorRef<MockRaftActor> mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, Collections.EMPTY_MAP, Optional.<ConfigParams>of(config), dataPersistenceProviderMonitor), persistenceId); MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); mockRaftActor.onReceiveCommand(new ApplyLogEntries(10)); assertEquals("Persist called", true, persistLatch.await(5, TimeUnit.SECONDS)); mockActorRef.tell(PoisonPill.getInstance(), getRef()); } }; } @Test public void testCaptureSnapshotReplyCallsDataPersistence() throws Exception { new JavaTestKit(getSystem()) { { String persistenceId = "testCaptureSnapshotReplyCallsDataPersistence"; DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); CountDownLatch persistLatch = new CountDownLatch(1); DataPersistenceProviderMonitor dataPersistenceProviderMonitor = new DataPersistenceProviderMonitor(); dataPersistenceProviderMonitor.setSaveSnapshotLatch(persistLatch); TestActorRef<MockRaftActor> mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, Collections.EMPTY_MAP, Optional.<ConfigParams>of(config), dataPersistenceProviderMonitor), persistenceId); MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); ByteString snapshotBytes = fromObject(Arrays.asList( new MockRaftActorContext.MockPayload("A"), new MockRaftActorContext.MockPayload("B"), new MockRaftActorContext.MockPayload("C"), new MockRaftActorContext.MockPayload("D"))); mockRaftActor.onReceiveCommand(new CaptureSnapshot(-1,1,-1,1)); mockRaftActor.onReceiveCommand(new CaptureSnapshotReply(snapshotBytes)); assertEquals("Save Snapshot called", true, persistLatch.await(5, TimeUnit.SECONDS)); mockActorRef.tell(PoisonPill.getInstance(), getRef()); } }; } @Test public void testSaveSnapshotSuccessCallsDataPersistence() throws Exception { new JavaTestKit(getSystem()) { { String persistenceId = "testSaveSnapshotSuccessCallsDataPersistence"; DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); CountDownLatch deleteMessagesLatch = new CountDownLatch(1); CountDownLatch deleteSnapshotsLatch = new CountDownLatch(1); DataPersistenceProviderMonitor dataPersistenceProviderMonitor = new DataPersistenceProviderMonitor(); dataPersistenceProviderMonitor.setDeleteMessagesLatch(deleteMessagesLatch); dataPersistenceProviderMonitor.setDeleteSnapshotsLatch(deleteSnapshotsLatch); TestActorRef<MockRaftActor> mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, Collections.EMPTY_MAP, Optional.<ConfigParams>of(config), dataPersistenceProviderMonitor), persistenceId); MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); ByteString snapshotBytes = fromObject(Arrays.asList( new MockRaftActorContext.MockPayload("A"), new MockRaftActorContext.MockPayload("B"), new MockRaftActorContext.MockPayload("C"), new MockRaftActorContext.MockPayload("D"))); mockRaftActor.onReceiveCommand(new CaptureSnapshot(-1,1,-1,1)); mockRaftActor.onReceiveCommand(new CaptureSnapshotReply(snapshotBytes)); mockRaftActor.onReceiveCommand(new SaveSnapshotSuccess(new SnapshotMetadata("foo", 100, 100))); assertEquals("Delete Messages called", true, deleteMessagesLatch.await(5, TimeUnit.SECONDS)); assertEquals("Delete Snapshots called", true, deleteSnapshotsLatch.await(5, TimeUnit.SECONDS)); mockActorRef.tell(PoisonPill.getInstance(), getRef()); } }; } private ByteString fromObject(Object snapshot) throws Exception { ByteArrayOutputStream b = null; ObjectOutputStream o = null; try { b = new ByteArrayOutputStream(); o = new ObjectOutputStream(b); o.writeObject(snapshot); byte[] snapshotBytes = b.toByteArray(); return ByteString.copyFrom(snapshotBytes); } finally { if (o != null) { o.flush(); o.close(); } if (b != null) { b.close(); } } } }
Bug 2134: Fix intermittent RaftActorTest failure We need to wait for akka's recovery to complete before we perform our tests as akka's recovery runs async and may interfere with our tests and cause them to fail if the timing is right. This was seen once on jenkins. Change-Id: Ia748d17f662d64235881005e6522441b384c78ea Signed-off-by: tpantelis <[email protected]>
opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/RaftActorTest.java
Bug 2134: Fix intermittent RaftActorTest failure
<ide><path>pendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/RaftActorTest.java <ide> TestActorRef<MockRaftActor> mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, <ide> Collections.EMPTY_MAP, Optional.<ConfigParams>of(config)), persistenceId); <ide> <add> MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); <add> <add> // Wait for akka's recovery to complete so it doesn't interfere. <add> mockRaftActor.waitForRecoveryComplete(); <add> <ide> ByteString snapshotBytes = fromObject(Arrays.asList( <ide> new MockRaftActorContext.MockPayload("A"), <ide> new MockRaftActorContext.MockPayload("B"), <ide> Snapshot snapshot = Snapshot.create(snapshotBytes.toByteArray(), <ide> Lists.<ReplicatedLogEntry>newArrayList(), 3, 1 ,3, 1); <ide> <del> MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); <del> <ide> mockRaftActor.onReceiveRecover(new SnapshotOffer(new SnapshotMetadata(persistenceId, 100, 100), snapshot)); <ide> <ide> CountDownLatch applyRecoverySnapshotLatch = mockRaftActor.getApplyRecoverySnapshotLatch(); <ide> assertEquals("voted for", "foobar", mockRaftActor.getRaftActorContext().getTermInformation().getVotedFor()); <ide> <ide> mockRaftActor.onReceiveRecover(mock(RecoveryCompleted.class)); <del> <del> mockRaftActor.waitForRecoveryComplete(); <ide> <ide> mockActorRef.tell(PoisonPill.getInstance(), getRef()); <ide> <ide> <ide> MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); <ide> <add> // Wait for akka's recovery to complete so it doesn't interfere. <add> mockRaftActor.waitForRecoveryComplete(); <add> <ide> ByteString snapshotBytes = fromObject(Arrays.asList( <ide> new MockRaftActorContext.MockPayload("A"), <ide> new MockRaftActorContext.MockPayload("B"), <ide> assertNotEquals("voted for", "foobar", mockRaftActor.getRaftActorContext().getTermInformation().getVotedFor()); <ide> <ide> mockRaftActor.onReceiveRecover(mock(RecoveryCompleted.class)); <del> <del> mockRaftActor.waitForRecoveryComplete(); <ide> <ide> mockActorRef.tell(PoisonPill.getInstance(), getRef()); <ide> }};
Java
apache-2.0
3d69f72fdcb3bf2775f622c7da28e79490fe571c
0
sajithar/carbon-uuf-maven-plugin,this/carbon-uuf-maven-tools,this/carbon-uuf-maven-tools,this/carbon-uuf-maven-tools
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.uuf.maven.bean; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.regex.Pattern; /** * Bean class that represents the app's config file of an UUF App. * * @since 1.0.0 */ public class AppConfig { private static final Pattern HTTP_STATUS_CODES_PATTERN = Pattern.compile("[1-9][0-9][0-9]"); private String contextPath; private String theme; private String loginPageUri; private Map<String, String> errorPages = Collections.emptyMap(); private Map<String, List<MenuItem>> menus = Collections.emptyMap(); private SecurityConfig security = new SecurityConfig(); /** * Returns the client-side context path in this app's config. * * @return client-side context path in this app's config. */ public String getContextPath() { return contextPath; } /** * Sets the client-side context path in this app's config. * * @param contextPath client-side context path to be set * @throws IllegalArgumentException if {@code contextPath} is empty or doesn't start with a '/'. */ public void setContextPath(String contextPath) { if (contextPath != null) { if (contextPath.isEmpty()) { throw new IllegalArgumentException( "Context path configured with 'contextPath' key in the app's config cannot be empty."); } else if (contextPath.charAt(0) != '/') { throw new IllegalArgumentException( "Context path configured with 'contextPath' key in the app's config must start with a '/'. " + "Instead found '" + contextPath.charAt(0) + "' at the beginning."); } } this.contextPath = contextPath; } /** * Returns the theme name in this app's config. * * @return theme name in this app's config */ public String getTheme() { return theme; } /** * Sets the theme name in this app's config. * * @param theme theme name to be set * @throws IllegalArgumentException if {@code theme} is an empty string */ public void setTheme(String theme) { if (theme != null) { if (theme.isEmpty()) { throw new IllegalArgumentException( "Theme name configured with 'theme' key in the app's config cannot be empty."); } } this.theme = theme; } /** * Returns the login page URI in this app's config. * * @return URI of the login page in this app's config */ public String getLoginPageUri() { return loginPageUri; } /** * Sets the login page URI in this app's config. * * @param loginPageUri URI of the login page to be set * @throws IllegalArgumentException if {@code loginPageUri} is empty or doesn't start with a '/'. */ public void setLoginPageUri(String loginPageUri) { if (loginPageUri != null) { if (loginPageUri.isEmpty()) { throw new IllegalArgumentException( "Login page URI configured with 'loginPageUri' key in the app's config cannot be empty."); } if (loginPageUri.charAt(0) != '/') { throw new IllegalArgumentException( "Login page URI configured with 'loginPageUri' key in the app's config must start with a '/'." + " Instead found '" + loginPageUri.charAt(0) + "' at the beginning."); } } this.loginPageUri = loginPageUri; } /** * Returns the error pages URIs in this app's config. * * @return URIs of error pages in this app's config */ public Map<String, String> getErrorPages() { return errorPages; } /** * Sets the error pages URIs in this app's config. * * @param errorPages URIs of error pages to be set * @throws IllegalArgumentException if an error page URI is empty or doesn't start with a '/'. */ public void setErrorPages(Map<String, String> errorPages) { if (errorPages == null) { this.errorPages = Collections.emptyMap(); } else { for (Map.Entry<String, String> entry : errorPages.entrySet()) { String httpStatusCode = entry.getKey(); String errorPageUri = entry.getValue(); if (!httpStatusCode.equals("default") && !HTTP_STATUS_CODES_PATTERN.matcher(httpStatusCode).matches()) { throw new IllegalArgumentException( "HTTP status code of an error page entry in the app's config must be between 100 and 999." + " Instead found '" + httpStatusCode + "' for URI '" + errorPageUri + "'."); } if (errorPageUri.isEmpty()) { throw new IllegalArgumentException( "URI of an error page entry in the app's config cannot be empty. " + "Found an empty URI for HTTP status code '" + httpStatusCode + "'."); } else if (errorPageUri.charAt(0) != '/') { throw new IllegalArgumentException( "URI of an error page entry in the app's config must start with a '/'. Instead found '" + errorPageUri.charAt(0) + "' at the beginning of the URI for HTTP status code '" + httpStatusCode + "'."); } } this.errorPages = errorPages; } } /** * Returns the menus in this app's config. * * @return menus in this app's config */ public Map<String, List<MenuItem>> getMenus() { return menus; } /** * Sets the menus in this app's config. * * @param menus menus to be set */ public void setMenus(Map<String, List<MenuItem>> menus) { this.menus = (menus == null) ? Collections.emptyMap() : menus; } /** * Returns the security related configurations in this app's config. * * @return security related configurations in this app's config */ public SecurityConfig getSecurity() { return security; } /** * Sets the security related configurations in this app's config. * * @param security security configs to be set */ public void setSecurity(SecurityConfig security) { this.security = (security == null) ? new SecurityConfig() : security; } /** * Bean class that represents a menu item in the app's config file of an UUF App. * * @since 1.0.0 */ public static class MenuItem { private String text; private String link; private String icon; private List<MenuItem> submenus; /** * Returns the text of this menu item. * * @return text of this menu item */ public String getText() { return text; } /** * Sets the text of this menu item. * * @param text text to be set */ public void setText(String text) { this.text = text; } /** * Returns the link of this menu item. * * @return link of this menu item. */ public String getLink() { return link; } /** * Sets the link of this menu item. * * @param link link to be set */ public void setLink(String link) { this.link = link; } /** * Returns the icon CSS class of this menu item. * * @return icon CSS class of this menu item */ public String getIcon() { return icon; } /** * Sets the icon CSS class of this menu item. * * @param icon icon CSS class to be set */ public void setIcon(String icon) { this.icon = icon; } /** * Returns the sub-menus of this menu item. * * @return sub-menus of this menu item */ public List<MenuItem> getSubmenus() { return submenus; } /** * Sets the sub-menus of this menu item. * * @param submenus sub-menus to be set */ public void setSubmenus(List<MenuItem> submenus) { this.submenus = (submenus == null) ? Collections.emptyList() : submenus; } } /** * Bean class that represents security related configurations in the app's config file of an UUF App. * * @since 1.0.0 */ public static class SecurityConfig { private PatternsConfig csrfPatterns = new PatternsConfig(); private PatternsConfig xssPatterns = new PatternsConfig(); private Map<String, String> responseHeaders = Collections.emptyMap(); /** * Returns CSRF URI patterns of this security configuration. * * @return CSRF URI patterns */ public PatternsConfig getCsrfPatterns() { return csrfPatterns; } /** * Sets the CSRF URI patterns of this security configuration. * * @param csrfPatterns CSRF URI patterns to be set */ public void setCsrfPatterns(PatternsConfig csrfPatterns) { this.csrfPatterns = (csrfPatterns == null) ? new PatternsConfig() : csrfPatterns; } /** * Returns XSS URI patterns of this security configuration. * * @return XSS URI patterns */ public PatternsConfig getXssPatterns() { return xssPatterns; } /** * Sets the XSS URI patterns of this security configuration. * * @param xssPatterns XSS URI patterns to be set */ public void setXssPatterns(PatternsConfig xssPatterns) { this.xssPatterns = (xssPatterns == null) ? new PatternsConfig() : xssPatterns; } /** * Returns HTTP response headers of this security configuration. * * @return HTTP response headers */ public Map<String, String> getResponseHeaders() { return responseHeaders; } /** * Sets the HTTP response headers of this security configuration. * * @param responseHeaders HTTP response headers to be set */ public void setResponseHeaders(Map<String, String> responseHeaders) { this.responseHeaders = (responseHeaders == null) ? Collections.emptyMap() : responseHeaders; } } /** * Bean class that represents security related URI patterns configurations in the app's config file of an UUF App. * * @since 1.0.0 */ public static class PatternsConfig { private List<String> accept = Collections.emptyList(); private List<String> reject = Collections.emptyList(); /** * Returns allowing URI patterns of this URI pattern configuration. * * @return allowing URI patterns */ public List<String> getAccept() { return accept; } /** * Sets the allowing URI patterns of this URI pattern configuration. * * @param accept allowing URI patterns to be set */ public void setAccept(List<String> accept) { if (accept == null) { this.accept = Collections.emptyList(); } else { for (String uriPattern : accept) { if (uriPattern.isEmpty()) { throw new IllegalArgumentException("Accepting URI pattern cannot be empty."); } // TODO: 12/29/16 Check whether uriPattern is a valid pattern. } this.accept = accept; } } /** * Returns denying URI patterns of this URI pattern configuration. * * @return denying URI patterns */ public List<String> getReject() { return reject; } /** * Sets the denying URI patterns of this URI pattern configuration. * * @param reject denying URI patterns to be set */ public void setReject(List<String> reject) { if (reject == null) { this.reject = Collections.emptyList(); } else { for (String uriPattern : reject) { if (uriPattern.isEmpty()) { throw new IllegalArgumentException("Rejecting URI pattern cannot be empty."); } // TODO: 12/29/16 Check whether uriPattern is a valid pattern. } this.reject = reject; } } } }
plugin/src/main/java/org/wso2/carbon/uuf/maven/bean/AppConfig.java
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.uuf.maven.bean; import java.util.List; import java.util.Map; import java.util.regex.Pattern; /** * Bean class that represents the app's config file of an UUF App. * * @since 1.0.0 */ public class AppConfig { private static final Pattern HTTP_STATUS_CODES_PATTERN = Pattern.compile("[1-9][0-9][0-9]"); private String contextPath; private String theme; private String loginPageUri; private Map<String, String> errorPages; private Map<String, List<MenuItem>> menus; private SecurityConfig security; /** * Returns the client-side context path in this app's config. * * @return client-side context path in this app's config. */ public String getContextPath() { return contextPath; } /** * Sets the client-side context path in this app's config. * * @param contextPath client-side context path to be set * @throws IllegalArgumentException if {@code contextPath} is empty or doesn't start with a '/'. */ public void setContextPath(String contextPath) { if (contextPath != null) { if (contextPath.isEmpty()) { throw new IllegalArgumentException( "Context path configured with 'contextPath' key in the app's config cannot be empty."); } else if (contextPath.charAt(0) != '/') { throw new IllegalArgumentException( "Context path configured with 'contextPath' key in the app's config must start with a '/'. " + "Instead found '" + contextPath.charAt(0) + "' at the beginning."); } } this.contextPath = contextPath; } /** * Returns the theme name in this app's config. * * @return theme name in this app's config */ public String getTheme() { return theme; } /** * Sets the theme name in this app's config. * * @param theme theme name to be set * @throws IllegalArgumentException if {@code theme} is an empty string */ public void setTheme(String theme) { if (theme != null) { if (theme.isEmpty()) { throw new IllegalArgumentException( "Theme name configured with 'theme' key in the app's config cannot be empty."); } } this.theme = theme; } /** * Returns the login page URI in this app's config. * * @return URI of the login page in this app's config */ public String getLoginPageUri() { return loginPageUri; } /** * Sets the login page URI in this app's config. * * @param loginPageUri URI of the login page to be set * @throws IllegalArgumentException if {@code loginPageUri} is empty or doesn't start with a '/'. */ public void setLoginPageUri(String loginPageUri) { if (loginPageUri != null) { if (loginPageUri.isEmpty()) { throw new IllegalArgumentException( "Login page URI configured with 'loginPageUri' key in the app's config cannot be empty."); } if (loginPageUri.charAt(0) != '/') { throw new IllegalArgumentException( "Login page URI configured with 'loginPageUri' key in the app's config must start with a '/'." + " Instead found '" + loginPageUri.charAt(0) + "' at the beginning."); } } this.loginPageUri = loginPageUri; } /** * Returns the error pages URIs in this app's config. * * @return URIs of error pages in this app's config */ public Map<String, String> getErrorPages() { return errorPages; } /** * Sets the error pages URIs in this app's config. * * @param errorPages URIs of error pages to be set * @throws IllegalArgumentException if an error page URI is empty or doesn't start with a '/'. */ public void setErrorPages(Map<String, String> errorPages) { if (errorPages != null) { for (Map.Entry<String, String> entry : errorPages.entrySet()) { String httpStatusCode = entry.getKey(); String errorPageUri = entry.getValue(); if (!httpStatusCode.equals("default") && !HTTP_STATUS_CODES_PATTERN.matcher(httpStatusCode).matches()) { throw new IllegalArgumentException( "HTTP status code of an error page entry in the app's config must be between 100 and 999." + " Instead found '" + httpStatusCode + "' for URI '" + errorPageUri + "'."); } if (errorPageUri.isEmpty()) { throw new IllegalArgumentException( "URI of an error page entry in the app's config cannot be empty. " + "Found an empty URI for HTTP status code '" + httpStatusCode + "'."); } else if (errorPageUri.charAt(0) != '/') { throw new IllegalArgumentException( "URI of an error page entry in the app's config must start with a '/'. Instead found '" + errorPageUri.charAt(0) + "' at the beginning of the URI for HTTP status code '" + httpStatusCode + "'."); } } } this.errorPages = errorPages; } /** * Returns the menus in this app's config. * * @return menus in this app's config */ public Map<String, List<MenuItem>> getMenus() { return menus; } /** * Sets the menus in this app's config. * * @param menus menus to be set */ public void setMenus(Map<String, List<MenuItem>> menus) { this.menus = menus; } /** * Returns the security related configurations in this app's config. * * @return security related configurations in this app's config */ public SecurityConfig getSecurity() { return security; } /** * Sets the security related configurations in this app's config. * * @param security security configs to be set */ public void setSecurity(SecurityConfig security) { this.security = security; } /** * Bean class that represents a menu item in the app's config file of an UUF App. * * @since 1.0.0 */ public static class MenuItem { private String text; private String link; private String icon; private List<MenuItem> submenus; /** * Returns the text of this menu item. * * @return text of this menu item */ public String getText() { return text; } /** * Sets the text of this menu item. * * @param text text to be set */ public void setText(String text) { this.text = text; } /** * Returns the link of this menu item. * * @return link of this menu item. */ public String getLink() { return link; } /** * Sets the link of this menu item. * * @param link link to be set */ public void setLink(String link) { this.link = link; } /** * Returns the icon CSS class of this menu item. * * @return icon CSS class of this menu item */ public String getIcon() { return icon; } /** * Sets the icon CSS class of this menu item. * * @param icon icon CSS class to be set */ public void setIcon(String icon) { this.icon = icon; } /** * Returns the sub-menus of this menu item. * * @return sub-menus of this menu item */ public List<MenuItem> getSubmenus() { return submenus; } /** * Sets the sub-menus of this menu item. * * @param submenus sub-menus to be set */ public void setSubmenus(List<MenuItem> submenus) { this.submenus = submenus; } } /** * Bean class that represents security related configurations in the app's config file of an UUF App. * * @since 1.0.0 */ public static class SecurityConfig { private PatternsConfig csrfPatterns; private PatternsConfig xssPatterns; private Map<String, String> responseHeaders; /** * Returns CSRF URI patterns of this security configuration. * * @return CSRF URI patterns */ public PatternsConfig getCsrfPatterns() { return csrfPatterns; } /** * Sets the CSRF URI patterns of this security configuration. * * @param csrfPatterns CSRF URI patterns to be set */ public void setCsrfPatterns(PatternsConfig csrfPatterns) { this.csrfPatterns = csrfPatterns; } /** * Returns XSS URI patterns of this security configuration. * * @return XSS URI patterns */ public PatternsConfig getXssPatterns() { return xssPatterns; } /** * Sets the XSS URI patterns of this security configuration. * * @param xssPatterns XSS URI patterns to be set */ public void setXssPatterns(PatternsConfig xssPatterns) { this.xssPatterns = xssPatterns; } /** * Returns HTTP response headers of this security configuration. * * @return HTTP response headers */ public Map<String, String> getResponseHeaders() { return responseHeaders; } /** * Sets the HTTP response headers of this security configuration. * * @param responseHeaders HTTP response headers to be set */ public void setResponseHeaders(Map<String, String> responseHeaders) { this.responseHeaders = responseHeaders; } } /** * Bean class that represents security related URI patterns configurations in the app's config file of an UUF App. * * @since 1.0.0 */ public static class PatternsConfig { private List<String> accept; private List<String> reject; /** * Returns allowing URI patterns of this URI pattern configuration. * * @return allowing URI patterns */ public List<String> getAccept() { return accept; } /** * Sets the allowing URI patterns of this URI pattern configuration. * * @param accept allowing URI patterns to be set */ public void setAccept(List<String> accept) { if (accept != null) { for (String uriPattern : accept) { if (uriPattern.isEmpty()) { throw new IllegalArgumentException("Accepting URI pattern cannot be empty."); } // TODO: 12/29/16 Check whether uriPattern is a valid pattern. } } this.accept = accept; } /** * Returns denying URI patterns of this URI pattern configuration. * * @return denying URI patterns */ public List<String> getReject() { return reject; } /** * Sets the denying URI patterns of this URI pattern configuration. * * @param reject denying URI patterns to be set */ public void setReject(List<String> reject) { if (reject != null) { for (String uriPattern : reject) { if (uriPattern.isEmpty()) { throw new IllegalArgumentException("Rejecting URI pattern cannot be empty."); } // TODO: 12/29/16 Check whether uriPattern is a valid pattern. } } this.reject = reject; } } }
added default values where necessary in AppConfig bean class
plugin/src/main/java/org/wso2/carbon/uuf/maven/bean/AppConfig.java
added default values where necessary in AppConfig bean class
<ide><path>lugin/src/main/java/org/wso2/carbon/uuf/maven/bean/AppConfig.java <ide> <ide> package org.wso2.carbon.uuf.maven.bean; <ide> <add>import java.util.Collections; <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.regex.Pattern; <ide> private String contextPath; <ide> private String theme; <ide> private String loginPageUri; <del> private Map<String, String> errorPages; <del> private Map<String, List<MenuItem>> menus; <del> private SecurityConfig security; <add> private Map<String, String> errorPages = Collections.emptyMap(); <add> private Map<String, List<MenuItem>> menus = Collections.emptyMap(); <add> private SecurityConfig security = new SecurityConfig(); <ide> <ide> /** <ide> * Returns the client-side context path in this app's config. <ide> * @throws IllegalArgumentException if an error page URI is empty or doesn't start with a '/'. <ide> */ <ide> public void setErrorPages(Map<String, String> errorPages) { <del> if (errorPages != null) { <add> if (errorPages == null) { <add> this.errorPages = Collections.emptyMap(); <add> } else { <ide> for (Map.Entry<String, String> entry : errorPages.entrySet()) { <ide> String httpStatusCode = entry.getKey(); <ide> String errorPageUri = entry.getValue(); <ide> httpStatusCode + "'."); <ide> } <ide> } <del> } <del> this.errorPages = errorPages; <add> this.errorPages = errorPages; <add> } <ide> } <ide> <ide> /** <ide> * @param menus menus to be set <ide> */ <ide> public void setMenus(Map<String, List<MenuItem>> menus) { <del> this.menus = menus; <add> this.menus = (menus == null) ? Collections.emptyMap() : menus; <ide> } <ide> <ide> /** <ide> * @param security security configs to be set <ide> */ <ide> public void setSecurity(SecurityConfig security) { <del> this.security = security; <add> this.security = (security == null) ? new SecurityConfig() : security; <ide> } <ide> <ide> /** <ide> * @param submenus sub-menus to be set <ide> */ <ide> public void setSubmenus(List<MenuItem> submenus) { <del> this.submenus = submenus; <add> this.submenus = (submenus == null) ? Collections.emptyList() : submenus; <ide> } <ide> } <ide> <ide> */ <ide> public static class SecurityConfig { <ide> <del> private PatternsConfig csrfPatterns; <del> private PatternsConfig xssPatterns; <del> private Map<String, String> responseHeaders; <add> private PatternsConfig csrfPatterns = new PatternsConfig(); <add> private PatternsConfig xssPatterns = new PatternsConfig(); <add> private Map<String, String> responseHeaders = Collections.emptyMap(); <ide> <ide> /** <ide> * Returns CSRF URI patterns of this security configuration. <ide> * @param csrfPatterns CSRF URI patterns to be set <ide> */ <ide> public void setCsrfPatterns(PatternsConfig csrfPatterns) { <del> this.csrfPatterns = csrfPatterns; <add> this.csrfPatterns = (csrfPatterns == null) ? new PatternsConfig() : csrfPatterns; <ide> } <ide> <ide> /** <ide> * @param xssPatterns XSS URI patterns to be set <ide> */ <ide> public void setXssPatterns(PatternsConfig xssPatterns) { <del> this.xssPatterns = xssPatterns; <add> this.xssPatterns = (xssPatterns == null) ? new PatternsConfig() : xssPatterns; <ide> } <ide> <ide> /** <ide> * @param responseHeaders HTTP response headers to be set <ide> */ <ide> public void setResponseHeaders(Map<String, String> responseHeaders) { <del> this.responseHeaders = responseHeaders; <add> this.responseHeaders = (responseHeaders == null) ? Collections.emptyMap() : responseHeaders; <ide> } <ide> } <ide> <ide> */ <ide> public static class PatternsConfig { <ide> <del> private List<String> accept; <del> private List<String> reject; <add> private List<String> accept = Collections.emptyList(); <add> private List<String> reject = Collections.emptyList(); <ide> <ide> /** <ide> * Returns allowing URI patterns of this URI pattern configuration. <ide> * @param accept allowing URI patterns to be set <ide> */ <ide> public void setAccept(List<String> accept) { <del> if (accept != null) { <add> if (accept == null) { <add> this.accept = Collections.emptyList(); <add> } else { <ide> for (String uriPattern : accept) { <ide> if (uriPattern.isEmpty()) { <ide> throw new IllegalArgumentException("Accepting URI pattern cannot be empty."); <ide> } <ide> // TODO: 12/29/16 Check whether uriPattern is a valid pattern. <ide> } <del> } <del> this.accept = accept; <add> this.accept = accept; <add> } <ide> } <ide> <ide> /** <ide> * @param reject denying URI patterns to be set <ide> */ <ide> public void setReject(List<String> reject) { <del> if (reject != null) { <add> if (reject == null) { <add> this.reject = Collections.emptyList(); <add> } else { <ide> for (String uriPattern : reject) { <ide> if (uriPattern.isEmpty()) { <ide> throw new IllegalArgumentException("Rejecting URI pattern cannot be empty."); <ide> } <ide> // TODO: 12/29/16 Check whether uriPattern is a valid pattern. <ide> } <del> } <del> this.reject = reject; <add> this.reject = reject; <add> } <ide> } <ide> } <ide> }
Java
apache-2.0
3e03ec9abcaa4637e4c4e40917b94ee0346dc782
0
facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho
/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.litho.widget; import android.graphics.Color; import android.support.annotation.IdRes; import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView.ItemAnimator; import android.view.View; import com.facebook.litho.ComponentContext; import com.facebook.litho.ComponentLayout; import com.facebook.litho.Diff; import com.facebook.litho.EventHandler; import com.facebook.litho.Output; import com.facebook.litho.Size; import com.facebook.litho.annotations.FromBind; import com.facebook.litho.annotations.FromPrepare; import com.facebook.litho.annotations.MountSpec; import com.facebook.litho.annotations.OnBind; import com.facebook.litho.annotations.OnBoundsDefined; import com.facebook.litho.annotations.OnCreateMountContent; import com.facebook.litho.annotations.OnMeasure; import com.facebook.litho.annotations.OnMount; import com.facebook.litho.annotations.OnPrepare; import com.facebook.litho.annotations.OnUnbind; import com.facebook.litho.annotations.OnUnmount; import com.facebook.litho.annotations.Prop; import com.facebook.litho.annotations.PropDefault; import com.facebook.litho.annotations.ResType; import com.facebook.litho.annotations.ShouldUpdate; @MountSpec(canMountIncrementally = true, isPureRender = true, events = {PTRRefreshEvent.class}) class RecyclerSpec { @PropDefault static final int scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY; @PropDefault static final boolean hasFixedSize = true; @PropDefault static final boolean nestedScrollingEnabled = true; @PropDefault static final ItemAnimator itemAnimator = new NoUpdateItemAnimator(); @PropDefault static final int recyclerViewId = View.NO_ID; @PropDefault static final int refreshProgressBarColor = Color.BLACK; @OnMeasure static void onMeasure( ComponentContext context, ComponentLayout layout, int widthSpec, int heightSpec, Size measureOutput, @Prop Binder<RecyclerView> binder) { binder.measure(measureOutput, widthSpec, heightSpec); } @OnBoundsDefined static void onBoundsDefined( ComponentContext context, ComponentLayout layout, @Prop Binder<RecyclerView> binder) { binder.setSize( layout.getWidth(), layout.getHeight()); } @OnCreateMountContent static RecyclerViewWrapper onCreateMountContent(ComponentContext c) { return new RecyclerViewWrapper(c, new RecyclerView(c)); } @OnPrepare static void onPrepare( ComponentContext c, @Prop(optional = true) final EventHandler refreshHandler, Output<OnRefreshListener> onRefreshListener) { if (refreshHandler != null) { onRefreshListener.set(new OnRefreshListener() { @Override public void onRefresh() { Recycler.dispatchPTRRefreshEvent(refreshHandler); } }); } } @OnMount static void onMount( ComponentContext c, RecyclerViewWrapper recyclerViewWrapper, @Prop Binder<RecyclerView> binder, @Prop(optional = true) boolean hasFixedSize, @Prop(optional = true) boolean clipToPadding, @Prop(optional = true) boolean nestedScrollingEnabled, @Prop(optional = true) int scrollBarStyle, @Prop(optional = true) RecyclerView.ItemDecoration itemDecoration, @Prop(optional = true, resType = ResType.COLOR) int refreshProgressBarColor, @Prop(optional = true) @IdRes int recyclerViewId) { final RecyclerView recyclerView = recyclerViewWrapper.getRecyclerView(); if (recyclerView == null) { throw new IllegalStateException( "RecyclerView not found, it should not be removed from SwipeRefreshLayout"); } recyclerViewWrapper.setColorSchemeColors(refreshProgressBarColor); recyclerView.setHasFixedSize(hasFixedSize); recyclerView.setClipToPadding(clipToPadding); recyclerView.setNestedScrollingEnabled(nestedScrollingEnabled); recyclerViewWrapper.setNestedScrollingEnabled(nestedScrollingEnabled); recyclerView.setScrollBarStyle(scrollBarStyle); // TODO (t14949498) determine if this is necessary recyclerView.setId(recyclerViewId); if (itemDecoration != null) { recyclerView.addItemDecoration(itemDecoration); } binder.mount(recyclerView); } @OnBind protected static void onBind( ComponentContext context, RecyclerViewWrapper recyclerViewWrapper, @Prop(optional = true) ItemAnimator itemAnimator, @Prop Binder<RecyclerView> binder, @Prop(optional = true) final RecyclerEventsController recyclerEventsController, @Prop(optional = true) RecyclerView.OnScrollListener onScrollListener, @FromPrepare OnRefreshListener onRefreshListener, Output<ItemAnimator> oldAnimator) { recyclerViewWrapper.setEnabled(onRefreshListener != null); recyclerViewWrapper.setOnRefreshListener(onRefreshListener); final RecyclerView recyclerView = recyclerViewWrapper.getRecyclerView(); if (recyclerView == null) { throw new IllegalStateException( "RecyclerView not found, it should not be removed from SwipeRefreshLayout " + "before unmounting"); } oldAnimator.set(recyclerView.getItemAnimator()); if (itemAnimator != RecyclerSpec.itemAnimator) { recyclerView.setItemAnimator(itemAnimator); } else { recyclerView.setItemAnimator(new NoUpdateItemAnimator()); } if (onScrollListener != null) { recyclerView.addOnScrollListener(onScrollListener); } binder.bind(recyclerView); if (recyclerEventsController != null) { recyclerEventsController.setRecyclerViewWrapper(recyclerViewWrapper); } if (recyclerViewWrapper.hasBeenDetachedFromWindow()) { recyclerView.requestLayout(); recyclerViewWrapper.setHasBeenDetachedFromWindow(false); } } @OnUnbind static void onUnbind( ComponentContext context, RecyclerViewWrapper recyclerViewWrapper, @Prop Binder<RecyclerView> binder, @Prop(optional = true) RecyclerEventsController recyclerEventsController, @Prop(optional = true) RecyclerView.OnScrollListener onScrollListener, @FromBind ItemAnimator oldAnimator) { final RecyclerView recyclerView = recyclerViewWrapper.getRecyclerView(); if (recyclerView == null) { throw new IllegalStateException( "RecyclerView not found, it should not be removed from SwipeRefreshLayout " + "before unmounting"); } recyclerView.setItemAnimator(oldAnimator); binder.unbind(recyclerView); if (recyclerEventsController != null) { recyclerEventsController.setRecyclerViewWrapper(null); } if (onScrollListener != null) { recyclerView.removeOnScrollListener(onScrollListener); } recyclerViewWrapper.setOnRefreshListener(null); } @OnUnmount static void onUnmount( ComponentContext context, RecyclerViewWrapper recyclerViewWrapper, @Prop Binder<RecyclerView> binder, @Prop(optional = true) RecyclerView.ItemDecoration itemDecoration) { final RecyclerView recyclerView = recyclerViewWrapper.getRecyclerView(); if (recyclerView == null) { throw new IllegalStateException( "RecyclerView not found, it should not be removed from SwipeRefreshLayout " + "before unmounting"); } recyclerView.setId(RecyclerSpec.recyclerViewId); if (itemDecoration != null) { recyclerView.removeItemDecoration(itemDecoration); } binder.unmount(recyclerView);
litho-widget/src/main/java/com/facebook/litho/widget/RecyclerSpec.java
/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.litho.widget; import android.graphics.Color; import android.support.annotation.IdRes; import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView.ItemAnimator; import android.view.View; import com.facebook.litho.ComponentContext; import com.facebook.litho.ComponentLayout; import com.facebook.litho.Diff; import com.facebook.litho.EventHandler; import com.facebook.litho.Output; import com.facebook.litho.Size; import com.facebook.litho.annotations.FromBind; import com.facebook.litho.annotations.FromPrepare; import com.facebook.litho.annotations.MountSpec; import com.facebook.litho.annotations.OnBind; import com.facebook.litho.annotations.OnBoundsDefined; import com.facebook.litho.annotations.OnCreateMountContent; import com.facebook.litho.annotations.OnMeasure; import com.facebook.litho.annotations.OnMount; import com.facebook.litho.annotations.OnPrepare; import com.facebook.litho.annotations.OnUnbind; import com.facebook.litho.annotations.OnUnmount; import com.facebook.litho.annotations.Prop; import com.facebook.litho.annotations.PropDefault; import com.facebook.litho.annotations.ResType; import com.facebook.litho.annotations.ShouldUpdate; @MountSpec(canMountIncrementally = true, isPureRender = true, events = {PTRRefreshEvent.class}) class RecyclerSpec { @PropDefault static final int scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY; @PropDefault static final boolean hasFixedSize = true; @PropDefault static final boolean nestedScrollingEnabled = true; @PropDefault static final ItemAnimator itemAnimator = new NoUpdateItemAnimator(); @PropDefault static final int recyclerViewId = View.NO_ID; @PropDefault static final int refreshProgressBarColor = Color.BLACK; @OnMeasure static void onMeasure( ComponentContext context, ComponentLayout layout, int widthSpec, int heightSpec, Size measureOutput, @Prop Binder<RecyclerView> binder) { binder.measure(measureOutput, widthSpec, heightSpec); } @OnBoundsDefined static void onBoundsDefined( ComponentContext context, ComponentLayout layout, @Prop Binder<RecyclerView> binder) { binder.setSize( layout.getWidth(), layout.getHeight()); } @OnCreateMountContent static RecyclerViewWrapper onCreateMountContent(ComponentContext c) { return new RecyclerViewWrapper(c, new RecyclerView(c)); } @OnPrepare static void onPrepare( ComponentContext c, @Prop(optional = true) final EventHandler refreshHandler, Output<OnRefreshListener> onRefreshListener) { if (refreshHandler != null) { onRefreshListener.set(new OnRefreshListener() { @Override public void onRefresh() { Recycler.dispatchPTRRefreshEvent(refreshHandler); } }); } } @OnMount static void onMount( ComponentContext c, RecyclerViewWrapper recyclerViewWrapper, @Prop Binder<RecyclerView> binder, @Prop(optional = true) boolean hasFixedSize, @Prop(optional = true) boolean clipToPadding, @Prop(optional = true) boolean nestedScrollingEnabled, @Prop(optional = true) int scrollBarStyle, @Prop(optional = true) RecyclerView.ItemDecoration itemDecoration, @Prop(optional = true, resType = ResType.COLOR) int refreshProgressBarColor, @Prop(optional = true) @IdRes int recyclerViewId) { final RecyclerView recyclerView = recyclerViewWrapper.getRecyclerView(); if (recyclerView == null) { throw new IllegalStateException( "RecyclerView not found, it should not be removed from SwipeRefreshLayout"); } recyclerViewWrapper.setColorSchemeColors(refreshProgressBarColor); recyclerView.setHasFixedSize(hasFixedSize); recyclerView.setClipToPadding(clipToPadding); recyclerView.setNestedScrollingEnabled(nestedScrollingEnabled); recyclerViewWrapper.setNestedScrollingEnabled(nestedScrollingEnabled); recyclerView.setScrollBarStyle(scrollBarStyle); // TODO (t14949498) determine if this is necessary recyclerView.setId(recyclerViewId); if (itemDecoration != null) { recyclerView.addItemDecoration(itemDecoration); } binder.mount(recyclerView); } @OnBind protected static void onBind( ComponentContext context, RecyclerViewWrapper recyclerViewWrapper, @Prop(optional = true) ItemAnimator itemAnimator, @Prop Binder<RecyclerView> binder, @Prop(optional = true) final RecyclerEventsController recyclerEventsController, @Prop(optional = true) RecyclerView.OnScrollListener onScrollListener, @FromPrepare OnRefreshListener onRefreshListener, Output<ItemAnimator> oldAnimator) { recyclerViewWrapper.setEnabled(onRefreshListener != null); recyclerViewWrapper.setOnRefreshListener(onRefreshListener); final RecyclerView recyclerView = recyclerViewWrapper.getRecyclerView(); if (recyclerView == null) { throw new IllegalStateException( "RecyclerView not found, it should not be removed from SwipeRefreshLayout " + "before unmounting"); } oldAnimator.set(recyclerView.getItemAnimator()); if (itemAnimator != RecyclerSpec.itemAnimator) { recyclerView.setItemAnimator(itemAnimator); } else { recyclerView.setItemAnimator(new NoUpdateItemAnimator()); } if (onScrollListener != null) { recyclerView.addOnScrollListener(onScrollListener); } binder.bind(recyclerView); if (recyclerEventsController != null) { recyclerEventsController.setRecyclerViewWrapper(recyclerViewWrapper); } if (recyclerViewWrapper.hasBeenDetachedFromWindow()) { recyclerView.requestLayout(); recyclerViewWrapper.setHasBeenDetachedFromWindow(false); } } @OnUnbind static void onUnbind( ComponentContext context, RecyclerViewWrapper recyclerViewWrapper, @Prop Binder<RecyclerView> binder, @Prop(optional = true) RecyclerEventsController recyclerEventsController, @Prop(optional = true) RecyclerView.OnScrollListener onScrollListener, @FromBind ItemAnimator oldAnimator) { final RecyclerView recyclerView = recyclerViewWrapper.getRecyclerView(); if (recyclerView == null) { throw new IllegalStateException( "RecyclerView not found, it should not be removed from SwipeRefreshLayout " + "before unmounting"); } recyclerView.setItemAnimator(oldAnimator); binder.unbind(recyclerView); if (recyclerEventsController != null) { recyclerEventsController.setRecyclerViewWrapper(null); } if (onScrollListener != null) { recyclerView.removeOnScrollListener(onScrollListener); } recyclerViewWrapper.setOnRefreshListener(null); } @OnUnmount static void onUnmount( ComponentContext context, RecyclerViewWrapper recyclerViewWrapper, @Prop Binder<RecyclerView> binder, @Prop(optional = true) RecyclerView.ItemDecoration itemDecoration) { final RecyclerView recyclerView = recyclerViewWrapper.getRecyclerView(); if (recyclerView == null) { throw new IllegalStateException( "RecyclerView not found, it should not be removed from SwipeRefreshLayout " + "before unmounting"); } recyclerView.setId(RecyclerSpec.recyclerViewId); if (itemDecoration != null) { recyclerView.removeItemDecoration(itemDecoration); }
Lines authored by mihaelao This commit forms part of the blame-preserving initial commit suite.
litho-widget/src/main/java/com/facebook/litho/widget/RecyclerSpec.java
Lines authored by mihaelao
<ide><path>itho-widget/src/main/java/com/facebook/litho/widget/RecyclerSpec.java <ide> recyclerView.removeItemDecoration(itemDecoration); <ide> } <ide> <add> binder.unmount(recyclerView);
Java
mit
error: pathspec 'src/main/java/dtprogrammer/github/io/algo/InsertionSort.java' did not match any file(s) known to git
1e106fd7c4cb31bf4126978c247502a41b840b6d
1
dtprogrammer/leetcode-solutions
package dtprogrammer.github.io.algo; import java.util.Arrays; public class InsertionSort { public static void sort(Comparable[] data) { for (int i = 0; i < data.length; i++) { for (int j = i; j > 0; j--) { if (data[j].compareTo(data[j - 1]) < 0) { Comparable temp = data[j - 1]; data[j - 1] = data[j]; data[j] = temp; } } } } public static void main(String[] args) { Integer[] data = new Integer[]{23, 56, 33, 0, 9, 56, 87}; InsertionSort.sort(data); System.out.println(Arrays.toString(data)); } }
src/main/java/dtprogrammer/github/io/algo/InsertionSort.java
Insertion Sort
src/main/java/dtprogrammer/github/io/algo/InsertionSort.java
Insertion Sort
<ide><path>rc/main/java/dtprogrammer/github/io/algo/InsertionSort.java <add>package dtprogrammer.github.io.algo; <add> <add>import java.util.Arrays; <add> <add>public class InsertionSort { <add> <add> public static void sort(Comparable[] data) { <add> for (int i = 0; i < data.length; i++) { <add> for (int j = i; j > 0; j--) { <add> if (data[j].compareTo(data[j - 1]) < 0) { <add> Comparable temp = data[j - 1]; <add> data[j - 1] = data[j]; <add> data[j] = temp; <add> } <add> } <add> } <add> } <add> <add> public static void main(String[] args) { <add> Integer[] data = new Integer[]{23, 56, 33, 0, 9, 56, 87}; <add> InsertionSort.sort(data); <add> System.out.println(Arrays.toString(data)); <add> } <add>}
Java
agpl-3.0
a2a1976028060505caef5cd18fac96142580b81e
0
VietOpenCPS/opencps-v2,VietOpenCPS/opencps-v2
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package org.opencps.dossiermgt.service.impl; import com.liferay.counter.kernel.service.CounterLocalServiceUtil; import com.liferay.petra.string.StringPool; import com.liferay.portal.kernel.dao.orm.QueryUtil; import com.liferay.portal.kernel.exception.NoSuchUserException; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.json.JSONArray; import com.liferay.portal.kernel.json.JSONException; import com.liferay.portal.kernel.json.JSONFactoryUtil; import com.liferay.portal.kernel.json.JSONObject; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.messaging.Message; import com.liferay.portal.kernel.messaging.MessageBusUtil; import com.liferay.portal.kernel.model.Company; import com.liferay.portal.kernel.model.User; import com.liferay.portal.kernel.service.ServiceContext; import com.liferay.portal.kernel.service.SubscriptionLocalServiceUtil; import com.liferay.portal.kernel.service.UserLocalServiceUtil; import com.liferay.portal.kernel.transaction.Isolation; import com.liferay.portal.kernel.transaction.Propagation; import com.liferay.portal.kernel.transaction.Transactional; import com.liferay.portal.kernel.util.GetterUtil; import com.liferay.portal.kernel.util.ListUtil; import com.liferay.portal.kernel.util.LocaleUtil; import com.liferay.portal.kernel.util.PwdGenerator; import com.liferay.portal.kernel.util.StringUtil; import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.kernel.uuid.PortalUUIDUtil; import java.io.IOException; import java.io.Serializable; import java.net.URLEncoder; import java.sql.Timestamp; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.activation.DataHandler; import javax.ws.rs.HttpMethod; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.opencps.auth.api.BackendAuth; import org.opencps.auth.api.BackendAuthImpl; import org.opencps.auth.api.exception.UnauthenticationException; import org.opencps.auth.api.exception.UnauthorizationException; import org.opencps.auth.api.keys.ActionKeys; import org.opencps.auth.api.keys.NotificationType; import org.opencps.auth.utils.APIDateTimeUtils; import org.opencps.cache.actions.CacheActions; import org.opencps.cache.actions.impl.CacheActionsImpl; import org.opencps.communication.model.NotificationQueue; import org.opencps.communication.model.Notificationtemplate; import org.opencps.communication.model.ServerConfig; import org.opencps.communication.service.NotificationQueueLocalServiceUtil; import org.opencps.communication.service.NotificationtemplateLocalServiceUtil; import org.opencps.communication.service.ServerConfigLocalServiceUtil; import org.opencps.datamgt.model.DictCollection; import org.opencps.datamgt.model.DictItem; import org.opencps.datamgt.model.Holiday; import org.opencps.datamgt.service.DictCollectionLocalServiceUtil; import org.opencps.datamgt.service.DictItemLocalServiceUtil; import org.opencps.datamgt.service.HolidayLocalServiceUtil; import org.opencps.datamgt.util.ExtendDueDateUtils; import org.opencps.datamgt.util.HolidayUtils; import org.opencps.dossiermgt.action.DossierActions; import org.opencps.dossiermgt.action.DossierUserActions; import org.opencps.dossiermgt.action.impl.DossierActionsImpl; import org.opencps.dossiermgt.action.impl.DossierPermission; import org.opencps.dossiermgt.action.impl.DossierUserActionsImpl; import org.opencps.dossiermgt.action.util.AutoFillFormData; import org.opencps.dossiermgt.action.util.DocumentTypeNumberGenerator; import org.opencps.dossiermgt.action.util.DossierActionUtils; import org.opencps.dossiermgt.action.util.DossierMgtUtils; import org.opencps.dossiermgt.action.util.DossierNumberGenerator; import org.opencps.dossiermgt.action.util.DossierPaymentUtils; import org.opencps.dossiermgt.action.util.KeyPay; import org.opencps.dossiermgt.action.util.OpenCPSConfigUtil; import org.opencps.dossiermgt.action.util.PaymentUrlGenerator; import org.opencps.dossiermgt.constants.ActionConfigTerm; import org.opencps.dossiermgt.constants.DossierActionTerm; import org.opencps.dossiermgt.constants.DossierActionUserTerm; import org.opencps.dossiermgt.constants.DossierDocumentTerm; import org.opencps.dossiermgt.constants.DossierFileTerm; import org.opencps.dossiermgt.constants.DossierPartTerm; import org.opencps.dossiermgt.constants.DossierStatusConstants; import org.opencps.dossiermgt.constants.DossierSyncTerm; import org.opencps.dossiermgt.constants.DossierTerm; import org.opencps.dossiermgt.constants.PaymentFileTerm; import org.opencps.dossiermgt.constants.ProcessActionTerm; import org.opencps.dossiermgt.constants.PublishQueueTerm; import org.opencps.dossiermgt.constants.ServerConfigTerm; import org.opencps.dossiermgt.constants.StepConfigTerm; import org.opencps.dossiermgt.exception.DataConflictException; import org.opencps.dossiermgt.exception.NoSuchDossierUserException; import org.opencps.dossiermgt.exception.NoSuchPaymentFileException; import org.opencps.dossiermgt.input.model.DossierInputModel; import org.opencps.dossiermgt.input.model.DossierMultipleInputModel; import org.opencps.dossiermgt.input.model.PaymentFileInputModel; import org.opencps.dossiermgt.model.ActionConfig; import org.opencps.dossiermgt.model.Deliverable; import org.opencps.dossiermgt.model.DocumentType; import org.opencps.dossiermgt.model.Dossier; import org.opencps.dossiermgt.model.DossierAction; import org.opencps.dossiermgt.model.DossierActionUser; import org.opencps.dossiermgt.model.DossierDocument; import org.opencps.dossiermgt.model.DossierFile; import org.opencps.dossiermgt.model.DossierMark; import org.opencps.dossiermgt.model.DossierPart; import org.opencps.dossiermgt.model.DossierTemplate; import org.opencps.dossiermgt.model.DossierUser; import org.opencps.dossiermgt.model.PaymentConfig; import org.opencps.dossiermgt.model.PaymentFile; import org.opencps.dossiermgt.model.ProcessAction; import org.opencps.dossiermgt.model.ProcessOption; import org.opencps.dossiermgt.model.ProcessSequence; import org.opencps.dossiermgt.model.ProcessStep; import org.opencps.dossiermgt.model.ProcessStepRole; import org.opencps.dossiermgt.model.PublishQueue; import org.opencps.dossiermgt.model.ServiceConfig; import org.opencps.dossiermgt.model.ServiceInfo; import org.opencps.dossiermgt.model.ServiceProcess; import org.opencps.dossiermgt.model.ServiceProcessRole; import org.opencps.dossiermgt.model.StepConfig; import org.opencps.dossiermgt.scheduler.InvokeREST; import org.opencps.dossiermgt.scheduler.RESTFulConfiguration; import org.opencps.dossiermgt.service.DocumentTypeLocalServiceUtil; import org.opencps.dossiermgt.service.DossierActionLocalServiceUtil; import org.opencps.dossiermgt.service.DossierActionUserLocalServiceUtil; import org.opencps.dossiermgt.service.DossierDocumentLocalServiceUtil; import org.opencps.dossiermgt.service.DossierFileLocalServiceUtil; import org.opencps.dossiermgt.service.DossierLocalServiceUtil; import org.opencps.dossiermgt.service.ProcessActionLocalServiceUtil; import org.opencps.dossiermgt.service.ProcessStepLocalServiceUtil; import org.opencps.dossiermgt.service.PublishQueueLocalServiceUtil; import org.opencps.dossiermgt.service.StepConfigLocalServiceUtil; import org.opencps.dossiermgt.service.base.CPSDossierBusinessLocalServiceBaseImpl; import org.opencps.dossiermgt.service.persistence.DossierActionUserPK; import org.opencps.dossiermgt.service.persistence.DossierUserPK; import org.opencps.dossiermgt.service.persistence.ServiceProcessRolePK; import org.opencps.usermgt.model.Applicant; import org.opencps.usermgt.model.Employee; import org.opencps.usermgt.model.EmployeeJobPos; import org.opencps.usermgt.model.JobPos; import org.opencps.usermgt.model.WorkingUnit; import org.opencps.usermgt.service.ApplicantLocalServiceUtil; import org.opencps.usermgt.service.EmployeeJobPosLocalServiceUtil; import org.opencps.usermgt.service.EmployeeLocalServiceUtil; import org.opencps.usermgt.service.JobPosLocalServiceUtil; import org.opencps.usermgt.service.WorkingUnitLocalServiceUtil; import backend.auth.api.exception.NotFoundException; /** * The implementation of the cps dossier business local service. * * <p> * All custom service methods should be put in this class. Whenever methods are added, rerun ServiceBuilder to copy their definitions into the {@link org.opencps.dossiermgt.service.CPSDossierBusinessLocalService} interface. * * <p> * This is a local service. Methods of this service will not have security checks based on the propagated JAAS credentials because this service can only be accessed from within the same VM. * </p> * * @author huymq * @see CPSDossierBusinessLocalServiceBaseImpl * @see org.opencps.dossiermgt.service.CPSDossierBusinessLocalServiceUtil */ @Transactional(isolation = Isolation.PORTAL, rollbackFor = { PortalException.class, SystemException.class }) public class CPSDossierBusinessLocalServiceImpl extends CPSDossierBusinessLocalServiceBaseImpl { /* * NOTE FOR DEVELOPERS: * * Never reference this class directly. Always use {@link org.opencps.dossiermgt.service.CPSDossierBusinessLocalServiceUtil} to access the cps dossier business local service. */ public static final String DOSSIER_SATUS_DC_CODE = "DOSSIER_STATUS"; public static final String DOSSIER_SUB_SATUS_DC_CODE = "DOSSIER_SUB_STATUS"; CacheActions cache = new CacheActionsImpl(); int ttl = OpenCPSConfigUtil.getCacheTTL(); private Dossier createCrossDossier(long groupId, ProcessAction proAction, ProcessStep curStep, DossierAction previousAction, Employee employee, Dossier dossier, User user, ServiceContext context) throws PortalException { if (Validator.isNotNull(proAction.getCreateDossiers())) { //Create new HSLT String GOVERNMENT_AGENCY = "GOVERNMENT_AGENCY"; String govAgencyName = getDictItemName(groupId, GOVERNMENT_AGENCY, proAction.getCreateDossiers()); String createDossiers = proAction.getCreateDossiers(); String govAgencyCode = StringPool.BLANK; String serviceCode = dossier.getServiceCode(); String dossierTemplateNo = dossier.getDossierTemplateNo(); if (createDossiers.contains(StringPool.POUND)) { String[] splitCDs = createDossiers.split(StringPool.POUND); if (splitCDs.length == 2) { govAgencyCode = splitCDs[0]; if (splitCDs[1].contains(StringPool.AT)) { if (splitCDs[1].split(StringPool.AT).length != 2) { throw new PortalException("Cross dossier config error"); } else { dossierTemplateNo = splitCDs[1].split(StringPool.AT)[0]; serviceCode = splitCDs[1].split(StringPool.AT)[1]; } } else { govAgencyCode = splitCDs[0]; } } } else { if (createDossiers.contains(StringPool.AT)) { if (createDossiers.split(StringPool.AT).length != 2) { throw new PortalException("Cross dossier config error"); } else { govAgencyCode = createDossiers.split(StringPool.AT)[0]; serviceCode = createDossiers.split(StringPool.AT)[1]; } } else { govAgencyCode = createDossiers; } } ServiceConfig serviceConfig = serviceConfigLocalService.getBySICodeAndGAC(groupId, dossier.getServiceCode(), govAgencyCode); if (serviceConfig != null) { List<ProcessOption> lstOptions = processOptionLocalService.getByServiceProcessId(serviceConfig.getServiceConfigId()); // ProcessOption foundOption = null; if (createDossiers.contains(StringPool.POUND)) { for (ProcessOption po : lstOptions) { DossierTemplate dt = dossierTemplateLocalService.fetchDossierTemplate(po.getDossierTemplateId()); if (dt.getTemplateNo().equals(dossierTemplateNo)) { foundOption = po; break; } } } else { if (lstOptions.size() > 0) { foundOption = lstOptions.get(0); } } if (foundOption != null) { ServiceProcess ltProcess = serviceProcessLocalService.fetchServiceProcess(foundOption.getServiceProcessId()); DossierTemplate dossierTemplate = dossierTemplateLocalService.fetchDossierTemplate(foundOption.getDossierTemplateId()); // String delegateName = dossier.getDelegateName(); String delegateName = dossier.getGovAgencyName(); String delegateAddress = dossier.getDelegateAddress(); String delegateTelNo = dossier.getDelegateTelNo(); String delegateEmail = dossier.getDelegateEmail(); String delegateIdNo = dossier.getGovAgencyCode(); // Dossier oldHslt = DossierLocalServiceUtil.getByG_AN_SC_GAC_DTNO(groupId, dossier.getApplicantIdNo(), dossier.getServiceCode(), govAgencyCode, dossierTemplate.getTemplateNo()); // long hsltDossierId = (oldHslt != null ? oldHslt.getDossierId() : 0l); Dossier hsltDossier = dossierLocalService.initDossier(groupId, 0l, UUID.randomUUID().toString(), dossier.getCounter(), dossier.getServiceCode(), dossier.getServiceName(), govAgencyCode, govAgencyName, dossier.getApplicantName(), dossier.getApplicantIdType(), dossier.getApplicantIdNo(), dossier.getApplicantIdDate(), dossier.getAddress(), dossier.getCityCode(), dossier.getCityName(), dossier.getDistrictCode(), dossier.getDistrictName(), dossier.getWardCode(), dossier.getWardName(), dossier.getContactName(), dossier.getContactTelNo(), dossier.getContactEmail(), dossierTemplate.getTemplateNo(), dossier.getPassword(), dossier.getViaPostal(), dossier.getPostalAddress(), dossier.getPostalCityCode(), dossier.getPostalCityName(), dossier.getPostalTelNo(), dossier.getOnline(), dossier.getNotification(), dossier.getApplicantNote(), DossierTerm.ORIGINALITY_DVCTT, context); WorkingUnit wu = WorkingUnitLocalServiceUtil.fetchByF_govAgencyCode(dossier.getGroupId(), dossier.getGovAgencyCode()); if (wu != null) { delegateName = wu.getName(); delegateAddress = wu.getAddress(); delegateTelNo = wu.getTelNo(); delegateEmail = wu.getEmail(); delegateIdNo = wu.getGovAgencyCode(); if (hsltDossier != null) { hsltDossier.setDelegateName(delegateName); hsltDossier.setDelegateAddress(delegateAddress); hsltDossier.setDelegateTelNo(delegateTelNo); hsltDossier.setDelegateEmail(delegateEmail); hsltDossier.setDelegateIdNo(delegateIdNo); hsltDossier.setNew(false); hsltDossier = dossierLocalService.updateDossier(hsltDossier); } } else if (user != null) { if (employee != null) { delegateName = employee.getFullName(); delegateAddress = dossier.getGovAgencyName(); delegateTelNo = employee.getTelNo(); delegateEmail = employee.getEmail(); if (hsltDossier != null) { hsltDossier.setDelegateName(delegateName); hsltDossier.setDelegateAddress(delegateAddress); hsltDossier.setDelegateTelNo(delegateTelNo); hsltDossier.setDelegateEmail(delegateEmail); hsltDossier.setDelegateIdNo(delegateIdNo); hsltDossier.setNew(false); hsltDossier = dossierLocalService.updateDossier(hsltDossier); } } } // String dossierNote = StringPool.BLANK; if (previousAction != null) { dossierNote = previousAction.getActionNote(); if (Validator.isNotNull(dossierNote)) { dossierNote = previousAction.getStepInstruction(); } } if (hsltDossier != null) { //Set HSLT dossierId to origin dossier hsltDossier.setOriginDossierId(dossier.getDossierId()); if (ltProcess.getServerNo().contains(StringPool.COMMA)) { if (!serviceCode.equals(dossier.getServiceCode())) { String serverNoProcess = ltProcess.getServerNo().split(StringPool.COMMA)[0]; hsltDossier.setServerNo(serverNoProcess + StringPool.AT + serviceCode + StringPool.COMMA + ltProcess.getServerNo().split(StringPool.COMMA)[1]); hsltDossier = dossierLocalService.updateDossier(hsltDossier); } } else { hsltDossier.setServerNo(ltProcess.getServerNo()); } //Update DossierName hsltDossier.setDossierName(dossier.getDossierName()); hsltDossier.setOriginDossierNo(dossier.getDossierNo()); dossierLocalService.updateDossier(hsltDossier); JSONObject jsonDataStatusText = getStatusText(groupId, DOSSIER_SATUS_DC_CODE, DossierTerm.DOSSIER_STATUS_NEW, StringPool.BLANK); hsltDossier = dossierLocalService.updateStatus(groupId, hsltDossier.getDossierId(), hsltDossier.getReferenceUid(), DossierTerm.DOSSIER_STATUS_NEW, jsonDataStatusText != null ? jsonDataStatusText.getString(DossierTerm.DOSSIER_STATUS_NEW) : StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, dossierNote, context); } else { return null; } JSONObject jsonDataStatusText = getStatusText(groupId, DOSSIER_SATUS_DC_CODE, DossierTerm.DOSSIER_STATUS_INTEROPERATING, StringPool.BLANK); if (curStep != null) { dossier = dossierLocalService.updateStatus(groupId, dossier.getDossierId(), dossier.getReferenceUid(), DossierTerm.DOSSIER_STATUS_INTEROPERATING, jsonDataStatusText != null ? jsonDataStatusText.getString(DossierTerm.DOSSIER_STATUS_INTEROPERATING) : StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, curStep.getLockState(), dossierNote, context); dossier.setDossierStatus(DossierTerm.DOSSIER_STATUS_INTEROPERATING); dossier.setDossierStatusText(jsonDataStatusText != null ? jsonDataStatusText.getString(DossierTerm.DOSSIER_STATUS_INTEROPERATING) : StringPool.BLANK); dossier.setDossierSubStatus(StringPool.BLANK); dossier.setDossierSubStatusText(StringPool.BLANK); dossier.setLockState(curStep.getLockState()); dossier.setDossierNote(dossierNote);; } return hsltDossier; } else { return null; } } else { return null; } } else { return null; } } private void createDossierDocument(long groupId, long userId, ActionConfig actionConfig, Dossier dossier, DossierAction dossierAction, JSONObject payloadObject, Employee employee, User user, ServiceContext context) throws com.liferay.portal.kernel.search.ParseException, JSONException { //Check if generate dossier document ActionConfig ac = actionConfig; if (ac != null) { if (dossier.getOriginality() != DossierTerm.ORIGINALITY_DVCTT) { if (Validator.isNotNull(ac.getDocumentType()) && !ac.getActionCode().startsWith("@")) { //Generate document DocumentType dt = DocumentTypeLocalServiceUtil.getByTypeCode(groupId, ac.getDocumentType()); if (dt != null) { String documentCode = DocumentTypeNumberGenerator.generateDocumentTypeNumber(groupId, ac.getCompanyId(), dt.getDocumentTypeId()); DossierDocument dossierDocument = DossierDocumentLocalServiceUtil.addDossierDoc(groupId, dossier.getDossierId(), UUID.randomUUID().toString(), dossierAction.getDossierActionId(), dt.getTypeCode(), dt.getDocumentName(), documentCode, 0L, dt.getDocSync(), context); //Generate PDF String formData = dossierAction.getPayload(); JSONObject payloadTmp = JSONFactoryUtil.createJSONObject(formData); if (payloadTmp != null && payloadTmp.has("complementDate")) { if (payloadTmp.getLong("complementDate") > 0) { Timestamp ts = new Timestamp(payloadTmp.getLong("complementDate")); SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy"); payloadTmp.put("complementDate", format.format(ts)); } } JSONObject formDataObj = processMergeDossierFormData(dossier, payloadTmp); formDataObj = processMergeDossierProcessRole(dossier, 1, formDataObj, dossierAction); formDataObj.put("url", context.getPortalURL()); if (employee != null) { formDataObj.put("userName", employee.getFullName()); } else { formDataObj.put("userName", user.getFullName()); } Message message = new Message(); // _log.info("Document script: " + dt.getDocumentScript()); JSONObject msgData = JSONFactoryUtil.createJSONObject(); msgData.put("className", DossierDocument.class.getName()); msgData.put("classPK", dossierDocument.getDossierDocumentId()); msgData.put("jrxmlTemplate", dt.getDocumentScript()); msgData.put("formData", formDataObj.toJSONString()); msgData.put("userId", userId); message.put("msgToEngine", msgData); MessageBusUtil.sendMessage("jasper/engine/out/destination", message); payloadObject.put("dossierDocument", dossierDocument.getDossierDocumentId()); } } } } } private void createDossierSync(long groupId, long userId, ActionConfig actionConfig, ProcessAction proAction, DossierAction dossierAction, Dossier dossier, int syncType, ProcessOption option, JSONObject payloadObject, Map<String, Boolean> flagChanged, String actionCode, String actionUser, String actionNote, ServiceProcess serviceProcess, ServiceContext context) throws PortalException { //Create DossierSync String dossierRefUid = dossier.getReferenceUid(); String syncRefUid = UUID.randomUUID().toString(); if (syncType > 0) { int state = DossierActionUtils.getSyncState(syncType, dossier); //If state = 1 set pending dossier if (state == DossierSyncTerm.STATE_WAITING_SYNC) { if (dossierAction != null) { dossierAction.setPending(true); dossierActionLocalService.updateDossierAction(dossierAction); } } else { if (dossierAction != null) { dossierAction.setPending(false); dossierActionLocalService.updateDossierAction(dossierAction); } } //Update payload JSONArray dossierFilesArr = JSONFactoryUtil.createJSONArray(); List<DossierFile> lstFiles = DossierFileLocalServiceUtil.findByDID(dossier.getDossierId()); if (actionConfig.getSyncType() == DossierSyncTerm.SYNCTYPE_REQUEST) { if (dossier.getOriginDossierId() == 0) { if (lstFiles.size() > 0) { for (DossierFile df : lstFiles) { JSONObject dossierFileObj = JSONFactoryUtil.createJSONObject(); dossierFileObj.put(DossierFileTerm.REFERENCE_UID, df.getReferenceUid()); dossierFilesArr.put(dossierFileObj); } } } else { // ServiceConfig serviceConfig = ServiceConfigLocalServiceUtil.getBySICodeAndGAC(groupId, dossier.getServiceCode(), dossier.getGovAgencyCode()); // List<ProcessOption> lstOptions = ProcessOptionLocalServiceUtil.getByServiceProcessId(serviceConfig.getServiceConfigId()); // if (serviceConfig != null) { // if (lstOptions.size() > 0) { // ProcessOption processOption = lstOptions.get(0); ProcessOption processOption = option; DossierTemplate dossierTemplate = dossierTemplateLocalService.fetchDossierTemplate(processOption.getDossierTemplateId()); List<DossierPart> lstParts = dossierPartLocalService.getByTemplateNo(groupId, dossierTemplate.getTemplateNo()); List<DossierFile> lstOriginFiles = dossierFileLocalService.findByDID(dossier.getOriginDossierId()); if (lstOriginFiles.size() > 0) { for (DossierFile df : lstOriginFiles) { boolean flagHslt = false; for (DossierPart dp : lstParts) { if (dp.getPartNo().equals(df.getDossierPartNo())) { flagHslt = true; break; } } if (flagHslt) { JSONObject dossierFileObj = JSONFactoryUtil.createJSONObject(); dossierFileObj.put(DossierFileTerm.REFERENCE_UID, df.getReferenceUid()); dossierFilesArr.put(dossierFileObj); } } } // } // } } } else { //Sync result files } payloadObject.put("dossierFiles", dossierFilesArr); if (Validator.isNotNull(proAction.getReturnDossierFiles())) { List<DossierFile> lsDossierFile = lstFiles; dossierFilesArr = JSONFactoryUtil.createJSONArray(); // check return file List<String> returnDossierFileTemplateNos = ListUtil .toList(StringUtil.split(proAction.getReturnDossierFiles())); for (DossierFile dossierFile : lsDossierFile) { if (returnDossierFileTemplateNos.contains(dossierFile.getFileTemplateNo())) { JSONObject dossierFileObj = JSONFactoryUtil.createJSONObject(); dossierFileObj.put(DossierFileTerm.REFERENCE_UID, dossierFile.getReferenceUid()); dossierFilesArr.put(dossierFileObj); } } payloadObject.put("dossierFiles", dossierFilesArr); } List<DossierDocument> lstDossierDocuments = dossierDocumentLocalService.getDossierDocumentList(dossier.getDossierId(), QueryUtil.ALL_POS, QueryUtil.ALL_POS); JSONArray dossierDocumentArr = JSONFactoryUtil.createJSONArray(); for (DossierDocument dossierDocument : lstDossierDocuments) { JSONObject dossierDocumentObj = JSONFactoryUtil.createJSONObject(); dossierDocumentObj.put(DossierDocumentTerm.REFERENCE_UID, dossierDocument.getReferenceUid()); dossierDocumentArr.put(dossierDocumentObj); } payloadObject.put("dossierFiles", dossierFilesArr); payloadObject.put("dossierDocuments", dossierDocumentArr); //Put dossier note payloadObject.put(DossierTerm.DOSSIER_NOTE, dossier.getDossierNote()); //Put dossier note payloadObject.put(DossierTerm.SUBMIT_DATE, dossier.getSubmitDate() != null ? dossier.getSubmitDate().getTime() : 0); // _log.info("Flag changed: " + flagChanged); payloadObject = DossierActionUtils.buildChangedPayload(payloadObject, flagChanged, dossier); if (Validator.isNotNull(dossier.getServerNo()) && dossier.getServerNo().split(StringPool.COMMA).length > 1) { String serverNo = dossier.getServerNo().split(StringPool.COMMA)[0].split(StringPool.AT)[0]; dossierSyncLocalService.updateDossierSync(groupId, userId, dossier.getDossierId(), dossierRefUid, syncRefUid, dossierAction.getPrimaryKey(), actionCode, proAction.getActionName(), actionUser, actionNote, syncType, actionConfig.getInfoType(), payloadObject.toJSONString(), serverNo, state); } else { dossierSyncLocalService.updateDossierSync(groupId, userId, dossier.getDossierId(), dossierRefUid, syncRefUid, dossierAction.getPrimaryKey(), actionCode, proAction.getActionName(), actionUser, actionNote, syncType, actionConfig.getInfoType(), payloadObject.toJSONString(), dossier.getServerNo(), state); } //Gửi thông tin hồ sơ để tra cứu if (state == DossierSyncTerm.STATE_NOT_SYNC && actionConfig != null && actionConfig.getEventType() == ActionConfigTerm.EVENT_TYPE_SENT) { publishEvent(dossier, context); } } else if (actionConfig != null && actionConfig.getEventType() == ActionConfigTerm.EVENT_TYPE_SENT) { publishEvent(dossier, context); } } private void doMappingAction(long groupId, long userId, Employee employee, Dossier dossier, ActionConfig actionConfig, String actionUser, String actionNote, String payload, String assignUsers, String payment,ServiceContext context) throws PortalException, Exception { if (Validator.isNotNull(actionConfig) && Validator.isNotNull(actionConfig.getMappingAction())) { ActionConfig mappingConfig = actionConfigLocalService.getByCode(groupId, actionConfig.getMappingAction()); if (dossier.getOriginDossierId() != 0) { Dossier hslt = dossierLocalService.fetchDossier(dossier.getOriginDossierId()); ProcessOption optionHslt = getProcessOption(hslt.getServiceCode(), hslt.getGovAgencyCode(), hslt.getDossierTemplateNo(), groupId); ProcessAction actionHslt = getProcessAction(groupId, hslt.getDossierId(), hslt.getReferenceUid(), actionConfig.getMappingAction(), optionHslt.getServiceProcessId()); String actionUserHslt = actionUser; if (employee != null) { actionUserHslt = actionUser; } if (DossierTerm.DOSSIER_STATUS_NEW.equals(hslt.getDossierStatus())) { Date now = new Date(); hslt.setSubmitDate(now); hslt = dossierLocalService.updateDossier(hslt); try { JSONObject payloadObj = JSONFactoryUtil.createJSONObject(payload); payloadObj.put(DossierTerm.SUBMIT_DATE, now.getTime()); payload = payloadObj.toJSONString(); } catch (JSONException e) { _log.debug(e); } } doAction(groupId, userId, hslt, optionHslt, actionHslt, actionConfig.getMappingAction(), actionUserHslt, actionNote, payload, assignUsers, payment, mappingConfig.getSyncType(), context); } else { Dossier originDossier = dossierLocalService.getByOrigin(groupId, dossier.getDossierId()); if (originDossier != null) { ProcessOption optionOrigin = getProcessOption(originDossier.getServiceCode(), originDossier.getGovAgencyCode(), originDossier.getDossierTemplateNo(), groupId); ProcessAction actionOrigin = getProcessAction(groupId, originDossier.getDossierId(), originDossier.getReferenceUid(), actionConfig.getMappingAction(), optionOrigin.getServiceProcessId()); doAction(groupId, userId, originDossier, optionOrigin, actionOrigin, actionConfig.getMappingAction(), actionUser, actionNote, payload, assignUsers, payment, mappingConfig.getSyncType(), context); } } } } private DossierAction createActionAndAssignUser(long groupId, long userId, ProcessStep curStep, ActionConfig actionConfig, DossierAction dossierAction, DossierAction previousAction, ProcessAction proAction, Dossier dossier, String actionCode, String actionUser, String actionNote, String payload, String assignUsers, String payment, ServiceProcess serviceProcess, ProcessOption option, Map<String, Boolean> flagChanged, ServiceContext context) throws PortalException { int actionOverdue = getActionDueDate(groupId, dossier.getDossierId(), dossier.getReferenceUid(), proAction.getProcessActionId()); String actionName = proAction.getActionName(); String prevStatus = dossier.getDossierStatus(); if (curStep != null) { String curStatus = curStep.getDossierStatus(); String curSubStatus = curStep.getDossierSubStatus(); String stepCode = curStep.getStepCode(); String stepName = curStep.getStepName(); String stepInstruction = curStep.getStepInstruction(); String sequenceNo = curStep.getSequenceNo(); JSONObject jsonDataStatusText = getStatusText(groupId, DOSSIER_SATUS_DC_CODE, curStatus, curSubStatus); String fromStepCode = previousAction != null ? previousAction.getStepCode() : StringPool.BLANK; String fromStepName = previousAction != null ? previousAction.getStepName() : StringPool.BLANK; String fromSequenceNo = previousAction != null ? previousAction.getSequenceNo() : StringPool.BLANK; int state = DossierActionTerm.STATE_WAITING_PROCESSING; int eventStatus = (actionConfig != null ? (actionConfig.getEventType() == ActionConfigTerm.EVENT_TYPE_NOT_SENT ? DossierActionTerm.EVENT_STATUS_NOT_CREATED : DossierActionTerm.EVENT_STATUS_WAIT_SENDING) : DossierActionTerm.EVENT_STATUS_NOT_CREATED); boolean rollbackable = false; if (actionConfig != null) { if (actionConfig.getRollbackable()) { rollbackable = true; } else { } } else { if (proAction.isRollbackable()) { rollbackable = true; } else { } } dossierAction = dossierActionLocalService.updateDossierAction(groupId, 0, dossier.getDossierId(), serviceProcess.getServiceProcessId(), dossier.getDossierActionId(), fromStepCode, fromStepName, fromSequenceNo, actionCode, actionUser, actionName, actionNote, actionOverdue, stepCode, stepName, sequenceNo, null, 0l, payload, stepInstruction, state, eventStatus, rollbackable, context); dossier.setDossierActionId(dossierAction.getDossierActionId()); String dossierNote = StringPool.BLANK; if (dossierAction != null) { dossierNote = dossierAction.getActionNote(); if (Validator.isNotNull(dossierNote)) { dossierNote = dossierAction.getStepInstruction(); } } //Update previous action nextActionId Date now = new Date(); if (previousAction != null && dossierAction != null) { previousAction.setNextActionId(dossierAction.getDossierActionId()); previousAction.setState(DossierActionTerm.STATE_ALREADY_PROCESSED); previousAction.setModifiedDate(now); previousAction = dossierActionLocalService.updateDossierAction(previousAction); } updateStatus(dossier, curStatus, jsonDataStatusText != null ? jsonDataStatusText.getString(curStatus) : StringPool.BLANK, curSubStatus, jsonDataStatusText != null ? jsonDataStatusText.getString(curSubStatus) : StringPool.BLANK, curStep.getLockState(), dossierNote, context); //Cập nhật cờ đồng bộ ngày tháng sang các hệ thống khác flagChanged = updateProcessingDate(dossierAction, previousAction, curStep, dossier, curStatus, curSubStatus, prevStatus, actionConfig, option, serviceProcess, context); dossierAction = dossierActionLocalService.fetchDossierAction(dossier.getDossierActionId()); } //Thiết lập quyền thao tác hồ sơ int allowAssignUser = proAction.getAllowAssignUser(); if (allowAssignUser != ProcessActionTerm.NOT_ASSIGNED) { if (Validator.isNotNull(assignUsers)) { JSONArray assignedUsersArray = JSONFactoryUtil.createJSONArray(assignUsers); assignDossierActionUser(dossier, allowAssignUser, dossierAction, userId, groupId, proAction.getAssignUserId(), assignedUsersArray); if (OpenCPSConfigUtil.isNotificationEnable()) { createNotificationSMS(userId, groupId, dossier, assignedUsersArray, dossierAction, context); } } else { initDossierActionUser(proAction, dossier, allowAssignUser, dossierAction, userId, groupId, proAction.getAssignUserId()); } } else { //Process role as step if (Validator.isNotNull(curStep.getRoleAsStep())) { copyRoleAsStep(curStep, dossier); } else { initDossierActionUser(proAction, dossier, allowAssignUser, dossierAction, userId, groupId, proAction.getAssignUserId()); } } return dossierAction; } private DossierAction doActionInsideProcess(long groupId, long userId, Dossier dossier, ActionConfig actionConfig, ProcessOption option, ProcessAction proAction, String actionCode, String actionUser, String actionNote, String payload, String assignUsers, String payment, int syncType, ServiceContext context) throws PortalException, SystemException, Exception { context.setUserId(userId); DossierAction dossierAction = null; Map<String, Boolean> flagChanged = null; JSONObject payloadObject = JSONFactoryUtil.createJSONObject(); User user = userLocalService.fetchUser(userId); String dossierStatus = dossier.getDossierStatus().toLowerCase(); Employee employee = null; Serializable employeeCache = cache.getFromCache("Employee", groupId +"_"+ userId); // _log.info("EMPLOYEE CACHE: " + employeeCache); if (employeeCache == null) { employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userId); if (employee != null) { cache.addToCache("Employee", groupId +"_"+ userId, (Serializable) employee, ttl); } } else { employee = (Employee) employeeCache; } try { JSONFactoryUtil.createJSONObject(payload); } catch (JSONException e) { _log.debug(e); } if (Validator.isNotNull(dossierStatus)) { if(!"new".equals(dossierStatus)) { } else if (dossier.getOriginality() == DossierTerm.ORIGINALITY_DVCTT) { dossier.setSubmitDate(new Date()); } } long dossierId = dossier.getDossierId(); ServiceProcess serviceProcess = null; DossierAction previousAction = null; if (dossier.getDossierActionId() != 0) { previousAction = dossierActionLocalService.fetchDossierAction(dossier.getDossierActionId()); } //Cập nhật thông tin hồ sơ dựa vào payload truyền vào khi thực hiện thao tác if (Validator.isNotNull(payload)) { JSONObject pl = payloadObject; updateDossierPayload(dossier, pl); } if ((option != null || previousAction != null) && proAction != null) { long serviceProcessId = (option != null ? option.getServiceProcessId() : previousAction.getServiceProcessId()); Serializable serviceProcessCache = cache.getFromCache("ServiceProcess", groupId +"_"+ serviceProcessId); if (serviceProcessCache == null) { serviceProcess = serviceProcessLocalService.fetchServiceProcess(serviceProcessId); if (serviceProcess != null) { cache.addToCache("ServiceProcess", groupId +"_"+ serviceProcessId, (Serializable) serviceProcess, ttl); } } else { serviceProcess = (ServiceProcess) serviceProcessCache; } String paymentFee = StringPool.BLANK; String postStepCode = proAction.getPostStepCode(); //Xử lý phiếu thanh toán processPaymentFile(groupId, userId, payment, option, proAction, previousAction, dossier, context); //Bước sau không có thì mặc định quay lại bước trước đó if (Validator.isNull(postStepCode)) { postStepCode = previousAction.getFromStepCode(); ProcessStep backCurStep = processStepLocalService.fetchBySC_GID(postStepCode, groupId, serviceProcessId); String curStatus = backCurStep.getDossierStatus(); String curSubStatus = backCurStep.getDossierSubStatus(); JSONObject jsonDataStatusText = getStatusText(groupId, DOSSIER_SATUS_DC_CODE, curStatus, curSubStatus); //update dossierStatus dossier = DossierLocalServiceUtil.updateStatus(groupId, dossierId, dossier.getReferenceUid(), curStatus, jsonDataStatusText != null ? jsonDataStatusText.getString(curStatus) : StringPool.BLANK, curSubStatus, jsonDataStatusText != null ? jsonDataStatusText.getString(curSubStatus) : StringPool.BLANK, backCurStep.getLockState(), dossier.getDossierNote(), context); dossier.setDossierActionId(previousAction.getPreviousActionId()); dossierLocalService.updateDossier(dossier); return previousAction; } ProcessStep curStep = processStepLocalService.fetchBySC_GID(postStepCode, groupId, serviceProcessId); //Kiểm tra cấu hình cần tạo hồ sơ liên thông Dossier hsltDossier = createCrossDossier(groupId, proAction, curStep, previousAction, employee, dossier, user, context); if (Validator.isNotNull(proAction.getCreateDossiers())) { if (Validator.isNull(hsltDossier)) { return null; } } //Cập nhật hành động và quyền người dùng với hồ sơ dossierAction = createActionAndAssignUser(groupId, userId, curStep, actionConfig, dossierAction, previousAction, proAction, dossier, actionCode, actionUser, actionNote, payload, assignUsers, paymentFee, serviceProcess, option, flagChanged, context); // dossier = dossierLocalService.updateDossier(dossier); //Tạo văn bản đính kèm createDossierDocument(groupId, userId, actionConfig, dossier, dossierAction, payloadObject, employee, user, context); //Kiểm tra xem có gửi dịch vụ vận chuyển hay không if (proAction.getPreCondition().toLowerCase().contains("sendviapostal=1")) { vnpostEvent(dossier); } } else { } //Create notification if (OpenCPSConfigUtil.isNotificationEnable()) { createNotificationQueue(user, groupId, dossier, actionConfig, dossierAction, context); } //Create subcription createSubcription(userId, groupId, dossier, actionConfig, dossierAction, context); //Tạo thông tin đồng bộ hồ sơ createDossierSync(groupId, userId, actionConfig, proAction, dossierAction, dossier, syncType, option, payloadObject, flagChanged, actionCode, actionUser, actionNote, serviceProcess, context); //Thực hiện thao tác lên hồ sơ gốc hoặc hồ sơ liên thông trong trường hợp có cấu hình mappingAction doMappingAction(groupId, userId, employee, dossier, actionConfig, actionUser, actionNote, payload, assignUsers, payment, context); dossier = dossierLocalService.updateDossier(dossier); // Indexer<Dossier> indexer = IndexerRegistryUtil // .nullSafeGetIndexer(Dossier.class); // indexer.reindex(dossier); return dossierAction; } @Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class }) public DossierAction doAction(long groupId, long userId, Dossier dossier, ProcessOption option, ProcessAction proAction, String actionCode, String actionUser, String actionNote, String payload, String assignUsers, String payment, int syncType, ServiceContext context) throws PortalException, SystemException, Exception { context.setUserId(userId); DossierAction dossierAction = null; ActionConfig actionConfig = null; actionConfig = actionConfigLocalService.getByCode(groupId, actionCode); if (actionConfig != null && !actionConfig.getInsideProcess()) { dossierAction = doActionOutsideProcess(groupId, userId, dossier, actionConfig, option, proAction, actionCode, actionUser, actionNote, payload, assignUsers, payment, syncType, context); } else { dossierAction = doActionInsideProcess(groupId, userId, dossier, actionConfig, option, proAction, actionCode, actionUser, actionNote, payload, assignUsers, payment, syncType, context); } return dossierAction; } private void createNotificationQueue(User user, long groupId, Dossier dossier, ActionConfig actionConfig, DossierAction dossierAction, ServiceContext context) throws PortalException { // DossierAction dossierAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId()); // User u = UserLocalServiceUtil.fetchUser(userId); JSONObject payloadObj = JSONFactoryUtil.createJSONObject(); try { payloadObj.put( "Dossier", JSONFactoryUtil.createJSONObject( JSONFactoryUtil.looseSerialize(dossier))); if (dossierAction != null) { payloadObj.put("actionCode", dossierAction.getActionCode()); payloadObj.put("actionUser", dossierAction.getActionUser()); payloadObj.put("actionName", dossierAction.getActionName()); payloadObj.put("actionNote", dossierAction.getActionNote()); } } catch (Exception e) { _log.error(e); } if (actionConfig != null && Validator.isNotNull(actionConfig.getNotificationType())) { // Notificationtemplate notiTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, actionConfig.getNotificationType()); Serializable notiCache = cache.getFromCache("NotificationTemplate", groupId +"_"+ actionConfig.getNotificationType()); Notificationtemplate notiTemplate = null; // notiTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, actionConfig.getNotificationType()); if (notiCache == null) { notiTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, actionConfig.getNotificationType()); if (notiTemplate != null) { cache.addToCache("NotificationTemplate", groupId +"_"+ actionConfig.getNotificationType(), (Serializable) notiTemplate, ttl); } } else { notiTemplate = (Notificationtemplate) notiCache; } Date now = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(now); if (notiTemplate != null) { if ("minutely".equals(notiTemplate.getInterval())) { cal.add(Calendar.MINUTE, notiTemplate.getExpireDuration()); } else if ("hourly".equals(notiTemplate.getInterval())) { cal.add(Calendar.HOUR, notiTemplate.getExpireDuration()); } else { cal.add(Calendar.MINUTE, notiTemplate.getExpireDuration()); } Date expired = cal.getTime(); if (actionConfig.getNotificationType().startsWith("APLC")) { if (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA || dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) { try { // Applicant applicant = ApplicantLocalServiceUtil.fetchByAppId(dossier.getApplicantIdNo()); List<Applicant> applicants = ApplicantLocalServiceUtil.findByAppIds(dossier.getApplicantIdNo()); Applicant foundApplicant = (applicants.isEmpty() ? null : applicants.get(0)); for (Applicant applicant : applicants) { long toUserId = (applicant != null ? applicant.getMappingUserId() : 0l); if (toUserId != 0) { foundApplicant = applicant; break; } } if (foundApplicant != null) { NotificationQueueLocalServiceUtil.addNotificationQueue( user.getUserId(), groupId, actionConfig.getNotificationType(), Dossier.class.getName(), String.valueOf(dossier.getDossierId()), payloadObj.toJSONString(), user.getFullName(), dossier.getApplicantName(), foundApplicant.getMappingUserId(), dossier.getContactEmail(), dossier.getContactTelNo(), now, expired, context); } } catch (NoSuchUserException e) { // e.printStackTrace(); _log.error(e); //_log.error(e); // e.printStackTrace(); } } } else if (actionConfig.getNotificationType().startsWith("USER")) { } } } // Notificationtemplate emplTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, "EMPL-01"); Serializable emplCache = cache.getFromCache("NotificationTemplate", groupId +"_"+ "EMPL-01"); Notificationtemplate emplTemplate = null; emplTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, "EMPL-01"); if (emplCache == null) { emplTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, "EMPL-01"); if (emplTemplate != null) { cache.addToCache("NotificationTemplate", groupId +"_"+ actionConfig.getNotificationType(), (Serializable) emplTemplate, ttl); } } else { emplTemplate = (Notificationtemplate) emplCache; } Date now = new Date(); Calendar calEmpl = Calendar.getInstance(); calEmpl.setTime(now); if (emplTemplate != null) { if ("minutely".equals(emplTemplate.getInterval())) { calEmpl.add(Calendar.MINUTE, emplTemplate.getExpireDuration()); } else if ("hourly".equals(emplTemplate.getInterval())) { calEmpl.add(Calendar.HOUR, emplTemplate.getExpireDuration()); } else { calEmpl.add(Calendar.MINUTE, emplTemplate.getExpireDuration()); } Date expired = calEmpl.getTime(); if (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA || dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) { try { String stepCode = dossierAction.getStepCode(); StringBuilder buildX = new StringBuilder(stepCode); if (stepCode.length() > 0) { buildX.setCharAt(stepCode.length() - 1, 'x'); } String stepCodeX = buildX.toString(); StepConfig stepConfig = StepConfigLocalServiceUtil.getByCode(groupId, dossierAction.getStepCode()); StepConfig stepConfigX = StepConfigLocalServiceUtil.getByCode(groupId, stepCodeX); if ((stepConfig != null && stepConfig.getStepType() == StepConfigTerm.STEP_TYPE_DISPLAY_MENU_BY_PROCESSED) || (stepConfigX != null && stepConfigX.getStepType() == StepConfigTerm.STEP_TYPE_DISPLAY_MENU_BY_PROCESSED)) { List<DossierActionUser> lstDaus = DossierActionUserLocalServiceUtil.getByDossierAndStepCode(dossier.getDossierId(), dossierAction.getStepCode()); for (DossierActionUser dau : lstDaus) { if (dau.getAssigned() == DossierActionUserTerm.ASSIGNED_TH || dau.getAssigned() == DossierActionUserTerm.ASSIGNED_PH) { // Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, dau.getUserId()); Serializable employeeCache = cache.getFromCache("Employee", groupId +"_"+ dau.getUserId()); Employee employee = null; // employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, dau.getUserId()); if (employeeCache == null) { employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, dau.getUserId()); if (employee != null) { cache.addToCache("Employee", groupId +"_"+ dau.getUserId(), (Serializable) employee, ttl); } } else { employee = (Employee) employeeCache; } if (employee != null) { String telNo = employee != null ? employee.getTelNo() : StringPool.BLANK; String fullName = employee != null ? employee.getFullName() : StringPool.BLANK; long start = System.currentTimeMillis(); NotificationQueueLocalServiceUtil.addNotificationQueue( user.getUserId(), groupId, "EMPL-01", Dossier.class.getName(), String.valueOf(dossier.getDossierId()), payloadObj.toJSONString(), user.getFullName(), fullName, dau.getUserId(), employee.getEmail(), telNo, now, expired, context); _log.debug("ADD NOTI QUEUE: " + (System.currentTimeMillis() - start)); } } } } } catch (NoSuchUserException e) { _log.error(e); //_log.error(e); // e.printStackTrace(); } } } } private void updateDossierPayload(Dossier dossier, JSONObject obj) { if (obj.has(DossierTerm.DOSSIER_NOTE)) { if (!obj.getString(DossierTerm.DOSSIER_NOTE).equals(dossier.getDossierNote())) { dossier.setDossierNote(obj.getString(DossierTerm.DOSSIER_NOTE)); } } if (obj.has(DossierTerm.EXTEND_DATE) && Validator.isNotNull(obj.get(DossierTerm.EXTEND_DATE)) && GetterUtil.getLong(obj.get(DossierTerm.EXTEND_DATE)) > 0) { if (dossier.getExtendDate() == null || obj.getLong(DossierTerm.EXTEND_DATE) != dossier.getExtendDate().getTime()) { dossier.setExtendDate(new Date(obj.getLong(DossierTerm.EXTEND_DATE))); } } if (obj.has(DossierTerm.DOSSIER_NO)) { //_log.info("Sync dossier no"); if (Validator.isNotNull(obj.getString(DossierTerm.DOSSIER_NO)) && !obj.getString(DossierTerm.DOSSIER_NO).equals(dossier.getDossierNo())) { //_log.info("Sync set dossier no"); dossier.setDossierNo(obj.getString(DossierTerm.DOSSIER_NO)); } } if (obj.has(DossierTerm.DUE_DATE) && Validator.isNotNull(obj.get(DossierTerm.DUE_DATE)) && GetterUtil.getLong(obj.get(DossierTerm.DUE_DATE)) > 0) { if (dossier.getDueDate() == null || obj.getLong(DossierTerm.DUE_DATE) != dossier.getDueDate().getTime()) { dossier.setDueDate(new Date(obj.getLong(DossierTerm.DUE_DATE))); } } if (obj.has(DossierTerm.FINISH_DATE) && Validator.isNotNull(obj.get(DossierTerm.FINISH_DATE)) && GetterUtil.getLong(obj.get(DossierTerm.FINISH_DATE)) > 0) { if (dossier.getFinishDate() == null || obj.getLong(DossierTerm.FINISH_DATE) != dossier.getFinishDate().getTime()) { dossier.setFinishDate(new Date(obj.getLong(DossierTerm.FINISH_DATE))); } } if (obj.has(DossierTerm.RECEIVE_DATE) && Validator.isNotNull(obj.get(DossierTerm.RECEIVE_DATE)) && GetterUtil.getLong(obj.get(DossierTerm.RECEIVE_DATE)) > 0) { if (dossier.getReceiveDate() == null || obj.getLong(DossierTerm.RECEIVE_DATE) != dossier.getReceiveDate().getTime()) { dossier.setReceiveDate(new Date(obj.getLong(DossierTerm.RECEIVE_DATE))); } } if (obj.has(DossierTerm.SUBMIT_DATE) && Validator.isNotNull(obj.get(DossierTerm.SUBMIT_DATE)) && GetterUtil.getLong(obj.get(DossierTerm.SUBMIT_DATE)) > 0) { if (dossier.getSubmitDate() == null || (dossier.getSubmitDate() != null && obj.getLong(DossierTerm.SUBMIT_DATE) != dossier.getSubmitDate().getTime())) { dossier.setSubmitDate(new Date(obj.getLong(DossierTerm.SUBMIT_DATE))); } } if (obj.has(DossierTerm.EXTEND_DATE) && Validator.isNotNull(obj.get(DossierTerm.EXTEND_DATE)) && GetterUtil.getLong(obj.get(DossierTerm.EXTEND_DATE)) > 0) { if (dossier.getExtendDate() == null || obj.getLong(DossierTerm.EXTEND_DATE) != dossier.getExtendDate().getTime()) { dossier.setExtendDate(new Date(obj.getLong(DossierTerm.EXTEND_DATE))); } } if (obj.has(DossierTerm.DOSSIER_NOTE)) { if (dossier.getDossierNote() == null || !obj.getString(DossierTerm.DOSSIER_NOTE).equals(dossier.getDossierNote())) { dossier.setDossierNote(obj.getString(DossierTerm.DOSSIER_NOTE)); } } if (obj.has(DossierTerm.SUBMISSION_NOTE)) { if (!obj.getString(DossierTerm.SUBMISSION_NOTE).equals(dossier.getDossierNote())) { dossier.setSubmissionNote(obj.getString(DossierTerm.SUBMISSION_NOTE)); } } if (obj.has(DossierTerm.RELEASE_DATE) && Validator.isNotNull(obj.get(DossierTerm.RELEASE_DATE)) && GetterUtil.getLong(obj.get(DossierTerm.RELEASE_DATE)) > 0) { if (dossier.getReleaseDate() == null || obj.getLong(DossierTerm.RELEASE_DATE) != dossier.getReleaseDate().getTime()) { dossier.setReleaseDate(new Date(obj.getLong(DossierTerm.RELEASE_DATE))); } } if (obj.has(DossierTerm.LOCK_STATE)) { if (!obj.getString(DossierTerm.LOCK_STATE).equals(dossier.getLockState())) { dossier.setLockState(obj.getString(DossierTerm.LOCK_STATE)); } } if (obj.has(DossierTerm.BRIEF_NOTE)) { if (!obj.getString(DossierTerm.BRIEF_NOTE).equals(dossier.getBriefNote())) { dossier.setBriefNote(obj.getString(DossierTerm.BRIEF_NOTE)); } } } private void processPaymentFile(long groupId, long userId, String payment, ProcessOption option, ProcessAction proAction, DossierAction previousAction, Dossier dossier, ServiceContext context) throws PortalException { // long serviceProcessId = (option != null ? option.getServiceProcessId() : previousAction.getServiceProcessId()); // ServiceProcess serviceProcess = ServiceProcessLocalServiceUtil.fetchServiceProcess(serviceProcessId); String paymentFee = StringPool.BLANK; //Yêu cầu nộp tạm ứng if (proAction.getRequestPayment() == ProcessActionTerm.REQUEST_PAYMENT_YEU_CAU_NOP_TAM_UNG || proAction.getRequestPayment() == ProcessActionTerm.REQUEST_PAYMENT_YEU_CAU_QUYET_TOAN_PHI && Validator.isNotNull(payment)) { Long feeAmount = 0l, serviceAmount = 0l, shipAmount = 0l; String paymentNote = StringPool.BLANK; long advanceAmount = 0l; long paymentAmount = 0l; String epaymentProfile = StringPool.BLANK; String bankInfo = StringPool.BLANK; int paymentStatus = 0; String paymentMethod = StringPool.BLANK; NumberFormat fmt = NumberFormat.getNumberInstance(LocaleUtil.getDefault()); DecimalFormatSymbols customSymbol = new DecimalFormatSymbols(); customSymbol.setDecimalSeparator(','); customSymbol.setGroupingSeparator('.'); ((DecimalFormat)fmt).setDecimalFormatSymbols(customSymbol); fmt.setGroupingUsed(true); try { JSONObject paymentObj = JSONFactoryUtil.createJSONObject(payment); if (paymentObj.has("paymentNote")) { paymentNote = paymentObj.getString("paymentNote"); } if (paymentObj.has("feeAmount")) { feeAmount = (Long)fmt.parse(paymentObj.getString("feeAmount")); } if (paymentObj.has("serviceAmount")) { serviceAmount = (Long)fmt.parse(paymentObj.getString("serviceAmount")); } if (paymentObj.has("shipAmount")) { shipAmount = (Long)fmt.parse(paymentObj.getString("shipAmount")); } if (paymentObj.has("requestPayment")) { paymentStatus = paymentObj.getInt("requestPayment"); } if (paymentObj.has("advanceAmount")) { advanceAmount = (Long)fmt.parse(paymentObj.getString("advanceAmount")); } JSONObject paymentObj2 = JSONFactoryUtil.createJSONObject(proAction.getPaymentFee()); if (paymentObj2.has("paymentFee")) { paymentFee = paymentObj2.getString("paymentFee"); } } catch (JSONException e) { _log.debug(e); } catch (ParseException e) { _log.debug(e); } PaymentFile oldPaymentFile = paymentFileLocalService.getByDossierId(groupId, dossier.getDossierId()); if (oldPaymentFile != null) { if (Validator.isNotNull(paymentNote)) oldPaymentFile.setPaymentNote(paymentNote); try { PaymentFile paymentFile = paymentFileLocalService.updateApplicantFeeAmount( oldPaymentFile.getPaymentFileId(), proAction.getRequestPayment(), feeAmount, serviceAmount, shipAmount, paymentNote, dossier.getOriginality()); String generatorPayURL = PaymentUrlGenerator.generatorPayURL(groupId, paymentFile.getPaymentFileId(), paymentFee, dossier.getDossierId()); JSONObject epaymentProfileJsonNew = JSONFactoryUtil.createJSONObject(paymentFile.getEpaymentProfile()); epaymentProfileJsonNew.put("keypayUrl", generatorPayURL); paymentFileLocalService.updateEProfile(dossier.getDossierId(), paymentFile.getReferenceUid(), epaymentProfileJsonNew.toJSONString(), context); } catch (IOException e) { _log.error(e); } catch (JSONException e) { _log.debug(e); } } else { paymentAmount = feeAmount + serviceAmount + shipAmount - advanceAmount; PaymentFile paymentFile = paymentFileLocalService.createPaymentFiles(userId, groupId, dossier.getDossierId(), dossier.getReferenceUid(), paymentFee, advanceAmount, feeAmount, serviceAmount, shipAmount, paymentAmount, paymentNote, epaymentProfile, bankInfo, paymentStatus, paymentMethod, context); long counterPaymentFile = CounterLocalServiceUtil.increment(PaymentFile.class.getName() + "paymentFileNo"); Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); int prefix = cal.get(Calendar.YEAR); String invoiceNo = Integer.toString(prefix) + String.format("%010d", counterPaymentFile); paymentFile.setInvoiceNo(invoiceNo); PaymentConfig paymentConfig = paymentConfigLocalService.getPaymentConfigByGovAgencyCode(groupId, dossier.getGovAgencyCode()); if (Validator.isNotNull(paymentConfig)) { paymentFile.setInvoiceTemplateNo(paymentConfig.getInvoiceTemplateNo()); paymentFile.setGovAgencyTaxNo(paymentConfig.getGovAgencyTaxNo()); paymentFile.setGovAgencyCode(paymentConfig.getGovAgencyCode()); paymentFile.setGovAgencyName(paymentConfig.getGovAgencyName()); } paymentFileLocalService.updatePaymentFile(paymentFile); JSONObject epaymentConfigJSON = paymentConfig != null ? JSONFactoryUtil.createJSONObject(paymentConfig.getEpaymentConfig()) : JSONFactoryUtil.createJSONObject(); JSONObject epaymentProfileJSON = JSONFactoryUtil.createJSONObject(); if (epaymentConfigJSON.has("paymentKeypayDomain")) { try { String generatorPayURL = PaymentUrlGenerator.generatorPayURL(groupId, paymentFile.getPaymentFileId(), paymentFee, dossier.getDossierId()); epaymentProfileJSON.put("keypayUrl", generatorPayURL); String pattern1 = "good_code="; String pattern2 = "&"; String regexString = Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2); Pattern p = Pattern.compile(regexString); Matcher m = p.matcher(generatorPayURL); if (m.find()) { String goodCode = m.group(1); epaymentProfileJSON.put("keypayGoodCode", goodCode); } else { epaymentProfileJSON.put("keypayGoodCode", StringPool.BLANK); } epaymentProfileJSON.put("keypayMerchantCode", epaymentConfigJSON.get("paymentMerchantCode")); epaymentProfileJSON.put("bank", "true"); epaymentProfileJSON.put("paygate", "true"); epaymentProfileJSON.put("serviceAmount", serviceAmount); epaymentProfileJSON.put("paymentNote", paymentNote); epaymentProfileJSON.put("paymentFee", paymentFee); paymentFileLocalService.updateEProfile(dossier.getDossierId(), paymentFile.getReferenceUid(), epaymentProfileJSON.toJSONString(), context); } catch (IOException e) { _log.error(e); } } else { paymentFileLocalService.updateEProfile(dossier.getDossierId(), paymentFile.getReferenceUid(), epaymentProfileJSON.toJSONString(), context); } } } else if (proAction.getRequestPayment() == ProcessActionTerm.REQUEST_PAYMENT_XAC_NHAN_HOAN_THANH_THU_PHI) { String CINVOICEUrl = "postal/invoice"; JSONObject resultObj = null; Map<String, Object> params = new HashMap<>(); PaymentFile oldPaymentFile = paymentFileLocalService.getByDossierId(groupId, dossier.getDossierId()); int intpaymentMethod = 0; if (Validator.isNotNull(proAction.getPreCondition())) { intpaymentMethod = checkPaymentMethodinPrecondition(proAction.getPreCondition()); } if (oldPaymentFile != null && proAction.getPreCondition().toLowerCase().contains("sendinvoice=1")){ params = createParamsInvoice(oldPaymentFile, dossier, intpaymentMethod); InvokeREST callRest = new InvokeREST(); String baseUrl = RESTFulConfiguration.SERVER_PATH_BASE; HashMap<String, String> properties = new HashMap<String, String>(); resultObj = callRest.callPostAPI(groupId, HttpMethod.POST, "application/json", baseUrl, CINVOICEUrl, "", "", properties, params, context); } if (Validator.isNotNull(oldPaymentFile) ) { String paymentMethod = ""; if (intpaymentMethod != 0) { paymentMethod = checkPaymentMethod(intpaymentMethod); } if(Validator.isNotNull(resultObj)) { oldPaymentFile.setEinvoice(resultObj.toString()); oldPaymentFile.setInvoicePayload(params.toString()); if (Validator.isNotNull(paymentMethod)) { oldPaymentFile.setPaymentMethod(paymentMethod); } } if (Validator.isNotNull(payment)) { try { JSONObject paymentObj = JSONFactoryUtil.createJSONObject(payment); if (paymentObj.has("paymentNote")) { oldPaymentFile.setPaymentNote(paymentObj.getString("paymentNote")); String epaymentProfile = oldPaymentFile.getEpaymentProfile(); if (Validator.isNotNull(epaymentProfile)) { JSONObject jsonEpayment = JSONFactoryUtil.createJSONObject(epaymentProfile); jsonEpayment.put("paymentNote", paymentObj.getString("paymentNote")); oldPaymentFile.setEpaymentProfile(jsonEpayment.toJSONString()); } } } catch (JSONException e) { _log.debug(e); } } oldPaymentFile.setPaymentStatus(proAction.getRequestPayment()); paymentFileLocalService.updatePaymentFile(oldPaymentFile); } } else if (proAction.getRequestPayment() == ProcessActionTerm.REQUEST_PAYMENT_BAO_DA_NOP_PHI) { PaymentFile oldPaymentFile = paymentFileLocalService.getByDossierId(groupId, dossier.getDossierId()); int intpaymentMethod = checkPaymentMethodinPrecondition(proAction.getPreCondition()); String paymentMethod = checkPaymentMethod(intpaymentMethod); if (oldPaymentFile != null) { oldPaymentFile.setPaymentStatus(proAction.getRequestPayment()); oldPaymentFile.setPaymentMethod(paymentMethod); paymentFileLocalService.updatePaymentFile(oldPaymentFile); } } } private void createNotificationSMS(long userId, long groupId, Dossier dossier, JSONArray assignedUsers, DossierAction dossierAction, ServiceContext context) { // DossierAction dossierAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId()); User u = UserLocalServiceUtil.fetchUser(userId); JSONObject payloadObj = JSONFactoryUtil.createJSONObject(); try { payloadObj.put( "Dossier", JSONFactoryUtil.createJSONObject( JSONFactoryUtil.looseSerialize(dossier))); if (dossierAction != null) { payloadObj.put("actionCode", dossierAction.getActionCode()); payloadObj.put("actionUser", dossierAction.getActionUser()); payloadObj.put("actionName", dossierAction.getActionName()); payloadObj.put("actionNote", dossierAction.getActionNote()); } } catch (Exception e) { _log.error(e); } Notificationtemplate emplTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, "EMPL-03"); Date now = new Date(); Calendar calEmpl = Calendar.getInstance(); calEmpl.setTime(now); if (emplTemplate != null) { if ("minutely".equals(emplTemplate.getInterval())) { calEmpl.add(Calendar.MINUTE, emplTemplate.getExpireDuration()); } else if ("hourly".equals(emplTemplate.getInterval())) { calEmpl.add(Calendar.HOUR, emplTemplate.getExpireDuration()); } else { calEmpl.add(Calendar.MINUTE, emplTemplate.getExpireDuration()); } Date expired = calEmpl.getTime(); if (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA || dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) { try { String stepCode = dossierAction.getStepCode(); StringBuilder buildX = new StringBuilder(stepCode); if (stepCode.length() > 0) { buildX.setCharAt(stepCode.length() - 1, 'x'); } String stepCodeX = buildX.toString(); StepConfig stepConfig = StepConfigLocalServiceUtil.getByCode(groupId, dossierAction.getStepCode()); StepConfig stepConfigX = StepConfigLocalServiceUtil.getByCode(groupId, stepCodeX); if ((stepConfig != null && stepConfig.getStepType() == StepConfigTerm.STEP_TYPE_DISPLAY_MENU_BY_PROCESSED) || (stepConfigX != null && stepConfigX.getStepType() == StepConfigTerm.STEP_TYPE_DISPLAY_MENU_BY_PROCESSED)) { for (int n = 0; n < assignedUsers.length(); n++) { JSONObject subUser = assignedUsers.getJSONObject(n); if (subUser != null && subUser.has(DossierActionUserTerm.ASSIGNED) && subUser.getInt(DossierActionUserTerm.ASSIGNED) == DossierActionUserTerm.ASSIGNED_TH) { long userIdAssigned = subUser.getLong("userId"); Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userIdAssigned); if (employee != null) { String telNo = employee != null ? employee.getTelNo() : StringPool.BLANK; String fullName = employee != null ? employee.getFullName() : StringPool.BLANK; NotificationQueueLocalServiceUtil.addNotificationQueue( userId, groupId, "EMPL-03", Dossier.class.getName(), String.valueOf(dossier.getDossierId()), payloadObj.toJSONString(), u.getFullName(), fullName, userIdAssigned, employee.getEmail(), telNo, now, expired, context); } } } } } catch (NoSuchUserException e) { _log.error(e); //_log.error(e); // e.printStackTrace(); } } } } private void createSubcription(long userId, long groupId, Dossier dossier, ActionConfig actionConfig, DossierAction dossierAction, ServiceContext context) { if (actionConfig != null && Validator.isNotNull(actionConfig.getNotificationType())) { // DossierAction dossierAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId()); // User u = UserLocalServiceUtil.fetchUser(userId); Notificationtemplate notiTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, actionConfig.getNotificationType()); if (notiTemplate != null) { if (actionConfig.getDocumentType().startsWith("APLC")) { if (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA || dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) { } } else if (actionConfig.getDocumentType().startsWith("EMPL")) { if ((dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA || dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) && dossierAction != null) { StepConfig stepConfig = stepConfigLocalService.getByCode(groupId, dossierAction.getStepCode()); List<DossierActionUser> lstDaus = dossierActionUserLocalService.getByDID_DAI_SC_AS(dossier.getDossierId(), dossierAction.getDossierActionId(), dossierAction.getStepCode(), new int[] { 1, 2 }); if ("EMPL-01".equals(actionConfig.getDocumentType()) && stepConfig != null && "1".equals(stepConfig.getStepType())) { for (DossierActionUser dau : lstDaus) { try { SubscriptionLocalServiceUtil.addSubscription(dau.getUserId(), groupId, "EMPL-01", 0); } catch (PortalException e) { _log.debug(e); } } } } } else if (actionConfig.getDocumentType().startsWith("USER")) { } } } } private List<String> _putPaymentMessage(String pattern) { List<String> lsDesc = new ArrayList<String>(); lsDesc.add(0, StringPool.BLANK); lsDesc.add(1, StringPool.BLANK); lsDesc.add(2, StringPool.BLANK); lsDesc.add(3, StringPool.BLANK); lsDesc.add(4, StringPool.BLANK); List<String> lsMsg = DossierPaymentUtils.getMessagePayment(pattern); for (int i = 0; i < lsMsg.size(); i++) { lsDesc.set(1, lsMsg.get(i)); } return lsDesc; } private long _genetatorTransactionId() { long transactionId = 0; try { transactionId = counterLocalService.increment(PaymentFile.class.getName() + ".genetatorTransactionId"); } catch (SystemException e) { _log.error(e); } return transactionId; } private String generatorPayURL(long groupId, long paymentFileId, String pattern, Dossier dossier) throws IOException { String result = ""; try { PaymentFile paymentFile = paymentFileLocalService.getPaymentFile(paymentFileId); PaymentConfig paymentConfig = paymentConfigLocalService.getPaymentConfigByGovAgencyCode(groupId, dossier.getGovAgencyCode()); if (Validator.isNotNull(paymentConfig)) { List<String> lsMessages = _putPaymentMessage(pattern); long merchant_trans_id = _genetatorTransactionId(); JSONObject epaymentConfigJSON = JSONFactoryUtil.createJSONObject(paymentConfig.getEpaymentConfig()); String merchant_code = epaymentConfigJSON.getString("paymentMerchantCode"); String good_code = generatorGoodCode(10); String net_cost = String.valueOf(paymentFile.getPaymentAmount()); String ship_fee = "0"; String tax = "0"; String bank_code = StringPool.BLANK; String service_code = epaymentConfigJSON.getString("paymentServiceCode"); String version = epaymentConfigJSON.getString("paymentVersion"); String command = epaymentConfigJSON.getString("paymentCommand"); String currency_code = epaymentConfigJSON.getString("paymentCurrencyCode"); String desc_1 = StringPool.BLANK; String desc_2 = StringPool.BLANK; String desc_3 = StringPool.BLANK; String desc_4 = StringPool.BLANK; String desc_5 = StringPool.BLANK; if (lsMessages.size() > 0) { desc_1 = lsMessages.get(0); desc_2 = lsMessages.get(1); desc_3 = lsMessages.get(2); desc_4 = lsMessages.get(3); desc_5 = lsMessages.get(4); if (desc_1.length() >= 20) { desc_1 = desc_1.substring(0, 19); } if (desc_2.length() >= 30) { desc_2 = desc_2.substring(0, 29); } if (desc_3.length() >= 40) { desc_3 = desc_3.substring(0, 39); } if (desc_4.length() >= 100) { desc_4 = desc_4.substring(0, 89); } if (desc_5.length() > 15) { desc_5 = desc_5.substring(0, 15); if (!Validator.isDigit(desc_5)) { desc_5 = StringPool.BLANK; } } } String xml_description = StringPool.BLANK; String current_locale = epaymentConfigJSON.getString("paymentCurrentLocale"); String country_code = epaymentConfigJSON.getString("paymentCountryCode"); String internal_bank = epaymentConfigJSON.getString("paymentInternalBank"); String merchant_secure_key = epaymentConfigJSON.getString("paymentMerchantSecureKey"); // dossier = _getDossier(dossierId); // TODO : update returnURL keyPay String return_url; _log.info("SONDT GENURL paymentReturnUrl ====================== "+ JSONFactoryUtil.looseSerialize(epaymentConfigJSON)); // return_url = epaymentConfigJSON.getString("paymentReturnUrl")+ "/" + dossier.getReferenceUid() + "/" + paymentFile.getReferenceUid(); return_url = epaymentConfigJSON.getString("paymentReturnUrl")+ "&dossierId=" + dossier.getDossierId() + "&goodCode=" + good_code + "&transId=" + merchant_trans_id + "&referenceUid=" + dossier.getReferenceUid(); _log.info("SONDT GENURL paymentReturnUrl ====================== "+ return_url); // http://119.17.200.66:2681/web/bo-van-hoa/dich-vu-cong/#/thanh-toan-thanh-cong?paymentPortal=KEYPAY&dossierId=77603&goodCode=123&transId=555 KeyPay keypay = new KeyPay(String.valueOf(merchant_trans_id), merchant_code, good_code, net_cost, ship_fee, tax, bank_code, service_code, version, command, currency_code, desc_1, desc_2, desc_3, desc_4, desc_5, xml_description, current_locale, country_code, return_url, internal_bank, merchant_secure_key); // keypay.setKeypay_url(paymentConfig.getKeypayDomain()); StringBuffer param = new StringBuffer(); param.append("merchant_code=").append(URLEncoder.encode(keypay.getMerchant_code(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("merchant_secure_key=").append(URLEncoder.encode(keypay.getMerchant_secure_key(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("bank_code=").append(URLEncoder.encode(keypay.getBank_code(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("internal_bank=").append(URLEncoder.encode(keypay.getInternal_bank(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("merchant_trans_id=").append(URLEncoder.encode(keypay.getMerchant_trans_id(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("good_code=").append(URLEncoder.encode(keypay.getGood_code(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("net_cost=").append(URLEncoder.encode(keypay.getNet_cost(), "UTF-8") ) .append(StringPool.AMPERSAND); param.append("ship_fee=").append(URLEncoder.encode(keypay.getShip_fee(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("tax=").append(URLEncoder.encode(keypay.getTax(), "UTF-8")).append(StringPool.AMPERSAND); param.append("return_url=").append(URLEncoder.encode(keypay.getReturn_url(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("version=").append(URLEncoder.encode(keypay.getVersion(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("command=").append(URLEncoder.encode(keypay.getCommand(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("current_locale=").append(URLEncoder.encode(keypay.getCurrent_locale(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("currency_code=").append(URLEncoder.encode(keypay.getCurrency_code(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("service_code=").append(URLEncoder.encode(keypay.getService_code(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("country_code=").append(URLEncoder.encode(keypay.getCountry_code(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("desc_1=").append(URLEncoder.encode(keypay.getDesc_1(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("desc_2=").append(URLEncoder.encode(keypay.getDesc_2(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("desc_3=").append(URLEncoder.encode(keypay.getDesc_3(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("desc_4=").append(URLEncoder.encode(keypay.getDesc_4(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("desc_5=").append(URLEncoder.encode(keypay.getDesc_5(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("xml_description=").append(URLEncoder.encode(keypay.getXml_description(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("secure_hash=").append(keypay.getSecure_hash()); result = epaymentConfigJSON.getString("paymentKeypayDomain") + StringPool.QUESTION + param.toString(); } } catch (NoSuchPaymentFileException e) { _log.debug(e); } catch (Exception e) { _log.debug(e); } return result; } private Map<String, Object> createParamsInvoice(PaymentFile oldPaymentFile, Dossier dossier, int intpaymentMethod) { Map<String, Object> params = new HashMap<>(); StringBuilder address = new StringBuilder(); address.append(dossier.getAddress());address.append(", "); address.append(dossier.getWardName());address.append(", "); address.append(dossier.getDistrictName());address.append(", "); address.append(dossier.getCityName()); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY"); String dateformatted = sdf.format(new Date()); _log.info("SONDT CINVOICE DATEFORMATED ============= " + dateformatted); params.put("userName", "HA"); params.put("passWord", "1"); params.put("soid", "0"); params.put("maHoadon", "01GTKT0/001"); params.put("ngayHd", dateformatted); //"01/08/2018" params.put("seri", "12314"); params.put("maNthue", "01"); params.put("kieuSo", "G"); params.put("maKhackHang", Long.toString(dossier.getUserId())); params.put("ten", dossier.getApplicantName()); params.put("phone", dossier.getContactTelNo()); if(dossier.getApplicantIdType().contentEquals("business")) { params.put("tax", dossier.getApplicantIdNo()); } else { params.put("tax", ""); } params.put("dchi", address); params.put("maTk", ""); params.put("tenNh", ""); params.put("mailH", GetterUtil.getString(dossier.getContactEmail())); params.put("phoneH", GetterUtil.getString(dossier.getContactTelNo())); params.put("tenM", GetterUtil.getString(dossier.getDelegateName())); params.put("maKhL", "K"); params.put("maNt", "VND"); params.put("tg", "1"); if(intpaymentMethod == 3) { params.put("hthuc", "M"); }else { params.put("hthuc", "C"); } params.put("han", ""); params.put("tlGgia", "0"); params.put("ggia", "0"); params.put("phi", "0"); params.put("noidung", dossier.getDossierNo()); params.put("tien", Long.toString(oldPaymentFile.getPaymentAmount())); params.put("ttoan", Long.toString(oldPaymentFile.getPaymentAmount())); params.put("maVtDetail", dossier.getDossierNo()); params.put("tenDetail", GetterUtil.getString(dossier.getServiceName())); params.put("dvtDetail", "bo"); params.put("luongDetail", "1"); params.put("giaDetail", Long.toString(oldPaymentFile.getPaymentAmount())); params.put("tienDetail", Long.toString(oldPaymentFile.getPaymentAmount())); params.put("tsDetail", "0"); params.put("thueDetail", "0"); params.put("ttoanDetail", Long.toString(oldPaymentFile.getPaymentAmount())); return params; } private int checkPaymentMethodinPrecondition(String preCondition) { int paymentMethod = 0; String[] preConditions = StringUtil.split(preCondition); for(String pre : preConditions) { pre = pre.trim(); if (pre.toLowerCase().contains("paymentmethod=")) { String[] splitPaymentMethod = pre.split("="); if (splitPaymentMethod.length == 2) { paymentMethod = Integer.parseInt(splitPaymentMethod[1]); } break; } } return paymentMethod; } private String checkPaymentMethod(int mt) { String pmMethod = ""; if (mt == 1) { pmMethod = "Chuyển khoản"; //KeyPay } else if (mt == 2) { pmMethod = "Chuyển khoản"; } else if (mt == 3) { pmMethod = "Tiền mặt"; } return pmMethod; } private JSONObject getStatusText(long groupId, String collectionCode, String curStatus, String curSubStatus) { JSONObject jsonData = null; DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(collectionCode, groupId); if (Validator.isNotNull(dc) && Validator.isNotNull(curStatus)) { jsonData = JSONFactoryUtil.createJSONObject(); DictItem it = DictItemLocalServiceUtil.fetchByF_dictItemCode(curStatus, dc.getPrimaryKey(), groupId); if (Validator.isNotNull(it)) { jsonData.put(curStatus, it.getItemName()); if (Validator.isNotNull(curSubStatus)) { DictItem dItem = DictItemLocalServiceUtil.fetchByF_dictItemCode(curSubStatus, dc.getPrimaryKey(), groupId); if (Validator.isNotNull(dItem)) { jsonData.put(curSubStatus, dItem.getItemName()); } } } } return jsonData; } private int getActionDueDate(long groupId, long dossierId, String refId, long processActionId) { return 0; } protected String getDictItemName(long groupId, String collectionCode, String itemCode) { DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(collectionCode, groupId); if (Validator.isNotNull(dc)) { DictItem it = DictItemLocalServiceUtil.fetchByF_dictItemCode(itemCode, dc.getPrimaryKey(), groupId); if(Validator.isNotNull(it)){ return it.getItemName(); }else{ return StringPool.BLANK; } } else { return StringPool.BLANK; } } private void updateStatus(Dossier dossier, String status, String statusText, String subStatus, String subStatusText, String lockState, String stepInstruction, ServiceContext context) throws PortalException { Date now = new Date(); dossier.setModifiedDate(now); dossier.setDossierStatus(status); dossier.setDossierStatusText(statusText); dossier.setDossierSubStatus(subStatus); dossier.setDossierSubStatusText(subStatusText); dossier.setLockState(lockState); dossier.setDossierNote(stepInstruction); if (status.equalsIgnoreCase(DossierStatusConstants.RELEASING)) { dossier.setReleaseDate(now); } if (status.equalsIgnoreCase(DossierStatusConstants.DONE)) { dossier.setFinishDate(now); } } private Map<String, Boolean> updateProcessingDate(DossierAction dossierAction, DossierAction prevAction, ProcessStep processStep, Dossier dossier, String curStatus, String curSubStatus, String prevStatus, ActionConfig actionConfig, ProcessOption option, ServiceProcess serviceProcess, ServiceContext context) { Date now = new Date(); Map<String, Boolean> bResult = new HashMap<>(); LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>(); params.put(DossierTerm.GOV_AGENCY_CODE, dossier.getGovAgencyCode()); params.put(DossierTerm.SERVICE_CODE, dossier.getServiceCode()); params.put(DossierTerm.DOSSIER_TEMPLATE_NO, dossier.getDossierTemplateNo()); params.put(DossierTerm.DOSSIER_STATUS, StringPool.BLANK); // ServiceProcess serviceProcess = null; // // long serviceProcessId = (option != null ? option.getServiceProcessId() : prevAction.getServiceProcessId()); // serviceProcess = ServiceProcessLocalServiceUtil.fetchServiceProcess(serviceProcessId); // if ((Validator.isNull(prevStatus) && DossierTerm.DOSSIER_STATUS_NEW.equals(curStatus) // && (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA)) if ((DossierTerm.DOSSIER_STATUS_RECEIVING.equals(curStatus) || DossierTerm.DOSSIER_STATUS_NEW.equals(curStatus)) && dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) { try { if (Validator.isNotNull(option) && Validator.isNull(dossier.getDossierNo())) { String dossierRef = DossierNumberGenerator.generateDossierNumber(dossier.getGroupId(), dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(), serviceProcess.getDossierNoPattern(), params); dossier.setDossierNo(dossierRef.trim()); // DossierLocalServiceUtil.updateDossier(dossier); bResult.put(DossierTerm.DOSSIER_NO, true); } } catch (PortalException e) { _log.debug(e); //_log.error(e); // e.printStackTrace(); } } if ((DossierTerm.DOSSIER_STATUS_NEW.equals(prevStatus) && DossierTerm.DOSSIER_STATUS_RECEIVING.equals(curStatus)) || (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA && DossierTerm.DOSSIER_STATUS_NEW.equals(curStatus))) { // try { // DossierLocalServiceUtil.updateSubmittingDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context); if (Validator.isNull(dossier.getSubmitDate())) { dossier.setSubmitDate(now); bResult.put(DossierTerm.SUBMIT_DATE, true); } // } catch (PortalException e) { // _log.error(e); // e.printStackTrace(); // } } if (dossier.getOriginality() != DossierTerm.ORIGINALITY_DVCTT && ((DossierTerm.DOSSIER_STATUS_PROCESSING.equals(curStatus) && dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) || (DossierTerm.DOSSIER_STATUS_NEW.equals(curStatus) && dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA) || (DossierTerm.DOSSIER_STATUS_NEW.equals(curStatus) && dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) || (actionConfig != null && actionConfig.getDateOption() == 2)) && dossier.getReceiveDate() == null) { // try { // DossierLocalServiceUtil.updateReceivingDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context); dossier.setReceiveDate(now); bResult.put(DossierTerm.RECEIVE_DATE, true); Double durationCount = serviceProcess.getDurationCount(); int durationUnit = serviceProcess.getDurationUnit(); Date dueDate = null; if (Validator.isNotNull(durationCount) && durationCount > 0 && !areEqualDouble(durationCount, 0.00d, 3)) { dueDate = HolidayUtils.getDueDate(now, durationCount, durationUnit, dossier.getGroupId()); } if (Validator.isNotNull(dueDate)) { dossier.setDueDate(dueDate); // DossierLocalServiceUtil.updateDueDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), dueDate, context); bResult.put(DossierTerm.DUE_DATE, true); } dossier.setDurationCount(durationCount); dossier.setDurationUnit(durationUnit); if (dossier.getCounter() == 0 && Validator.isNotNull(dossier.getRegisterBookCode())) { long counterCode = DossierNumberGenerator.countByRegiterBookCode(dossier.getGroupId(), dossier.getRegisterBookCode()); dossier.setCounter(counterCode); } if (Validator.isNull(dossier.getDossierNo())) { try { String dossierRef = DossierNumberGenerator.generateDossierNumber(dossier.getGroupId(), dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(), serviceProcess.getDossierNoPattern(), params); dossier.setDossierNo(dossierRef.trim()); } catch (Exception e) { //_log.debug(e); } } // dossier = DossierLocalServiceUtil.updateDossier(dossier); // } catch (PortalException e) { // _log.error(e); // e.printStackTrace(); // } } //Update counter and dossierNo if (actionConfig != null && actionConfig.getDateOption() == 2) { if (dossier.getCounter() == 0 && Validator.isNotNull(dossier.getRegisterBookCode())) { long counterCode = DossierNumberGenerator.countByRegiterBookCode(dossier.getGroupId(), dossier.getRegisterBookCode()); dossier.setCounter(counterCode); } if (Validator.isNull(dossier.getDossierNo())) { try { String dossierRef = DossierNumberGenerator.generateDossierNumber(dossier.getGroupId(), dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(), serviceProcess.getDossierNoPattern(), params); dossier.setDossierNo(dossierRef.trim()); } catch (Exception e) { // _log.debug(e); } } } if (DossierTerm.DOSSIER_STATUS_RECEIVING.equals(prevStatus) && DossierTerm.DOSSIER_STATUS_PROCESSING.equals(curStatus)) { // try { // DossierLocalServiceUtil.updateProcessDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context); dossier.setProcessDate(now); bResult.put(DossierTerm.PROCESS_DATE, true); // } catch (PortalException e) { // _log.error(e); // e.printStackTrace(); // } } // if (DossierTerm.DOSSIER_STATUS_RELEASING.equals(curStatus) // || DossierTerm.DOSSIER_STATUS_DENIED.equals(curStatus) // || DossierTerm.DOSSIER_STATUS_UNRESOLVED.equals(curStatus) // || DossierTerm.DOSSIER_STATUS_CANCELLED.equals(curStatus) // || DossierTerm.DOSSIER_STATUS_DONE.equals(curStatus)) { if (DossierTerm.DOSSIER_STATUS_RELEASING.equals(curStatus) || DossierTerm.DOSSIER_STATUS_UNRESOLVED.equals(curStatus) || DossierTerm.DOSSIER_STATUS_CANCELLED.equals(curStatus) || (actionConfig != null && actionConfig.getDateOption() == 4) ) { if (Validator.isNull(dossier.getReleaseDate())) { // try { // DossierLocalServiceUtil.updateReleaseDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context); dossier.setReleaseDate(now); bResult.put(DossierTerm.RELEASE_DATE, true); // } catch (PortalException e) { // _log.error(e); // e.printStackTrace(); // } } } // _log.info("========STEP DUE CUR STATUS: " + curStatus); if (DossierTerm.DOSSIER_STATUS_DENIED.equals(curStatus) || DossierTerm.DOSSIER_STATUS_UNRESOLVED.equals(curStatus) || DossierTerm.DOSSIER_STATUS_CANCELLED.equals(curStatus) || DossierTerm.DOSSIER_STATUS_DONE.equals(curStatus)) { // _log.info("========STEP DUE CUR STATUS UPDATING STATE DONE"); // dossierAction.setState(DossierActionTerm.STATE_ALREADY_PROCESSED); // dossierAction.setModifiedDate(new Date()); dossierAction = dossierActionLocalService.updateState(dossierAction.getDossierActionId(), DossierActionTerm.STATE_ALREADY_PROCESSED); } // if (DossierTerm.DOSSIER_STATUS_DENIED.equals(curStatus) // || DossierTerm.DOSSIER_STATUS_UNRESOLVED.equals(curStatus) // || DossierTerm.DOSSIER_STATUS_CANCELLED.equals(curStatus) // || DossierTerm.DOSSIER_STATUS_DONE.equals(curStatus)) { if (DossierTerm.DOSSIER_STATUS_DENIED.equals(curStatus) || DossierTerm.DOSSIER_STATUS_DONE.equals(curStatus) || DossierTerm.DOSSIER_STATUS_UNRESOLVED.equals(curStatus) || DossierTerm.DOSSIER_STATUS_CANCELLED.equals(curStatus) || (actionConfig != null && actionConfig.getDateOption() == 5)) { if (Validator.isNull(dossier.getFinishDate())) { // try { // DossierLocalServiceUtil.updateFinishDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context); dossier.setFinishDate(now); bResult.put(DossierTerm.FINISH_DATE, true); // dossierAction.setState(DossierActionTerm.STATE_ALREADY_PROCESSED); // dossierAction.setModifiedDate(new Date()); dossierAction = dossierActionLocalService.updateState(dossierAction.getDossierActionId(), DossierActionTerm.STATE_ALREADY_PROCESSED); // } catch (PortalException e) { // _log.error(e); // e.printStackTrace(); // } } if (Validator.isNull(dossier.getReleaseDate())) { // try { // DossierLocalServiceUtil.updateReleaseDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context); dossier.setReleaseDate(now); bResult.put(DossierTerm.RELEASE_DATE, true); // } catch (PortalException e) { // _log.error(e); // e.printStackTrace(); // } } } if (DossierTerm.DOSSIER_STATUS_PROCESSING.equals(curStatus) || DossierTerm.DOSSIER_STATUS_INTEROPERATING.equals(curStatus) || DossierTerm.DOSSIER_STATUS_WAITING.equals(curStatus)) { if (Validator.isNotNull(dossier.getFinishDate())) { dossier.setFinishDate(null); bResult.put(DossierTerm.FINISH_DATE, true); } if (Validator.isNotNull(dossier.getReleaseDate())) { dossier.setReleaseDate(null); bResult.put(DossierTerm.RELEASE_DATE, true); } } if (DossierTerm.DOSSIER_STATUS_RECEIVING.equals(prevStatus)) { bResult.put(DossierTerm.DOSSIER_NO, true); bResult.put(DossierTerm.RECEIVE_DATE, true); bResult.put(DossierTerm.PROCESS_DATE, true); bResult.put(DossierTerm.RELEASE_DATE, true); bResult.put(DossierTerm.FINISH_DATE, true); } if (DossierTerm.DOSSIER_STATUS_NEW.equals(prevStatus) && dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG && Validator.isNotNull(dossier.getReceiveDate())) { bResult.put(DossierTerm.RECEIVE_DATE, true); } int dateOption = actionConfig.getDateOption(); _log.debug("dateOption: "+dateOption); if (dateOption == DossierTerm.DATE_OPTION_CAL_WAITING) { DossierAction dActEnd = dossierActionLocalService .fetchDossierAction(dossierAction.getDossierActionId()); // DossierAction dActEnd = dossierAction; if (dActEnd != null) { _log.debug("dActEnd.getPreviousActionId(): "+dActEnd.getPreviousActionId()); DossierAction dActStart = dossierActionLocalService .fetchDossierAction(dActEnd.getPreviousActionId()); // DossierAction dActStart = prevAction; if (dActStart != null) { long createEnd = dActEnd.getCreateDate().getTime(); long createStart = dActStart.getCreateDate().getTime(); _log.debug("createStart: "+createStart); _log.debug("createEnd: "+createEnd); if (createEnd > createStart) { long extendDateTimeStamp = ExtendDueDateUtils.getTimeWaitingByHoliday(createStart, createEnd, dossier.getGroupId()); _log.debug("extendDateTimeStamp: "+extendDateTimeStamp); if (extendDateTimeStamp > 0) { long hoursCount = (long) (extendDateTimeStamp / (1000 * 60 * 60)); _log.debug("hoursCount: "+hoursCount); //_log.info("dossier.getExtendDate(): "+dossier.getExtendDate()); List<Holiday> holidayList = HolidayLocalServiceUtil .getHolidayByGroupIdAndType(dossier.getGroupId(), 0); List<Holiday> extendWorkDayList = HolidayLocalServiceUtil .getHolidayByGroupIdAndType(dossier.getGroupId(), 1); Date dueDateExtend = HolidayUtils.getEndDate(dossier.getGroupId(), dossier.getDueDate(), hoursCount, holidayList, extendWorkDayList); _log.debug("dueDateExtend: "+dueDateExtend); if (dueDateExtend != null) { dossier.setDueDate(dueDateExtend); //dossier.setCorrecttingDate(null); bResult.put(DossierTerm.DUE_DATE, true); } } } } } } else if (dateOption == DossierTerm.DATE_OPTION_CHANGE_DUE_DATE) { if (dossier.getDueDate() != null) { //dossier.setCorrecttingDate(dossier.getDueDate()); //dossier.setDueDate(null); dossier.setLockState(DossierTerm.PAUSE_STATE); } } else if (dateOption == DossierTerm.DATE_OPTION_RESET_DUE_DATE) { dossier.setLockState(StringPool.BLANK); if (dossier.getDueDate() != null) { if (serviceProcess != null) { Date newDueDate = HolidayUtils.getDueDate(new Date(), serviceProcess.getDurationCount(), serviceProcess.getDurationUnit(), dossier.getGroupId()); if (newDueDate != null) { dossier.setReceiveDate(new Date()); dossier.setDueDate(newDueDate); bResult.put(DossierTerm.DUE_DATE, true); } } } } //Check if dossier is done if (DossierTerm.DOSSIER_STATUS_DONE.equals(curStatus)) { List<DossierFile> lstFiles = dossierFileLocalService.getAllDossierFile(dossier.getDossierId()); for (DossierFile df : lstFiles) { if (!df.getRemoved()) { df.setOriginal(true); } dossierFileLocalService.updateDossierFile(df); } } //Calculate step due date // DossierAction dossierAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId()); // _log.info("dossierAction: "+dossierAction); dossierAction = dossierActionLocalService.fetchDossierAction(dossier.getDossierActionId()); Date rootDate = now; Date dueDate = null; // if (prevAction != null) { // if (prevAction.getDueDate() != null) { // if (rootDate.getTime() < prevAction.getDueDate().getTime()) { // rootDate = prevAction.getDueDate(); // } // } // } Double durationCount = processStep.getDurationCount(); // _log.info("durationCountStep: "+durationCount); int durationUnit = serviceProcess.getDurationUnit(); // _log.info("Calculate do action duration count: " + durationCount); if (Validator.isNotNull(durationCount) && durationCount > 0 && !areEqualDouble(durationCount, 0.00d, 3)) { // _log.info("========STEP DUE DATE CACULATE DUE DATE"); dueDate = HolidayUtils.getDueDate(rootDate, durationCount, durationUnit, dossier.getGroupId()); // _log.info("dueDateAction: "+dueDate); } // _log.info("========STEP DUE DATE:" + dueDate); // DossierLocalServiceUtil.updateDossier(dossier); // _log.info("dossierAction: " + dossierAction); if (dossierAction != null) { // _log.info("========STEP DUE DATE ACTION:" + dueDate); if (dueDate != null) { long dateNowTimeStamp = now.getTime(); Long dueDateTimeStamp = dueDate.getTime(); int overdue = 0; // _log.info("dueDateTEST: "+dueDate); // _log.info("Due date timestamp: " + dueDateTimeStamp); if (dueDateTimeStamp != null && dueDateTimeStamp > 0) { long subTimeStamp = dueDateTimeStamp - dateNowTimeStamp; if (subTimeStamp > 0) { overdue = calculatorOverDue(durationUnit, subTimeStamp); // overdue = calculatorOverDue(durationUnit, subTimeStamp, dateNowTimeStamp, dueDateTimeStamp, // dossierAction.getGroupId(), true); } else { overdue = -calculatorOverDue(durationUnit, subTimeStamp); //// calculatorOverDue(int durationUnit, long subTimeStamp, long releaseDateTimeStamp, //// long dueDateTimeStamp, long groupId, true); // overdue = -calculatorOverDue(durationUnit, subTimeStamp, dateNowTimeStamp, dueDateTimeStamp, // dossierAction.getGroupId(), true); } } else { } // _log.info("dueDateTEST111: "+dueDate); dossierAction.setActionOverdue(overdue); dossierAction.setDueDate(dueDate); // _log.info("========STEP DUE DATE SET DUE DATE: " + dossierAction.getStepCode()); // DossierAction dActTest = DossierActionLocalServiceUtil.updateDossierAction(dossierAction); dossierActionLocalService.updateDossierAction(dossierAction); // _log.info("dActTest: "+dActTest); } else { dossierActionLocalService.updateDossierAction(dossierAction); } } return bResult; } public static boolean areEqualDouble(double a, double b, int precision) { return Math.abs(a - b) <= Math.pow(10, -precision); } private static int calculatorOverDue(int durationUnit, long subTimeStamp) { if (subTimeStamp < 0) { subTimeStamp = Math.abs(subTimeStamp); } double dueCount; double overDue; int retval = Double.compare(durationUnit, 1.0); if (retval < 0) { dueCount = (double) subTimeStamp / VALUE_CONVERT_DATE_TIMESTAMP; double subDueCount = (double) Math.round(dueCount * 100) / 100; overDue = (double) Math.ceil(subDueCount * 4) / 4; return (int)overDue; } else { dueCount = (double) subTimeStamp / VALUE_CONVERT_HOUR_TIMESTAMP; overDue = (double) Math.round(dueCount); } return (int)overDue; } private JSONObject processMergeDossierFormData(Dossier dossier, JSONObject jsonData) { jsonData.put(DossierTerm.GOV_AGENCY_CODE, dossier.getGovAgencyCode()); jsonData.put(DossierTerm.GOV_AGENCY_NAME, dossier.getGovAgencyName()); jsonData.put(DossierTerm.APPLICANT_ID_NO, dossier.getApplicantIdNo()); jsonData.put(DossierTerm.APPLICANT_ID_TYPE, dossier.getApplicantIdType()); jsonData.put(DossierTerm.APPLICANT_ID_DATE, APIDateTimeUtils.convertDateToString(dossier.getApplicantIdDate(), APIDateTimeUtils._NORMAL_PARTTERN)); jsonData.put(DossierTerm.CITY_CODE, dossier.getCityCode()); jsonData.put(DossierTerm.CITY_NAME, dossier.getCityName()); jsonData.put(DossierTerm.DISTRICT_CODE, dossier.getDistrictCode()); jsonData.put(DossierTerm.DISTRICT_NAME, dossier.getDistrictName()); jsonData.put(DossierTerm.WARD_CODE, dossier.getWardCode()); jsonData.put(DossierTerm.WARD_NAME, dossier.getWardName()); jsonData.put(DossierTerm.DOSSIER_NO, dossier.getDossierNo()); jsonData.put(DossierTerm.APPLICANT_NAME, dossier.getApplicantName()); jsonData.put(DossierTerm.ADDRESS, dossier.getAddress()); jsonData.put(DossierTerm.CONTACT_TEL_NO, dossier.getContactTelNo()); jsonData.put(DossierTerm.CONTACT_EMAIL, dossier.getContactEmail()); jsonData.put(DossierTerm.CONTACT_NAME, dossier.getContactName()); jsonData.put(DossierTerm.DELEGATE_ADDRESS, dossier.getDelegateAddress()); jsonData.put(DossierTerm.SERVICE_CODE, dossier.getServiceCode()); jsonData.put(DossierTerm.SERVICE_NAME, dossier.getServiceName()); jsonData.put(DossierTerm.SAMPLE_COUNT, dossier.getSampleCount()); jsonData.put(DossierTerm.DURATION_UNIT, dossier.getDurationUnit()); jsonData.put(DossierTerm.DURATION_COUNT, dossier.getDurationCount()); jsonData.put(DossierTerm.SECRET_KEY, dossier.getPassword()); jsonData.put(DossierTerm.RECEIVE_DATE, APIDateTimeUtils.convertDateToString(dossier.getReceiveDate(), APIDateTimeUtils._NORMAL_PARTTERN)); jsonData.put(DossierTerm.DELEGATE_NAME, dossier.getDelegateName()); jsonData.put(DossierTerm.DELEGATE_EMAIL, dossier.getDelegateEmail()); jsonData.put(DossierTerm.DELEGATE_TELNO, dossier.getDelegateTelNo()); jsonData.put(DossierTerm.DOSSIER_NAME, dossier.getDossierName()); jsonData.put(DossierTerm.VIA_POSTAL, dossier.getViaPostal()); jsonData.put(DossierTerm.POSTAL_ADDRESS, dossier.getPostalAddress()); // Date dueDate = dossier.getDueDate(); if (dueDate != null) { ServiceProcess process = serviceProcessLocalService.getByG_PNO(dossier.getGroupId(), dossier.getProcessNo()); if (process != null) { String dueDatePattern = process.getDueDatePattern(); //_log.info("dueDatePattern: " + dueDatePattern); // _log.info("START DUEDATE TEST"); if (Validator.isNotNull(dueDatePattern)) { //_log.info("START DUEDATE TEST"); // _log.info("dueDatePattern: "+dueDatePattern); try { JSONObject jsonDueDate = JSONFactoryUtil.createJSONObject(dueDatePattern); //_log.info("jsonDueDate: " + jsonDueDate); if (jsonDueDate != null) { JSONObject hours = jsonDueDate.getJSONObject("hour"); JSONObject processHours = jsonDueDate.getJSONObject("processHour"); //_log.info("hours: " + hours); if (hours != null && hours.has("AM") && hours.has("PM")) { //_log.info("AM-PM: "); Calendar receiveCalendar = Calendar.getInstance(); receiveCalendar.setTime(dossier.getReceiveDate()); Calendar dueCalendar = Calendar.getInstance(); //_log.info("hours: " + receiveCalendar.get(Calendar.HOUR_OF_DAY)); if (receiveCalendar.get(Calendar.HOUR_OF_DAY) < 12) { dueCalendar.setTime(dossier.getDueDate()); String hoursAfterNoon = hours.getString("AM"); //_log.info("hoursAfterNoon: " + hoursAfterNoon); if (Validator.isNotNull(hoursAfterNoon)) { String[] splitAfter = StringUtil.split(hoursAfterNoon, StringPool.COLON); if (splitAfter != null) { dueCalendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(splitAfter[0])); dueCalendar.set(Calendar.MINUTE, Integer.valueOf(splitAfter[1])); } } } else { dueCalendar.setTime(dossier.getDueDate()); String hoursAfterNoon = hours.getString("PM"); if (Validator.isNotNull(hoursAfterNoon)) { String[] splitAfter = StringUtil.split(hoursAfterNoon, StringPool.COLON); if (splitAfter != null) { if (Integer.valueOf(splitAfter[0]) < 12) { dueCalendar.add(Calendar.DAY_OF_MONTH, 1); dueCalendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(splitAfter[0])); dueCalendar.set(Calendar.MINUTE, Integer.valueOf(splitAfter[1])); } else { //dueCalendar.add(Calendar.DAY_OF_MONTH, 1); dueCalendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(splitAfter[0])); dueCalendar.set(Calendar.MINUTE, Integer.valueOf(splitAfter[1])); } } } } jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils .convertDateToString(dueCalendar.getTime(), APIDateTimeUtils._NORMAL_PARTTERN)); } else if (processHours != null && processHours.has("startHour") && processHours.has("dueHour")) { //_log.info("STRART check new: "); Calendar receiveCalendar = Calendar.getInstance(); receiveCalendar.setTime(dossier.getReceiveDate()); // String receiveHour = processHours.getString("startHour"); //_log.info("receiveHour: " + receiveHour); if (Validator.isNotNull(receiveHour)) { String[] splitHour = StringUtil.split(receiveHour, StringPool.COLON); if (splitHour != null) { int hourStart = GetterUtil.getInteger(splitHour[0]); if (receiveCalendar.get(Calendar.HOUR_OF_DAY) < hourStart) { String[] splitdueHour = StringUtil.split(processHours.getString("dueHour"), StringPool.COLON); Calendar dueCalendar = Calendar.getInstance(); if (splitdueHour != null) { dueCalendar.set(Calendar.HOUR_OF_DAY, GetterUtil.getInteger(splitdueHour[0])); dueCalendar.set(Calendar.MINUTE, GetterUtil.getInteger(splitdueHour[1])); } else { jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils.convertDateToString( dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN)); } jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils.convertDateToString( dueCalendar.getTime(), APIDateTimeUtils._NORMAL_PARTTERN)); } else { jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils.convertDateToString( dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN)); } } } } else { jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils .convertDateToString(dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN)); } } else { jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils .convertDateToString(dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN)); } } catch (JSONException e) { _log.error(e); jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils.convertDateToString(dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN)); } } else { jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils.convertDateToString(dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN)); } } else { jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils.convertDateToString(dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN)); } } else { jsonData.put(DossierTerm.DUE_DATE, StringPool.BLANK); } // jsonData.put(DossierTerm.POSTAL_ADDRESS, dossier.getPostalAddress()); jsonData.put(DossierTerm.COUNTER, dossier.getCounter()); jsonData.put(DossierTerm.REGISTER_BOOK_CODE, dossier.getRegisterBookCode()); jsonData.put(DossierTerm.SECRET, dossier.getPassword()); jsonData.put(DossierTerm.BRIEF_NOTE, dossier.getBriefNote()); jsonData.put(DossierTerm.DOSSIER_ID, dossier.getDossierId()); // long groupId = dossier.getGroupId(); JSONArray dossierMarkArr = JSONFactoryUtil.createJSONArray(); long dossierId = dossier.getDossierId(); String templateNo = dossier.getDossierTemplateNo(); List<DossierMark> dossierMarkList = dossierMarkLocalService.getDossierMarksByFileMark(groupId, dossierId, 0); if (dossierMarkList != null && dossierMarkList.size() > 0) { JSONObject jsonMark = null; String partNo; for (DossierMark dossierMark : dossierMarkList) { jsonMark = JSONFactoryUtil.createJSONObject(); partNo = dossierMark.getDossierPartNo(); if (Validator.isNotNull(partNo)) { DossierPart part = dossierPartLocalService.getByTempAndPartNo(groupId, templateNo, partNo); if (part != null) { jsonMark.put(DossierPartTerm.DOSSIERPART_ID, part.getDossierPartId()); jsonMark.put(DossierPartTerm.PART_NAME, part.getPartName()); jsonMark.put(DossierPartTerm.PART_TIP, part.getPartTip()); jsonMark.put(DossierPartTerm.PART_TYPE, part.getPartType()); } } jsonMark.put(DossierPartTerm.PART_NO, partNo); jsonMark.put(DossierPartTerm.FILE_MARK, dossierMark.getFileMark()); jsonMark.put(DossierPartTerm.FILE_CHECK, dossierMark.getFileCheck()); jsonMark.put(DossierPartTerm.FILE_COMMENT, dossierMark.getFileComment()); // String strDossierMark = JSONFactoryUtil.looseSerialize(dossierMark); dossierMarkArr.put(jsonMark); } } //Hot fix TP99 DossierMark dossierMark = dossierMarkLocalService.getDossierMarkbyDossierId(groupId, dossierId, "TP99"); if (dossierMark != null) { JSONObject jsonMark = null; String partNo = dossierMark.getDossierPartNo(); if (Validator.isNotNull(partNo)) { List<DossierFile> fileList = dossierFileLocalService.getDossierFileByDID_DPNO(dossierId, partNo, false); DossierPart part = dossierPartLocalService.getByTempAndPartNo(groupId, templateNo, partNo); if (fileList != null && part != null) { for (DossierFile dossierFile : fileList) { jsonMark = JSONFactoryUtil.createJSONObject(); jsonMark.put(DossierPartTerm.PART_NAME, dossierFile.getDisplayName()); jsonMark.put(DossierPartTerm.DOSSIERPART_ID, part.getDossierPartId()); jsonMark.put(DossierPartTerm.PART_TIP, part.getPartTip()); jsonMark.put(DossierPartTerm.PART_TYPE, part.getPartType()); jsonMark.put(DossierPartTerm.PART_NO, partNo); jsonMark.put(DossierPartTerm.FILE_MARK, dossierMark.getFileMark()); jsonMark.put(DossierPartTerm.FILE_CHECK, dossierMark.getFileCheck()); jsonMark.put(DossierPartTerm.FILE_COMMENT, dossierMark.getFileComment()); // String strDossierMark = JSONFactoryUtil.looseSerialize(dossierMark); dossierMarkArr.put(jsonMark); } } } } jsonData.put(DossierTerm.DOSSIER_MARKS, dossierMarkArr); PaymentFile payment = paymentFileLocalService.getByDossierId(groupId, dossierId); if (payment != null) { jsonData.put(PaymentFileTerm.ADVANCE_AMOUNT, payment.getAdvanceAmount()); jsonData.put(PaymentFileTerm.PAYMENT_AMOUNT, payment.getPaymentAmount()); jsonData.put(PaymentFileTerm.PAYMENT_FEE, payment.getPaymentFee()); jsonData.put(PaymentFileTerm.SERVICE_AMOUNT, payment.getServiceAmount()); jsonData.put(PaymentFileTerm.SHIP_AMOUNT, payment.getShipAmount()); } if (dossier.getOriginality() == DossierTerm.ORIGINALITY_HOSONHOM) { JSONArray groupDossierArr = JSONFactoryUtil.createJSONArray(); List<Dossier> lstDossiers = dossierLocalService.findByG_GDID(groupId, dossier.getDossierId()); for (Dossier d : lstDossiers) { JSONObject dObject = JSONFactoryUtil.createJSONObject(); dObject.put(DossierTerm.DOSSIER_NO, d.getDossierNo()); dObject.put(DossierTerm.APPLICANT_NAME, d.getApplicantName()); dObject.put(DossierTerm.ADDRESS, d.getAddress()); dObject.put(DossierTerm.CONTACT_TEL_NO, d.getContactTelNo()); dObject.put(DossierTerm.CONTACT_EMAIL, d.getContactEmail()); dObject.put(DossierTerm.CONTACT_NAME, d.getContactName()); dObject.put(DossierTerm.DELEGATE_ADDRESS, d.getDelegateAddress()); dObject.put(DossierTerm.SERVICE_CODE, d.getServiceCode()); dObject.put(DossierTerm.SERVICE_NAME, d.getServiceName()); dObject.put(DossierTerm.SAMPLE_COUNT, d.getSampleCount()); dObject.put(DossierTerm.DURATION_UNIT, d.getDurationUnit()); dObject.put(DossierTerm.DURATION_COUNT, d.getDurationCount()); dObject.put(DossierTerm.SECRET_KEY, d.getPassword()); dObject.put(DossierTerm.RECEIVE_DATE, APIDateTimeUtils.convertDateToString(d.getReceiveDate(), APIDateTimeUtils._NORMAL_PARTTERN)); dObject.put(DossierTerm.DELEGATE_NAME, d.getDelegateName()); dObject.put(DossierTerm.DELEGATE_EMAIL, d.getDelegateEmail()); dObject.put(DossierTerm.DELEGATE_TELNO, d.getDelegateTelNo()); dObject.put(DossierTerm.DOSSIER_NAME, d.getDossierName()); dObject.put(DossierTerm.VIA_POSTAL, d.getViaPostal()); dObject.put(DossierTerm.POSTAL_ADDRESS, d.getPostalAddress()); groupDossierArr.put(dObject); } jsonData.put(DossierTerm.GROUP_DOSSIERS, groupDossierArr); } return jsonData; } //LamTV_ Mapping process dossier and formData private JSONObject processMergeDossierProcessRole(Dossier dossier, int length, JSONObject jsonData, DossierAction dAction) { // long groupId = dossier.getGroupId(); if (dAction != null) { long serviceProcessId = dAction.getServiceProcessId(); jsonData.put(DossierTerm.GOV_AGENCY_NAME, dossier.getGovAgencyName()); jsonData.put(DossierTerm.TOTAL, length); jsonData.put(DossierTerm.ACTION_USER, dAction.getActionUser()); String sequenceNo = dAction.getSequenceNo(); if (Validator.isNotNull(sequenceNo)) { ProcessSequence sequence = processSequenceLocalService.findBySID_SNO(groupId, serviceProcessId, sequenceNo); if (sequence != null) { jsonData.put(DossierTerm.SEQUENCE_ROLE, sequence.getSequenceRole()); } else { jsonData.put(DossierTerm.SEQUENCE_ROLE, StringPool.BLANK); } } else { jsonData.put(DossierTerm.SEQUENCE_ROLE, StringPool.BLANK); } // Process get Next sequence Role List<ProcessSequence> sequenceList = processSequenceLocalService.getByServiceProcess(groupId, serviceProcessId); String[] sequenceArr = null; if (sequenceList != null && !sequenceList.isEmpty()) { int lengthSeq = sequenceList.size(); sequenceArr = new String[lengthSeq]; for (int i = 0; i < lengthSeq; i++) { ProcessSequence processSequence = sequenceList.get(i); if (processSequence != null) { sequenceArr[i] = processSequence.getSequenceNo(); } } } if (sequenceArr != null && sequenceArr.length > 0) { for (int i = 0; i < sequenceArr.length; i++) { // _log.info("sequenceArr[i]: "+sequenceArr[i]); } Arrays.sort(sequenceArr); for (int i = 0; i < sequenceArr.length - 1; i++) { String seq = sequenceArr[i]; if (sequenceNo.equals(seq)) { String nextSequenceNo = sequenceArr[i + 1]; if (Validator.isNotNull(nextSequenceNo)) { ProcessSequence sequence = processSequenceLocalService.findBySID_SNO(groupId, serviceProcessId, nextSequenceNo); if (sequence != null) { jsonData.put(DossierTerm.NEXT_SEQUENCE_ROLE, sequence.getSequenceRole()); } else { jsonData.put(DossierTerm.NEXT_SEQUENCE_ROLE, StringPool.BLANK); } } else { jsonData.put(DossierTerm.NEXT_SEQUENCE_ROLE, StringPool.BLANK); } } } } else { jsonData.put(DossierTerm.NEXT_SEQUENCE_ROLE, StringPool.BLANK); } } return jsonData; } private void vnpostEvent(Dossier dossier) { Message message = new Message(); JSONObject msgData = JSONFactoryUtil.createJSONObject(); message.put("msgToEngine", msgData); message.put("dossier", DossierMgtUtils.convertDossierToJSON(dossier)); MessageBusUtil.sendMessage("vnpost/dossier/in/destination", message); } private void publishEvent(Dossier dossier, ServiceContext context) { if (dossier.getOriginDossierId() != 0 || Validator.isNotNull(dossier.getOriginDossierNo())) { return; } Message message = new Message(); JSONObject msgData = JSONFactoryUtil.createJSONObject(); message.put("msgToEngine", msgData); message.put("dossier", DossierMgtUtils.convertDossierToJSON(dossier)); // MessageBusUtil.sendMessage(DossierTerm.PUBLISH_DOSSIER_DESTINATION, message); Message lgspMessage = new Message(); JSONObject lgspMsgData = msgData; lgspMessage.put("msgToEngine", lgspMsgData); lgspMessage.put("dossier", DossierMgtUtils.convertDossierToJSON(dossier)); // MessageBusUtil.sendMessage(DossierTerm.LGSP_DOSSIER_DESTINATION, lgspMessage); //Add publish queue List<ServerConfig> lstScs = ServerConfigLocalServiceUtil.getByProtocol(dossier.getGroupId(), ServerConfigTerm.PUBLISH_PROTOCOL); for (ServerConfig sc : lstScs) { try { List<PublishQueue> lstQueues = PublishQueueLocalServiceUtil.getByG_DID_SN_ST(dossier.getGroupId(), dossier.getDossierId(), sc.getServerNo(), new int[] { PublishQueueTerm.STATE_WAITING_SYNC, PublishQueueTerm.STATE_ALREADY_SENT }); if (lstQueues == null || lstQueues.isEmpty()) { publishQueueLocalService.updatePublishQueue(dossier.getGroupId(), 0, dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context); } // PublishQueue pq = PublishQueueLocalServiceUtil.getByG_DID_SN(dossier.getGroupId(), dossier.getDossierId(), sc.getServerNo()); // if (pq == null) { // PublishQueueLocalServiceUtil.updatePublishQueue(dossier.getGroupId(), 0, dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context); // } // else { // if (pq.getStatus() == PublishQueueTerm.STATE_ACK_ERROR) { // PublishQueueLocalServiceUtil.updatePublishQueue(dossier.getGroupId(), pq.getPublishQueueId(), dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context); // } // } } catch (PortalException e) { _log.debug(e); } } lstScs = ServerConfigLocalServiceUtil.getByProtocol(dossier.getGroupId(), ServerConfigTerm.LGSP_PROTOCOL); for (ServerConfig sc : lstScs) { try { List<PublishQueue> lstQueues = publishQueueLocalService.getByG_DID_SN_ST(dossier.getGroupId(), dossier.getDossierId(), sc.getServerNo(), new int[] { PublishQueueTerm.STATE_WAITING_SYNC, PublishQueueTerm.STATE_ALREADY_SENT }); if (lstQueues == null || lstQueues.isEmpty()) { publishQueueLocalService.updatePublishQueue(dossier.getGroupId(), 0, dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context); } // PublishQueue pq = PublishQueueLocalServiceUtil.getByG_DID_SN(dossier.getGroupId(), dossier.getDossierId(), sc.getServerNo()); // if (pq == null) { // PublishQueueLocalServiceUtil.updatePublishQueue(dossier.getGroupId(), 0, dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context); // } // else { // if (pq.getStatus() == PublishQueueTerm.STATE_ACK_ERROR) { // PublishQueueLocalServiceUtil.updatePublishQueue(dossier.getGroupId(), pq.getPublishQueueId(), dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context); // } // } } catch (PortalException e) { _log.debug(e); } } } private ProcessOption getProcessOption(String serviceInfoCode, String govAgencyCode, String dossierTemplateNo, long groupId) throws PortalException { ServiceConfig config = serviceConfigLocalService.getBySICodeAndGAC(groupId, serviceInfoCode, govAgencyCode); return processOptionLocalService.getByDTPLNoAndServiceCF(groupId, dossierTemplateNo, config.getServiceConfigId()); } protected ProcessAction getProcessAction(long groupId, long dossierId, String refId, String actionCode, long serviceProcessId) throws PortalException { ProcessAction action = null; try { List<ProcessAction> actions = processActionLocalService.getByActionCode(groupId, actionCode, serviceProcessId); Dossier dossier = getDossier(groupId, dossierId, refId); String dossierStatus = dossier.getDossierStatus(); String dossierSubStatus = Validator.isNull(dossier.getDossierSubStatus()) ? StringPool.BLANK : dossier.getDossierSubStatus(); for (ProcessAction act : actions) { String preStepCode = act.getPreStepCode(); ProcessStep step = processStepLocalService.fetchBySC_GID(preStepCode, groupId, serviceProcessId); String subStepStatus = StringPool.BLANK; if (Validator.isNotNull(step)) { subStepStatus = Validator.isNull(step.getDossierSubStatus()) ? StringPool.BLANK : step.getDossierSubStatus(); } if (Validator.isNull(step)) { action = act; break; } else { if (step.getDossierStatus().contentEquals(dossierStatus) && subStepStatus.contentEquals(dossierSubStatus)) { action = act; break; } } } } catch (Exception e) { _log.debug(e); //_log.error(e); throw new NotFoundException("ProcessActionNotFoundException with actionCode= " + actionCode + "|serviceProcessId= " + serviceProcessId + "|referenceUid= " + refId + "|groupId= " + groupId); } return action; } protected Dossier getDossier(long groupId, long dossierId, String refId) throws PortalException { Dossier dossier = null; if (dossierId != 0) { dossier = dossierLocalService.fetchDossier(dossierId); } else { dossier = dossierLocalService.getByRef(groupId, refId); } return dossier; } private String generatorGoodCode(int length) { String tempGoodCode = _generatorUniqueString(length); String goodCode; while (_checkContainsGoodCode(tempGoodCode)) { tempGoodCode = _generatorUniqueString(length); } /* * while(_testCheck(tempGoodCode)) { tempGoodCode = * _generatorUniqueString(length); } */ goodCode = tempGoodCode; return goodCode; } private boolean _checkContainsGoodCode(String keypayGoodCode) { boolean isContains = false; try { PaymentFile paymentFile = null;//PaymentFileLocalServiceUtil.getByGoodCode(keypayGoodCode); if (Validator.isNotNull(paymentFile)) { isContains = true; } } catch (Exception e) { _log.error(e); isContains = true; } return isContains; } private DossierAction doActionOutsideProcess(long groupId, long userId, Dossier dossier, ActionConfig actionConfig, ProcessOption option, ProcessAction proAction, String actionCode, String actionUser, String actionNote, String payload, String assignUsers, String payment, int syncType, ServiceContext context) throws PortalException, SystemException, Exception { context.setUserId(userId); DossierAction dossierAction = null; String dossierStatus = dossier.getDossierStatus().toLowerCase(); if (Validator.isNotNull(dossierStatus) && !"new".equals(dossierStatus)) { dossier = dossierLocalService.updateDossier(dossier); } ServiceProcess serviceProcess = null; if (option != null) { long serviceProcessId = option.getServiceProcessId(); serviceProcess = serviceProcessLocalService.fetchServiceProcess(serviceProcessId); } dossierAction = dossierActionLocalService.fetchDossierAction(dossier.getDossierActionId()); // ActionConfig ac = actionConfigLocalService.getByCode(groupId, actionCode); ActionConfig ac = actionConfig; JSONObject payloadObject = JSONFactoryUtil.createJSONObject(payload); if (Validator.isNotNull(payload)) { if (DossierActionTerm.OUTSIDE_ACTION_9100.equals(actionCode)) { dossier = dossierLocalService.updateDossierSpecial(dossier.getDossierId(), payloadObject); } else { dossier = dossierLocalService.updateDossier(dossier.getDossierId(), payloadObject); } } if (DossierActionTerm.OUTSIDE_ACTION_ROLLBACK.equals(actionCode)) { if (dossierAction != null && dossierAction.isRollbackable()) { dossierActionLocalService.updateState(dossierAction.getDossierActionId(), DossierActionTerm.STATE_ROLLBACK); DossierAction previousAction = dossierActionLocalService.fetchDossierAction(dossierAction.getPreviousActionId()); if (previousAction != null) { dossierActionLocalService.updateState(previousAction.getDossierActionId(), DossierActionTerm.STATE_WAITING_PROCESSING); dossierActionLocalService.updateNextActionId(previousAction.getDossierActionId(), 0); dossierLocalService.rollback(dossier, previousAction); } else { dossierActionLocalService.removeAction(dossierAction.getDossierActionId()); dossier.setDossierActionId(0); dossierLocalService.updateDossier(dossier); } } } //Create DossierSync String dossierRefUid = dossier.getReferenceUid(); String syncRefUid = UUID.randomUUID().toString(); if (syncType > 0) { int state = DossierActionUtils.getSyncState(syncType, dossier); //Update payload if (Validator.isNotNull(dossier.getServerNo()) && dossier.getServerNo().split(StringPool.BLANK).length > 1) { String serverNo = dossier.getServerNo().split(StringPool.COMMA)[0].split(StringPool.AT)[0]; dossierSyncLocalService.updateDossierSync(groupId, userId, dossier.getDossierId(), dossierRefUid, syncRefUid, dossierAction.getPrimaryKey(), actionCode, ac.getActionName(), actionUser, actionNote, syncType, ac.getInfoType(), payloadObject.toJSONString(), serverNo, state); } else { dossierSyncLocalService.updateDossierSync(groupId, userId, dossier.getDossierId(), dossierRefUid, syncRefUid, dossierAction.getPrimaryKey(), actionCode, ac.getActionName(), actionUser, actionNote, syncType, ac.getInfoType(), payloadObject.toJSONString(), dossier.getServerNo(), state); } } if (ac != null && dossierAction != null) { //Only create dossier document if 2 && 3 if (dossier.getOriginality() != DossierTerm.ORIGINALITY_DVCTT) { if (Validator.isNotNull(ac.getDocumentType()) && !ac.getActionCode().startsWith("@")) { //Generate document DocumentType dt = documentTypeLocalService.getByTypeCode(groupId, ac.getDocumentType()); if (dt != null) { String documentCode = DocumentTypeNumberGenerator.generateDocumentTypeNumber(groupId, ac.getCompanyId(), dt.getDocumentTypeId()); DossierDocument dossierDocument = dossierDocumentLocalService.addDossierDoc(groupId, dossier.getDossierId(), UUID.randomUUID().toString(), dossierAction.getDossierActionId(), dt.getTypeCode(), dt.getDocumentName(), documentCode, 0L, dt.getDocSync(), context); //Generate PDF String formData = payload; JSONObject formDataObj = processMergeDossierFormData(dossier, JSONFactoryUtil.createJSONObject(formData)); // _log.info("Dossier document form data action outside: " + formDataObj.toJSONString()); Message message = new Message(); // _log.info("Document script: " + dt.getDocumentScript()); JSONObject msgData = JSONFactoryUtil.createJSONObject(); msgData.put("className", DossierDocument.class.getName()); msgData.put("classPK", dossierDocument.getDossierDocumentId()); msgData.put("jrxmlTemplate", dt.getDocumentScript()); msgData.put("formData", formDataObj.toJSONString()); msgData.put("userId", userId); message.put("msgToEngine", msgData); MessageBusUtil.sendMessage("jasper/engine/out/destination", message); } } } } if (ac != null && ac.getEventType() == ActionConfigTerm.EVENT_TYPE_SENT) { publishEvent(dossier, context); } if (OpenCPSConfigUtil.isNotificationEnable()) { createNotificationQueueOutsideProcess(userId, groupId, dossier, actionConfig, context); } if (DossierActionTerm.OUTSIDE_ACTION_ROLLBACK.equals(actionCode)) { if (dossier.getOriginDossierId() != 0) { Dossier hslt = dossierLocalService.fetchDossier(dossier.getOriginDossierId()); ProcessOption optionHslt = getProcessOption(hslt.getServiceCode(), hslt.getGovAgencyCode(), hslt.getDossierTemplateNo(), groupId); String actionUserHslt = actionUser; if (DossierTerm.DOSSIER_STATUS_NEW.equals(hslt.getDossierStatus())) { Date now = new Date(); hslt.setSubmitDate(now); hslt = dossierLocalService.updateDossier(hslt); try { JSONObject payloadObj = JSONFactoryUtil.createJSONObject(payload); payloadObj.put(DossierTerm.SUBMIT_DATE, now.getTime()); payload = payloadObj.toJSONString(); } catch (JSONException e) { _log.debug(e); } } doAction(groupId, userId, hslt, optionHslt, null, DossierActionTerm.OUTSIDE_ACTION_ROLLBACK, actionUserHslt, actionNote, payload, assignUsers, payment, 0, context); } } return dossierAction; } private void createNotificationQueueOutsideProcess(long userId, long groupId, Dossier dossier, ActionConfig actionConfig, ServiceContext context) { DossierAction dossierAction = dossierActionLocalService.fetchDossierAction(dossier.getDossierActionId()); User u = UserLocalServiceUtil.fetchUser(userId); JSONObject payloadObj = JSONFactoryUtil.createJSONObject(); try { payloadObj.put( "Dossier", JSONFactoryUtil.createJSONObject( JSONFactoryUtil.looseSerialize(dossier))); if (dossierAction != null) { payloadObj.put("actionCode", dossierAction.getActionCode()); payloadObj.put("actionUser", dossierAction.getActionUser()); payloadObj.put("actionName", dossierAction.getActionName()); payloadObj.put("actionNote", dossierAction.getActionNote()); } } catch (Exception e) { _log.error(e); } if (actionConfig != null && Validator.isNotNull(actionConfig.getNotificationType())) { Notificationtemplate notiTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, actionConfig.getNotificationType()); Date now = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(now); if (notiTemplate != null) { if ("minutely".equals(notiTemplate.getInterval())) { cal.add(Calendar.MINUTE, notiTemplate.getExpireDuration()); } else if ("hourly".equals(notiTemplate.getInterval())) { cal.add(Calendar.HOUR, notiTemplate.getExpireDuration()); } else { cal.add(Calendar.MINUTE, notiTemplate.getExpireDuration()); } Date expired = cal.getTime(); if (actionConfig.getNotificationType().startsWith("APLC")) { if (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA || dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) { try { Applicant applicant = ApplicantLocalServiceUtil.fetchByAppId(dossier.getApplicantIdNo()); long toUserId = (applicant != null ? applicant.getMappingUserId() : 0l); NotificationQueueLocalServiceUtil.addNotificationQueue( userId, groupId, actionConfig.getNotificationType(), Dossier.class.getName(), String.valueOf(dossier.getDossierId()), payloadObj.toJSONString(), u.getFullName(), dossier.getApplicantName(), toUserId, dossier.getContactEmail(), dossier.getContactTelNo(), now, expired, context); } catch (NoSuchUserException e) { _log.error(e); } } } else if (actionConfig.getNotificationType().startsWith("USER")) { } } } } /** * @param pattern * @param lenght * @return */ private String _generatorUniqueString(int lenght) { char[] chars = "0123456789".toCharArray(); StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < lenght; i++) { char c = chars[random.nextInt(chars.length)]; sb.append(c); } return sb.toString(); } private void assignDossierActionUser(Dossier dossier, int allowAssignUser, DossierAction dossierAction, long userId, long groupId, long assignUserId, JSONArray assignedUsers) throws PortalException { int moderator = 1; List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId()); HashMap<Long, DossierUser> mapDus = new HashMap<>(); for (DossierUser du : lstDus) { mapDus.put(du.getUserId(), du); } List<org.opencps.dossiermgt.model.DossierActionUser> lstDaus = dossierActionUserLocalService.getByDossierId(dossier.getDossierId()); HashMap<Long, Map<Long, org.opencps.dossiermgt.model.DossierActionUser>> mapDaus = new HashMap<>(); for (org.opencps.dossiermgt.model.DossierActionUser dau : lstDaus) { if (mapDaus.get(dau.getDossierActionId()) != null) { Map<Long, org.opencps.dossiermgt.model.DossierActionUser> temp = mapDaus.get(dau.getDossierActionId()); temp.put(dau.getUserId(), dau); } else { Map<Long, org.opencps.dossiermgt.model.DossierActionUser> temp = new HashMap<>(); temp.put(dau.getUserId(), dau); mapDaus.put(dau.getDossierActionId(), temp); } } for (int n = 0; n < assignedUsers.length(); n++) { JSONObject subUser = assignedUsers.getJSONObject(n); if (subUser != null && subUser.has(DossierActionUserTerm.ASSIGNED) && subUser.getInt(DossierActionUserTerm.ASSIGNED) == DossierActionUserTerm.ASSIGNED_TH) { DossierActionUserPK pk = new DossierActionUserPK(); long userIdAssigned = subUser.getLong("userId"); pk.setDossierActionId(dossierAction.getDossierActionId()); pk.setUserId(subUser.getLong("userId")); DossierUser dossierUser = null; dossierUser = mapDus.get(subUser.getLong("userId")); if (dossierUser != null) { //Update dossier user if assigned if (allowAssignUser != ProcessActionTerm.NOT_ASSIGNED) { dossierUser.setModerator(1); dossierUserLocalService.updateDossierUser(dossierUser.getDossierId(), dossierUser.getUserId(), dossierUser.getModerator(), dossierUser.getVisited()); // model.setModerator(dossierUser.getModerator()); moderator = dossierUser.getModerator(); } } else { if (allowAssignUser != ProcessActionTerm.NOT_ASSIGNED) { dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userIdAssigned, 1, true); } } // org.opencps.dossiermgt.model.DossierActionUser dau = DossierActionUserLocalServiceUtil.fetchDossierActionUser(pk); org.opencps.dossiermgt.model.DossierActionUser dau = null; // dau = mapDaus.get(userIdAssigned); if (mapDaus.get(dossierAction.getDossierActionId()) != null) { dau = mapDaus.get(dossierAction.getDossierActionId()).get(userIdAssigned); } if (Validator.isNull(dau)) { // DossierAction dAction = DossierActionLocalServiceUtil.fetchDossierAction(dossierAction.getDossierActionId()); DossierAction dAction = dossierAction; if (dAction != null) { addDossierActionUserByAssigned(allowAssignUser, userIdAssigned, dossierAction.getDossierActionId(), moderator, false, dAction.getStepCode(), dossier.getDossierId()); } else { addDossierActionUserByAssigned(allowAssignUser, userIdAssigned, dossierAction.getDossierActionId(), moderator, false, StringPool.BLANK, dossier.getDossierId()); } } else { dau.setModerator(1); dossierActionUserLocalService.updateDossierActionUser(dau); } } else if (subUser != null && subUser.has(DossierActionUserTerm.ASSIGNED) && subUser.getInt(DossierActionUserTerm.ASSIGNED) == DossierActionUserTerm.NOT_ASSIGNED) { // model = new org.opencps.dossiermgt.model.impl.DossierActionUserImpl(); DossierActionUserPK pk = new DossierActionUserPK(); pk.setDossierActionId(dossierAction.getDossierActionId()); pk.setUserId(subUser.getLong("userId")); org.opencps.dossiermgt.model.DossierActionUser dau = dossierActionUserLocalService.fetchDossierActionUser(pk); if (Validator.isNull(dau)) { } else { dau.setModerator(0); dossierActionUserLocalService.updateDossierActionUser(dau); } } } } private void addDossierActionUserByAssigned(int allowAssignUser, long userId, long dossierActionId, int moderator, boolean visited, String stepCode, long dossierId) { org.opencps.dossiermgt.model.DossierActionUser model = new org.opencps.dossiermgt.model.impl.DossierActionUserImpl(); int assigned = DossierActionUserTerm.NOT_ASSIGNED; model.setVisited(visited); model.setDossierId(dossierId); model.setStepCode(stepCode); //Check employee is exits and wokingStatus Employee employee = EmployeeLocalServiceUtil.fetchByFB_MUID(userId); _log.debug("Employee : " + employee); if (employee != null && employee.getWorkingStatus() == 1) { DossierActionUserPK pk = new DossierActionUserPK(dossierActionId, userId); org.opencps.dossiermgt.model.DossierActionUser dau = dossierActionUserLocalService.fetchDossierActionUser(pk); if (allowAssignUser == ProcessActionTerm.NOT_ASSIGNED) { model.setUserId(userId); model.setDossierActionId(dossierActionId); model.setModerator(moderator); if (moderator == 1) { model.setAssigned(1); } else { model.setAssigned(assigned); } // Add User // _log.info("Add assigned user by step role: " + model); if (dau == null) { dossierActionUserLocalService.addDossierActionUser(model); } else { if (dau.getModerator() != DossierActionUserTerm.ASSIGNED_TH && model.getModerator() == DossierActionUserTerm.ASSIGNED_TH) { dossierActionUserLocalService.updateDossierActionUser(model); } } } else if (allowAssignUser == ProcessActionTerm.ASSIGNED_TH) { _log.debug("Assign dau: " + userId); model.setUserId(userId); model.setDossierActionId(dossierActionId); model.setModerator(moderator); assigned = DossierActionUserTerm.ASSIGNED_TH; model.setAssigned(assigned); // Add User if (dau == null) { _log.debug("Assign add dau: " + userId); dossierActionUserLocalService.addDossierActionUser(model); } else { if (dau.getModerator() != DossierActionUserTerm.ASSIGNED_TH && model.getModerator() == DossierActionUserTerm.ASSIGNED_TH) { _log.debug("Assign update dau: " + userId); dossierActionUserLocalService.updateDossierActionUser(model); } } } else if (allowAssignUser == ProcessActionTerm.ASSIGNED_TH_PH) { model.setUserId(userId); model.setDossierActionId(dossierActionId); model.setModerator(moderator); assigned = DossierActionUserTerm.ASSIGNED_TH; model.setAssigned(assigned); // Add User dossierActionUserLocalService.addDossierActionUser(model); model.setUserId(userId); model.setDossierActionId(dossierActionId); model.setModerator(moderator); model.setVisited(true); assigned = DossierActionUserTerm.ASSIGNED_PH; model.setAssigned(assigned); // Add User if (dau == null) { dossierActionUserLocalService.addDossierActionUser(model); } else { if (dau.getModerator() != DossierActionUserTerm.ASSIGNED_TH && model.getModerator() == DossierActionUserTerm.ASSIGNED_TH) { dossierActionUserLocalService.updateDossierActionUser(model); } } } else if (allowAssignUser == ProcessActionTerm.ASSIGNED_TH_PH_TD) { model.setUserId(userId); model.setDossierActionId(dossierActionId); model.setModerator(moderator); assigned = DossierActionUserTerm.ASSIGNED_TH; model.setAssigned(assigned); // Add User dossierActionUserLocalService.addDossierActionUser(model); model.setUserId(userId); model.setDossierActionId(dossierActionId); model.setModerator(moderator); assigned = DossierActionUserTerm.ASSIGNED_PH; model.setAssigned(assigned); // Add User dossierActionUserLocalService.addDossierActionUser(model); model.setUserId(userId); model.setDossierActionId(dossierActionId); model.setModerator(moderator); assigned = DossierActionUserTerm.ASSIGNED_TD; model.setAssigned(assigned); // Add User if (dau == null) { dossierActionUserLocalService.addDossierActionUser(model); } else { if (dau.getModerator() != DossierActionUserTerm.ASSIGNED_TH && model.getModerator() == DossierActionUserTerm.ASSIGNED_TH) { dossierActionUserLocalService.updateDossierActionUser(model); } } } } } public void initDossierActionUser(ProcessAction processAction, Dossier dossier, int allowAssignUser, DossierAction dossierAction, long userId, long groupId, long assignUserId) throws PortalException { // Delete record in dossierActionUser List<org.opencps.dossiermgt.model.DossierActionUser> dossierActionUser = dossierActionUserLocalService .getListUser(dossierAction.getDossierActionId()); if (dossierActionUser != null && dossierActionUser.size() > 0) { dossierActionUserLocalService.deleteByDossierAction(dossierAction.getDossierActionId()); } long serviceProcessId = dossierAction.getServiceProcessId(); String stepCode = processAction.getPostStepCode(); // Get ProcessStep ProcessStep processStep = processStepLocalService.fetchBySC_GID(stepCode, groupId, serviceProcessId); long processStepId = processStep.getProcessStepId(); // Get List ProcessStepRole List<ProcessStepRole> listProcessStepRole = processStepRoleLocalService.findByP_S_ID(processStepId); ProcessStepRole processStepRole = null; List<DossierAction> lstStepActions = dossierActionLocalService.getByDID_FSC_NOT_DAI(dossier.getDossierId(), stepCode, dossierAction.getDossierActionId()); if (listProcessStepRole.size() != 0) { for (int i = 0; i < listProcessStepRole.size(); i++) { processStepRole = listProcessStepRole.get(i); long roleId = processStepRole.getRoleId(); boolean moderator = processStepRole.getModerator(); int mod = 0; if (moderator) { mod = 1; } // Get list user List<User> users = UserLocalServiceUtil.getRoleUsers(roleId); for (User user : users) { Employee employee = EmployeeLocalServiceUtil.fetchByFB_MUID(user.getUserId()); //_log.debug("Employee : " + employee); if (employee != null && employee.getWorkingStatus() == 1) { List<DossierAction> lstDoneActions = dossierActionLocalService .getByDID_U_FSC(dossier.getDossierId(), user.getUserId(), stepCode); if (!lstStepActions.isEmpty()) { if (!lstDoneActions.isEmpty()) mod = 1; else mod = 0; } updateDossierUser(dossier, processStepRole, user); addDossierActionUserByAssigned(processAction.getAllowAssignUser(), user.getUserId(), dossierAction.getDossierActionId(), mod, false, stepCode, dossier.getDossierId()); } } } } else { //Get role from service process initDossierActionUserByServiceProcessRole(dossier, allowAssignUser, dossierAction, userId, groupId, assignUserId); } } private void updateDossierUser(Dossier dossier, ProcessStepRole processStepRole, User user) { DossierUserPK pk = new DossierUserPK(); pk.setDossierId(dossier.getDossierId()); pk.setUserId(user.getUserId()); DossierUser du = dossierUserLocalService.fetchDossierUser(pk); if (du == null) { dossierUserLocalService.addDossierUser(dossier.getGroupId(), dossier.getDossierId(), user.getUserId(), processStepRole.getModerator() ? 1 : 0, true); } else { try { if ((processStepRole.getModerator() && du.getModerator() != DossierActionUserTerm.ASSIGNED_PH) || (!processStepRole.getModerator() && du.getModerator() != DossierActionUserTerm.ASSIGNED_PH)) { dossierUserLocalService.updateDossierUser(dossier.getDossierId(), user.getUserId(), du.getModerator() == 0 ? (processStepRole.getModerator() ? 1 : 0) : 1, true); } } catch (NoSuchDossierUserException e) { _log.error(e); } } } private void initDossierActionUserByServiceProcessRole(Dossier dossier, int allowAssignUser, DossierAction dossierAction, long userId, long groupId, long assignUserId) { try { ServiceProcess serviceProcess = serviceProcessLocalService.getServiceByCode(groupId, dossier.getServiceCode(), dossier.getGovAgencyCode(), dossier.getDossierTemplateNo()); List<ServiceProcessRole> listSprs = serviceProcessRoleLocalService.findByS_P_ID(serviceProcess.getServiceProcessId()); DossierAction da = dossierAction; for (ServiceProcessRole spr : listSprs) { int mod = 0; boolean moderator = spr.getModerator(); if (moderator) { mod = 1; } List<User> users = UserLocalServiceUtil.getRoleUsers(spr.getRoleId()); for (User user : users) { int assigned = user.getUserId() == assignUserId ? allowAssignUser : ProcessActionTerm.NOT_ASSIGNED; org.opencps.dossiermgt.model.DossierActionUser dau = dossierActionUserLocalService.getByDossierAndUser(dossierAction.getDossierActionId(), user.getUserId()); if (dau != null) { dau.setModerator(mod); if (moderator) { dau.setAssigned(1); } else { dau.setAssigned(assigned); } dossierActionUserLocalService.updateDossierActionUser(dau); } else { addDossierActionUserByAssigned(allowAssignUser, user.getUserId(), dossierAction.getDossierActionId(), mod, false, da.getStepCode(), dossier.getDossierId()); } } } } catch (PortalException e) { _log.error(e); } } private void copyRoleAsStep(ProcessStep curStep, Dossier dossier) { if (Validator.isNull(curStep.getRoleAsStep())) return; String[] stepCodeArr = StringUtil.split(curStep.getRoleAsStep()); if (stepCodeArr.length > 0) { for (String stepCode : stepCodeArr) { if (stepCode.startsWith("!")) { int index = stepCode.indexOf("!"); String stepCodePunc = stepCode.substring(index + 1); List<org.opencps.dossiermgt.model.DossierActionUser> lstDaus = dossierActionUserLocalService.getByDossierAndStepCode(dossier.getDossierId(), stepCodePunc); List<DossierAction> lstDossierActions = dossierActionLocalService.findDossierActionByDID_STEP(dossier.getDossierId(), stepCodePunc); try { for (org.opencps.dossiermgt.model.DossierActionUser dau : lstDaus) { boolean flagDA = false; for (DossierAction da : lstDossierActions) { if (da.getUserId() == dau.getUserId()) { flagDA = true; break; } } if (flagDA) { DossierUserPK duPk = new DossierUserPK(); duPk.setDossierId(dossier.getDossierId()); duPk.setUserId(dau.getUserId()); int moderator = dau.getModerator(); DossierUser duModel = dossierUserLocalService.fetchDossierUser(duPk); if (duModel == null) { dossierUserLocalService.addDossierUser(dossier.getGroupId(), dossier.getDossierId(), dau.getUserId(), moderator, true); } else { try { if (duModel.getModerator() == 0 && moderator == 1) { dossierUserLocalService.updateDossierUser(dossier.getDossierId(), dau.getUserId(), moderator, true); } } catch (NoSuchDossierUserException e) { // e.printStackTrace(); _log.error(e); } } DossierActionUserPK dauPk = new DossierActionUserPK(); dauPk.setDossierActionId(dossier.getDossierActionId()); dauPk.setUserId(dau.getUserId()); int assigned = moderator == 1 ? 1 : 0; dossierActionUserLocalService.addOrUpdateDossierActionUser(dau.getUserId(), dossier.getGroupId(), dossier.getDossierActionId(), dossier.getDossierId(), curStep.getStepCode(), moderator, assigned, true); } } } catch (Exception e) { _log.error(e); } } else { ServiceProcess serviceProcess = null; try { serviceProcess = serviceProcessLocalService.getServiceByCode(dossier.getGroupId(), dossier.getServiceCode(), dossier.getGovAgencyCode(), dossier.getDossierTemplateNo()); if (serviceProcess != null) { ProcessStep processStep = processStepLocalService.fetchBySC_GID(stepCode, dossier.getGroupId(), serviceProcess.getServiceProcessId()); if (processStep == null) continue; List<ProcessStepRole> lstRoles = processStepRoleLocalService.findByP_S_ID(processStep.getProcessStepId()); for (ProcessStepRole psr : lstRoles) { List<User> users = UserLocalServiceUtil.getRoleUsers(psr.getRoleId()); for (User u : users) { DossierUserPK duPk = new DossierUserPK(); duPk.setDossierId(dossier.getDossierId()); duPk.setUserId(u.getUserId()); int moderator = (psr.getModerator() ? 1 : 0); DossierUser duModel = dossierUserLocalService.fetchDossierUser(duPk); if (duModel == null) { dossierUserLocalService.addDossierUser(dossier.getGroupId(), dossier.getDossierId(), u.getUserId(), moderator, true); } else { try { if (duModel.getModerator() == 0 && moderator == 1) { dossierUserLocalService.updateDossierUser(dossier.getDossierId(), u.getUserId(), moderator, true); } } catch (NoSuchDossierUserException e) { _log.error(e); } } DossierActionUserPK dauPk = new DossierActionUserPK(); dauPk.setDossierActionId(dossier.getDossierActionId()); dauPk.setUserId(u.getUserId()); int assigned = moderator == 1 ? 1 : 0; dossierActionUserLocalService.addOrUpdateDossierActionUser(u.getUserId(), dossier.getGroupId(), dossier.getDossierActionId(), dossier.getDossierId(), curStep.getStepCode(), moderator, assigned, true); } } } } catch (PortalException e) { _log.error(e); } } } } } @Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class }) public Dossier addDossier(long groupId, Company company, User user, ServiceContext serviceContext, DossierInputModel input) throws UnauthenticationException, PortalException, Exception { BackendAuth auth = new BackendAuthImpl(); DossierPermission dossierPermission = new DossierPermission(); long start = System.currentTimeMillis(); if (!auth.isAuth(serviceContext)) { throw new UnauthenticationException(); } ProcessOption option = getProcessOption(input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo(), groupId); long serviceProcessId = 0; if (option != null) { serviceProcessId = option.getServiceProcessId(); } boolean flag = false; long userId = serviceContext.getUserId(); Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userId); if (employee != null) { long employeeId = employee.getEmployeeId(); if (employeeId > 0) { List<EmployeeJobPos> empJobList = EmployeeJobPosLocalServiceUtil.findByF_EmployeeId(employeeId); if (empJobList != null && empJobList.size() > 0) { for (EmployeeJobPos employeeJobPos : empJobList) { long jobPosId = employeeJobPos.getJobPostId(); if (jobPosId > 0) { JobPos job = JobPosLocalServiceUtil.fetchJobPos(jobPosId); if (job != null) { ServiceProcessRolePK pk = new ServiceProcessRolePK(serviceProcessId, job.getMappingRoleId()); ServiceProcessRole role = serviceProcessRoleLocalService .fetchServiceProcessRole(pk); if (role != null && role.getModerator()) { flag = true; break; } } } } } } } else { flag = true; } if (!flag) { throw new UnauthenticationException("No permission create dossier"); } _log.debug("CREATE DOSSIER 1: " + (System.currentTimeMillis() - start) + " ms"); dossierPermission.hasCreateDossier(groupId, user.getUserId(), input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo()); //int counter = DossierNumberGenerator.counterDossier(user.getUserId(), groupId); String referenceUid = input.getReferenceUid(); int counter = 0; // Create dossierNote ServiceProcess process = null; boolean online = GetterUtil.getBoolean(input.getOnline()); int originality = GetterUtil.getInteger(input.getOriginality()); Integer viaPostal = input.getViaPostal(); ServiceConfig config = serviceConfigLocalService.getBySICodeAndGAC(groupId, input.getServiceCode(), input.getGovAgencyCode()); if (config != null && Validator.isNotNull(viaPostal)) { viaPostal = config.getPostService() ? (viaPostal == 0 ? 1 : viaPostal) : 0; } else if (config != null) { viaPostal = config.getPostService() ? 1 : 0; } if (option != null) { process = serviceProcessLocalService.getServiceProcess(serviceProcessId); } if (process == null) { throw new NotFoundException("Cant find process"); } if (Validator.isNull(referenceUid) || referenceUid.trim().length() == 0) referenceUid = DossierNumberGenerator.generateReferenceUID(groupId); //Dossier checkDossier = dossierLocalService.getByRef(groupId, referenceUid); //if (checkDossier != null) { // return checkDossier; //} ServiceInfo service = serviceInfoLocalService.getByCode(groupId, input.getServiceCode()); String serviceName = StringPool.BLANK; if (service != null) { serviceName = service.getServiceName(); } String govAgencyName = getDictItemName(groupId, GOVERNMENT_AGENCY, input.getGovAgencyCode()); DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(ADMINISTRATIVE_REGION, groupId); String cityName = getDictItemName(groupId, dc, input.getCityCode()); String districtName = getDictItemName(groupId, dc, input.getDistrictCode()); String wardName = getDictItemName(groupId, dc, input.getWardCode()); // _log.info("Service code: " + input.getServiceCode()); _log.debug("===ADD DOSSIER CITY NAME:" + cityName); String password = StringPool.BLANK; if (Validator.isNotNull(input.getPassword())) { password = input.getPassword(); } else if (Validator.isNotNull(process.getGeneratePassword()) && process.getGeneratePassword()) { password = PwdGenerator.getPinNumber(); } String postalCityName = StringPool.BLANK; if (Validator.isNotNull(input.getPostalCityCode())) { postalCityName = getDictItemName(groupId, VNPOST_CITY_CODE, input.getPostalCityCode()); } Long sampleCount = (option != null ? option.getSampleCount() : 1l); // Process group dossier if (originality == 9) { _log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms"); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"); Date appIdDate = null; try { appIdDate = sdf.parse(input.getApplicantIdDate()); } catch (Exception e) { _log.debug(e); } Dossier dossier = dossierLocalService.initDossier(groupId, 0l, referenceUid, counter, input.getServiceCode(), serviceName, input.getGovAgencyCode(), govAgencyName, input.getApplicantName(), input.getApplicantIdType(), input.getApplicantIdNo(), appIdDate, input.getAddress(), input.getCityCode(), cityName, input.getDistrictCode(), districtName, input.getWardCode(), wardName, input.getContactName(), input.getContactTelNo(), input.getContactEmail(), input.getDossierTemplateNo(), password, viaPostal, input.getPostalAddress(), input.getPostalCityCode(), postalCityName, input.getPostalTelNo(), online, process.getDirectNotification(), input.getApplicantNote(), Integer.valueOf(input.getOriginality()), service, process, option, serviceContext); if (Validator.isNotNull(input.getDossierName())) { dossier.setDossierName(input.getDossierName()); } else { dossier.setDossierName(serviceName); } dossier.setSampleCount(sampleCount); if (Validator.isNotNull(input.getMetaData())) dossier.setMetaData(input.getMetaData()); updateDelegateApplicant(dossier, input); // Process update dossierNo // LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>(); // params.put(DossierTerm.GOV_AGENCY_CODE, dossier.getGovAgencyCode()); // params.put(DossierTerm.SERVICE_CODE, dossier.getServiceCode()); // params.put(DossierTerm.DOSSIER_TEMPLATE_NO, dossier.getDossierTemplateNo()); // params.put(DossierTerm.DOSSIER_STATUS, StringPool.BLANK); if (option != null) { //Process submition note dossier.setSubmissionNote(option.getSubmissionNote()); // String dossierRef = DossierNumberGenerator.generateDossierNumber(groupId, dossier.getCompanyId(), // dossier.getDossierId(), option.getProcessOptionId(), process.getDossierGroupPattern(), params); // dossier.setDossierNo(dossierRef.trim()); } dossier.setViaPostal(1); _log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms"); if (Validator.isNull(dossier)) { throw new NotFoundException("Can't add DOSSIER"); } _log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms"); //Create DossierMark _log.debug("originality: "+originality); String templateNo = dossier.getDossierTemplateNo(); _log.debug("templateNo: "+templateNo); if (Validator.isNotNull(input.getDossierMarkArr())) { JSONArray markArr = JSONFactoryUtil.createJSONArray(input.getDossierMarkArr()); if (markArr != null && markArr.length() > 0) { List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId()); Map<String, DossierMark> mapMarks = new HashMap<>(); for (DossierMark dm : lstMarks) { mapMarks.put(dm.getDossierPartNo(), dm); } for (int i = 0; i < markArr.length(); i++) { JSONObject jsonMark = markArr.getJSONObject(i); org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[markArr.length()]; org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel(); model.setDossierId(dossier.getDossierId()); model.setDossierPartNo(jsonMark.getString("partNo")); model.setFileCheck(0); model.setFileMark(jsonMark.getInt("fileMark")); model.setFileComment(StringPool.BLANK); model.setRecordCount(StringPool.BLANK); marks[i] = model; dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext); } } } else if (Validator.isNotNull(templateNo)) { List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo); // _log.info("partList: "+partList); if (partList != null && partList.size() > 0) { _log.debug("partList.size(): "+partList.size()); _log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms"); org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()]; int count = 0; List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId()); Map<String, DossierMark> mapMarks = new HashMap<>(); for (DossierMark dm : lstMarks) { mapMarks.put(dm.getDossierPartNo(), dm); } for (DossierPart dossierPart : partList) { int fileMark = dossierPart.getFileMark(); String dossierPartNo = dossierPart.getPartNo(); org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel(); model.setDossierId(dossier.getDossierId()); model.setDossierPartNo(dossierPartNo); model.setFileCheck(0); model.setFileMark(fileMark); model.setFileComment(StringPool.BLANK); model.setRecordCount(StringPool.BLANK); marks[count++] = model; } dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext); _log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms"); } } //Create dossier user List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId()); List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId()); if (lstDus.size() == 0) { DossierUserActions duActions = new DossierUserActionsImpl(); duActions.initDossierUser(groupId, dossier, process, lstProcessRoles); } // if (originality == DossierTerm.ORIGINALITY_DVCTT) { // dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true); // } _log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms"); //Add to dossier user based on service process role createDossierUsers(groupId, dossier, process, lstProcessRoles); if (Validator.isNotNull(input.getServerNo())) { dossier.setServerNo(input.getServerNo()); } _log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms"); return dossierLocalService.updateDossier(dossier); } else { List<Dossier> oldDossiers = dossierLocalService.getByU_G_GAC_SC_DTNO_DS_O( userId, groupId, input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo(), StringPool.BLANK, Integer.valueOf(input.getOriginality())); Dossier dossier = null; Dossier oldRefDossier = Validator.isNotNull(input.getReferenceUid()) ? dossierLocalService.getByRef(groupId, input.getReferenceUid()) : null; if (originality == DossierTerm.ORIGINALITY_DVCTT) { online = true; } boolean flagOldDossier = false; String registerBookCode = (option != null ? (Validator.isNotNull(option.getRegisterBookCode()) ? option.getRegisterBookCode() : StringPool.BLANK) : StringPool.BLANK); String registerBookName = (Validator.isNotNull(registerBookCode) ? getDictItemName(groupId, REGISTER_BOOK, registerBookCode) : StringPool.BLANK); _log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms"); if (oldRefDossier != null) { dossier = oldRefDossier; dossier.setSubmitDate(new Date()); ServiceProcess serviceProcess = process; double durationCount = 0; int durationUnit = 0; if (serviceProcess != null ) { durationCount = serviceProcess.getDurationCount(); durationUnit = serviceProcess.getDurationUnit(); dossier.setDurationCount(durationCount); dossier.setDurationUnit(durationUnit); } if (durationCount > 0) { Date dueDate = HolidayUtils.getDueDate(new Date(), durationCount, durationUnit, groupId); dossier.setDueDate(dueDate); } } else if (oldDossiers.size() > 0) { flagOldDossier = true; dossier = oldDossiers.get(0); dossier.setApplicantName(input.getApplicantName()); dossier.setApplicantNote(input.getApplicantNote()); dossier.setApplicantIdNo(input.getApplicantIdNo()); dossier.setAddress(input.getAddress()); dossier.setContactEmail(input.getContactEmail()); dossier.setContactName(input.getContactName()); dossier.setContactTelNo(input.getContactTelNo()); dossier.setDelegateName(input.getDelegateName()); dossier.setDelegateEmail(input.getDelegateEmail()); dossier.setDelegateAddress(input.getDelegateAddress()); dossier.setPostalAddress(input.getPostalAddress()); dossier.setPostalCityCode(input.getPostalCityCode()); dossier.setPostalCityName(postalCityName); dossier.setPostalTelNo(input.getPostalTelNo()); dossier.setPostalServiceCode(input.getPostalServiceCode()); dossier.setPostalServiceName(input.getPostalServiceName()); dossier.setPostalDistrictCode(input.getPostalDistrictCode()); dossier.setPostalDistrictName(input.getPostalDistrictName()); dossier.setPostalWardCode(input.getPostalWardCode()); dossier.setPostalWardName(input.getPostalWardName()); dossier.setPostalTelNo(input.getPostalTelNo()); dossier.setViaPostal(viaPostal); dossier.setOriginDossierNo(input.getOriginDossierNo()); dossier.setRegisterBookCode(registerBookCode); dossier.setRegisterBookName(registerBookName); dossier.setSampleCount(sampleCount); dossier.setServiceCode(input.getServiceCode()); dossier.setGovAgencyCode(input.getGovAgencyCode()); dossier.setDossierTemplateNo(input.getDossierTemplateNo()); updateDelegateApplicant(dossier, input); // dossier.setDossierNo(input.getDossierNo()); dossier.setSubmitDate(new Date()); // ServiceProcess serviceProcess = ServiceProcessLocalServiceUtil.fetchServiceProcess(serviceProcessId); ServiceProcess serviceProcess = process; double durationCount = 0; int durationUnit = 0; if (serviceProcess != null ) { durationCount = serviceProcess.getDurationCount(); durationUnit = serviceProcess.getDurationUnit(); dossier.setDurationCount(durationCount); dossier.setDurationUnit(durationUnit); } if (durationCount > 0) { Date dueDate = HolidayUtils.getDueDate(new Date(), durationCount, durationUnit, groupId); dossier.setDueDate(dueDate); } dossier.setOnline(online); if (Validator.isNotNull(input.getDossierName())) dossier.setDossierName(input.getDossierName()); if (serviceProcess != null) { dossier.setProcessNo(serviceProcess.getProcessNo()); } // dossier = DossierLocalServiceUtil.updateDossier(dossier); } else { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Date appIdDate = null; try { appIdDate = sdf.parse(input.getApplicantIdDate()); } catch (Exception e) { _log.debug(e); } dossier = dossierLocalService.initDossier(groupId, 0l, referenceUid, counter, input.getServiceCode(), serviceName, input.getGovAgencyCode(), govAgencyName, input.getApplicantName(), input.getApplicantIdType(), input.getApplicantIdNo(), appIdDate, input.getAddress(), input.getCityCode(), cityName, input.getDistrictCode(), districtName, input.getWardCode(), wardName, input.getContactName(), input.getContactTelNo(), input.getContactEmail(), input.getDossierTemplateNo(), password, viaPostal, input.getPostalAddress(), input.getPostalCityCode(), postalCityName, input.getPostalTelNo(), online, process.getDirectNotification(), input.getApplicantNote(), Integer.valueOf(input.getOriginality()), service, process, option, serviceContext); dossier.setDelegateName(input.getDelegateName()); dossier.setDelegateEmail(input.getDelegateEmail()); dossier.setDelegateAddress(input.getDelegateAddress()); if (Validator.isNotNull(input.getDossierName())) { dossier.setDossierName(input.getDossierName()); } else { dossier.setDossierName(serviceName); } dossier.setPostalCityName(postalCityName); dossier.setPostalTelNo(input.getPostalTelNo()); dossier.setPostalServiceCode(input.getPostalServiceCode()); dossier.setPostalServiceName(input.getPostalServiceName()); dossier.setPostalDistrictCode(input.getPostalDistrictCode()); dossier.setPostalDistrictName(input.getPostalDistrictName()); dossier.setPostalWardCode(input.getPostalWardCode()); dossier.setPostalWardName(input.getPostalWardName()); dossier.setOriginDossierNo(input.getOriginDossierNo()); dossier.setRegisterBookCode(registerBookCode); dossier.setRegisterBookName(registerBookName); dossier.setSampleCount(sampleCount); if (Validator.isNotNull(input.getMetaData())) dossier.setMetaData(input.getMetaData()); updateDelegateApplicant(dossier, input); if (process != null) { dossier.setProcessNo(process.getProcessNo()); } // dossier = DossierLocalServiceUtil.updateDossier(dossier); } _log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms"); if (originality != DossierTerm.ORIGINALITY_LIENTHONG) { Applicant applicant = ApplicantLocalServiceUtil.fetchByMappingID(serviceContext.getUserId()); if (applicant != null) { updateApplicantInfo(dossier, applicant.getApplicantIdDate(), applicant.getApplicantIdNo(), applicant.getApplicantIdType(), applicant.getApplicantName(), applicant.getAddress(), applicant.getCityCode(), applicant.getCityName(), applicant.getDistrictCode(), applicant.getDistrictName(), applicant.getWardCode(), applicant.getWardName(), applicant.getContactEmail(), applicant.getContactTelNo() ); } } if (Validator.isNull(dossier)) { throw new NotFoundException("Cant add DOSSIER"); } _log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms"); //Create DossierMark _log.debug("flagOldDossier: "+flagOldDossier); _log.debug("originality: "+originality); if ((originality == DossierTerm.ORIGINALITY_MOTCUA || originality == DossierTerm.ORIGINALITY_LIENTHONG) && !flagOldDossier) { String templateNo = dossier.getDossierTemplateNo(); _log.debug("templateNo: "+templateNo); if (Validator.isNotNull(templateNo)) { List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo); // _log.info("partList: "+partList); if (partList != null && partList.size() > 0) { _log.debug("partList.size(): "+partList.size()); _log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms"); org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()]; int count = 0; List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId()); Map<String, DossierMark> mapMarks = new HashMap<>(); for (DossierMark dm : lstMarks) { mapMarks.put(dm.getDossierPartNo(), dm); } for (DossierPart dossierPart : partList) { int fileMark = dossierPart.getFileMark(); String dossierPartNo = dossierPart.getPartNo(); org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel(); model.setDossierId(dossier.getDossierId()); model.setDossierPartNo(dossierPartNo); model.setFileCheck(0); model.setFileMark(fileMark); model.setFileComment(StringPool.BLANK); marks[count++] = model; // DossierMarkLocalServiceUtil.addDossierMark(groupId, dossier.getDossierId(), dossierPartNo, // fileMark, 0, StringPool.BLANK, serviceContext); } dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext); _log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms"); } } } //Create dossier user List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId()); List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId()); if (lstDus.size() == 0) { DossierUserActions duActions = new DossierUserActionsImpl(); // duActions.initDossierUser(groupId, dossier); duActions.initDossierUser(groupId, dossier, process, lstProcessRoles); } if (originality == DossierTerm.ORIGINALITY_DVCTT) { dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true); } _log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms"); // DossierLocalServiceUtil.updateDossier(dossier); if (dossier != null) { // long notificationQueueId = CounterLocalServiceUtil.increment(NotificationQueue.class.getName()); NotificationQueue queue = NotificationQueueLocalServiceUtil.createNotificationQueue(notificationQueueId); //Process add notification queue Date now = new Date(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) + 1); queue.setCreateDate(now); queue.setModifiedDate(now); queue.setGroupId(groupId); queue.setCompanyId(company.getCompanyId()); queue.setNotificationType(NotificationType.DOSSIER_01); queue.setClassName(Dossier.class.getName()); queue.setClassPK(String.valueOf(dossier.getPrimaryKey())); queue.setToUsername(dossier.getUserName()); queue.setToUserId(dossier.getUserId()); queue.setToEmail(dossier.getContactEmail()); queue.setToTelNo(dossier.getContactTelNo()); JSONObject payload = JSONFactoryUtil.createJSONObject(); try { // _log.info("START PAYLOAD: "); payload.put( "Dossier", JSONFactoryUtil.createJSONObject( JSONFactoryUtil.looseSerialize(dossier))); } catch (JSONException parse) { _log.error(parse); } // _log.info("payloadTest: "+payload.toJSONString()); queue.setPayload(payload.toJSONString()); queue.setExpireDate(cal.getTime()); NotificationQueueLocalServiceUtil.addNotificationQueue(queue); } _log.debug("CREATE DOSSIER 6: " + (System.currentTimeMillis() - start) + " ms"); //Add to dossier user based on service process role createDossierUsers(groupId, dossier, process, lstProcessRoles); if (Validator.isNotNull(input.getServerNo())) { dossier.setServerNo(input.getServerNo()); } _log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms"); dossierLocalService.updateDossier(dossier); _log.debug("CREATE DOSSIER 8: " + (System.currentTimeMillis() - start) + " ms"); return dossier; } } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = { SystemException.class, PortalException.class, Exception.class }) public Dossier addMultipleDossier(long groupId, Company company, User user, ServiceContext serviceContext, DossierMultipleInputModel input) throws UnauthenticationException, PortalException, Exception { BackendAuth auth = new BackendAuthImpl(); DossierPermission dossierPermission = new DossierPermission(); long start = System.currentTimeMillis(); if (!auth.isAuth(serviceContext)) { throw new UnauthenticationException(); } ProcessOption option = getProcessOption(input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo(), groupId); long serviceProcessId = 0; if (option != null) { serviceProcessId = option.getServiceProcessId(); } boolean flag = false; long userId = serviceContext.getUserId(); Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userId); if (employee != null) { long employeeId = employee.getEmployeeId(); if (employeeId > 0) { List<EmployeeJobPos> empJobList = EmployeeJobPosLocalServiceUtil.findByF_EmployeeId(employeeId); if (empJobList != null && empJobList.size() > 0) { for (EmployeeJobPos employeeJobPos : empJobList) { long jobPosId = employeeJobPos.getJobPostId(); if (jobPosId > 0) { JobPos job = JobPosLocalServiceUtil.fetchJobPos(jobPosId); if (job != null) { ServiceProcessRolePK pk = new ServiceProcessRolePK(serviceProcessId, job.getMappingRoleId()); ServiceProcessRole role = serviceProcessRoleLocalService .fetchServiceProcessRole(pk); if (role != null && role.getModerator()) { flag = true; break; } } } } } } } else { flag = true; } if (!flag) { throw new UnauthenticationException("No permission create dossier"); } _log.debug("CREATE DOSSIER 1: " + (System.currentTimeMillis() - start) + " ms"); dossierPermission.hasCreateDossier(groupId, user.getUserId(), input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo()); Dossier dossier = null; if (Validator.isNotNull(input.getDossiers())) { JSONObject jsonDossier = JSONFactoryUtil.createJSONObject(input.getDossiers()); //Get params input dossier String referenceUid = jsonDossier.getString(DossierTerm.REFERENCE_UID); if (Validator.isNull(referenceUid) || referenceUid.trim().length() == 0) referenceUid = DossierNumberGenerator.generateReferenceUID(groupId); int counter = 0; //boolean online = GetterUtil.getBoolean(input.getOnline()); boolean online = false; int originality = input.getOriginality(); int viaPostal = Validator.isNotNull(jsonDossier.getString(DossierTerm.VIA_POSTAL)) ? GetterUtil.getInteger(jsonDossier.getString(DossierTerm.VIA_POSTAL)): 0; ServiceConfig config = serviceConfigLocalService.getBySICodeAndGAC(groupId, input.getServiceCode(), input.getGovAgencyCode()); if (config != null && Validator.isNotNull(viaPostal)) { viaPostal = config.getPostService() ? (viaPostal == 0 ? 1 : viaPostal) : 0; } else if (config != null) { viaPostal = config.getPostService() ? 1 : 0; } //Get service process ServiceProcess process = null; if (option != null) { process = serviceProcessLocalService.getServiceProcess(serviceProcessId); if (process == null) { throw new NotFoundException("Cant find process"); } } ServiceInfo service = serviceInfoLocalService.getByCode(groupId, input.getServiceCode()); String serviceName = service != null ? service.getServiceName(): StringPool.BLANK; String govAgencyName = getDictItemName(groupId, GOVERNMENT_AGENCY, input.getGovAgencyCode()); //DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(ADMINISTRATIVE_REGION, groupId); //String cityName = getDictItemName(groupId, dc, input.getCityCode()); //String districtName = getDictItemName(groupId, dc, input.getDistrictCode()); //String wardName = getDictItemName(groupId, dc, input.getWardCode()); // _log.info("Service code: " + input.getServiceCode()); //_log.debug("===ADD DOSSIER CITY NAME:" + cityName); String password = StringPool.BLANK; if (Validator.isNotNull(jsonDossier.getString("password"))) { password = jsonDossier.getString("password"); } else if (Validator.isNotNull(process.getGeneratePassword()) && process.getGeneratePassword()) { password = PwdGenerator.getPinNumber(); } String postalCityName = StringPool.BLANK; if (Validator.isNotNull(jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE))) { postalCityName = getDictItemName(groupId, VNPOST_CITY_CODE, jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE)); } int sampleCount = (option != null ? (int) option.getSampleCount() : 1); String registerBookCode = (option != null ? (Validator.isNotNull(option.getRegisterBookCode()) ? option.getRegisterBookCode() : StringPool.BLANK) : StringPool.BLANK); String registerBookName = (Validator.isNotNull(registerBookCode) ? getDictItemName(groupId, REGISTER_BOOK, registerBookCode) : StringPool.BLANK); _log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms"); Long appIdDateLong = jsonDossier.getLong(DossierTerm.APPLICANT_ID_DATE); Date appIdDate = null; if (appIdDateLong > 0) { appIdDate = new Date(appIdDateLong); } // Params add dossier String applicantName = jsonDossier.getString(DossierTerm.APPLICANT_NAME); String applicantIdType = jsonDossier.getString(DossierTerm.APPLICANT_ID_TYPE); String applicantIdNo = jsonDossier.getString(DossierTerm.APPLICANT_ID_NO); String address = jsonDossier.getString(DossierTerm.ADDRESS); String contactName = jsonDossier.getString(DossierTerm.CONTACT_NAME); String contactTelNo = jsonDossier.getString(DossierTerm.CONTACT_TEL_NO); String contactEmail = jsonDossier.getString(DossierTerm.CONTACT_EMAIL); // String postalServiceCode = jsonDossier.getString(DossierTerm.POSTAL_SERVICE_CODE); String postalServiceName = jsonDossier.getString(DossierTerm.POSTAL_SERVICE_NAME); String postalAddress = jsonDossier.getString(DossierTerm.POSTAL_ADDRESS); String postalCityCode = jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE); String postalDistrictCode = jsonDossier.getString(DossierTerm.POSTAL_DISTRICT_CODE); String postalDistrictName = jsonDossier.getString(DossierTerm.POSTAL_DISTRICT_NAME); String postalWardCode = jsonDossier.getString(DossierTerm.POSTAL_WARD_CODE); String postalWardName = jsonDossier.getString(DossierTerm.POSTAL_WARD_NAME); String postalTelNo = jsonDossier.getString(DossierTerm.POSTAL_TEL_NO); String applicantNote = jsonDossier.getString(DossierTerm.APPLICANT_NOTE); String delegateIdNo = jsonDossier.getString(DossierTerm.DELEGATE_ID_NO); String delegateName = jsonDossier.getString(DossierTerm.DELEGATE_NAME); String delegateTelNo = jsonDossier.getString(DossierTerm.DELEGATE_TELNO); String delegateEmail = jsonDossier.getString(DossierTerm.DELEGATE_EMAIL); String delegateAddress = jsonDossier.getString(DossierTerm.DELEGATE_ADDRESS); //TODO String delegateCityCode = jsonDossier.getString(DossierTerm.DELEGATE_CITYCODE); String delegateCityName = StringPool.BLANK; if (Validator.isNotNull(delegateCityCode)) { delegateCityName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateCityCode); } String delegateDistrictCode = jsonDossier.getString(DossierTerm.DELEGATE_DISTRICTCODE); String delegateDistrictName = StringPool.BLANK; if (Validator.isNotNull(delegateDistrictCode)) { delegateDistrictName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateDistrictCode); } String delegateWardCode = jsonDossier.getString(DossierTerm.DELEGATE_WARDCODE); String delegateWardName = StringPool.BLANK; if (Validator.isNotNull(delegateWardCode)) { delegateWardName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateWardCode); } // String dossierName = Validator.isNotNull(jsonDossier.getString(DossierTerm.DOSSIER_NAME)) ? jsonDossier.getString(DossierTerm.DOSSIER_NAME) : serviceName; Long receiveDateTimeStamp = jsonDossier.getLong(DossierTerm.RECEIVE_DATE); Date receiveDate = null; if (receiveDateTimeStamp > 0) { receiveDate = new Date(receiveDateTimeStamp); } Long dueDateTimeStamp = jsonDossier.getLong(DossierTerm.DUE_DATE); Date dueDate = null; if (dueDateTimeStamp > 0) { dueDate = new Date(dueDateTimeStamp); } String metaData = jsonDossier.getString(DossierTerm.META_DATA); dossier = dossierLocalService.initMultipleDossier(groupId, 0l, referenceUid, counter, input.getServiceCode(), serviceName, input.getGovAgencyCode(), govAgencyName, applicantName, applicantIdType, applicantIdNo, appIdDate, address, contactName, contactTelNo, contactEmail, input.getDossierTemplateNo(), password, viaPostal, postalServiceCode, postalServiceName, postalAddress, postalCityCode, postalCityName, postalDistrictCode, postalDistrictName, postalWardCode, postalWardName, postalTelNo, online, process.getDirectNotification(), applicantNote, input.getOriginality(), delegateIdNo, delegateName, delegateTelNo, delegateEmail, delegateAddress, delegateCityCode, delegateCityName, delegateDistrictCode, delegateDistrictName, delegateWardCode, delegateWardName, registerBookCode, registerBookName, sampleCount, dossierName, service, process, option, serviceContext); if (receiveDate != null) dossier.setReceiveDate(receiveDate); if (dueDate != null) dossier.setDueDate(dueDate); if (Validator.isNotNull(metaData)) dossier.setMetaData(metaData); //TODO: Process then //updateDelegateApplicant(dossier, input); _log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms"); if (originality != DossierTerm.ORIGINALITY_LIENTHONG) { Applicant applicant = ApplicantLocalServiceUtil.fetchByMappingID(serviceContext.getUserId()); if (applicant != null) { updateApplicantInfo(dossier, applicant.getApplicantIdDate(), applicant.getApplicantIdNo(), applicant.getApplicantIdType(), applicant.getApplicantName(), applicant.getAddress(), applicant.getCityCode(), applicant.getCityName(), applicant.getDistrictCode(), applicant.getDistrictName(), applicant.getWardCode(), applicant.getWardName(), applicant.getContactEmail(), applicant.getContactTelNo() ); } } if (Validator.isNull(dossier)) { throw new NotFoundException("Cant add DOSSIER"); } _log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms"); //TODO /** Create DossierMark */ //_log.debug("flagOldDossier: "+flagOldDossier); _log.debug("originality: "+originality); String templateNo = dossier.getDossierTemplateNo(); _log.debug("templateNo: "+templateNo); long dossierId = dossier.getDossierId(); if (originality == DossierTerm.ORIGINALITY_MOTCUA || originality == DossierTerm.ORIGINALITY_LIENTHONG) { if (Validator.isNotNull(input.getDossierMarkArr())) { JSONArray markArr = JSONFactoryUtil.createJSONArray(input.getDossierMarkArr()); if (markArr != null && markArr.length() > 0) { List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossierId); Map<String, DossierMark> mapMarks = new HashMap<>(); for (DossierMark dm : lstMarks) { mapMarks.put(dm.getDossierPartNo(), dm); } org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[markArr.length()]; for (int i = 0; i < markArr.length(); i++) { JSONObject jsonMark = markArr.getJSONObject(i); //System.out.println("jsonMark: "+jsonMark); org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel(); model.setDossierId(dossier.getDossierId()); model.setDossierPartNo(jsonMark.getString("partNo")); model.setFileCheck(0); model.setFileMark(jsonMark.getInt("fileMark")); model.setFileComment(StringPool.BLANK); model.setRecordCount(StringPool.BLANK); marks[i] = model; } dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext); } } else if (Validator.isNotNull(templateNo)) { List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo); // _log.info("partList: "+partList); if (partList != null && partList.size() > 0) { _log.debug("partList.size(): "+partList.size()); _log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms"); org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()]; int count = 0; List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossierId); Map<String, DossierMark> mapMarks = new HashMap<>(); for (DossierMark dm : lstMarks) { mapMarks.put(dm.getDossierPartNo(), dm); } for (DossierPart dossierPart : partList) { int fileMark = dossierPart.getFileMark(); String dossierPartNo = dossierPart.getPartNo(); org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel(); model.setDossierId(dossier.getDossierId()); model.setDossierPartNo(dossierPartNo); model.setFileCheck(0); model.setFileMark(fileMark); model.setFileComment(StringPool.BLANK); model.setRecordCount(StringPool.BLANK); marks[count++] = model; } dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext); _log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms"); } } } /** * Add dossier file */ String strDossierFileId = input.getDossierFileArr(); if (Validator.isNotNull(strDossierFileId)) { String[] splitDossierFileId = strDossierFileId.split(StringPool.COMMA); if (splitDossierFileId != null && splitDossierFileId.length > 0) { for (String strFileId : splitDossierFileId) { processCloneDossierFile(Long.valueOf(strFileId), dossier.getDossierId(), userId); } } } /**Create dossier user */ List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId()); List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId()); if (lstDus.size() == 0) { DossierUserActions duActions = new DossierUserActionsImpl(); duActions.initDossierUser(groupId, dossier, process, lstProcessRoles); } if (originality == DossierTerm.ORIGINALITY_DVCTT) { dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true); } _log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms"); // if (dossier != null) { // // // long notificationQueueId = CounterLocalServiceUtil.increment(NotificationQueue.class.getName()); // // NotificationQueue queue = NotificationQueueLocalServiceUtil.createNotificationQueue(notificationQueueId); // //Process add notification queue // Date now = new Date(); // // Calendar cal = Calendar.getInstance(); // cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) + 1); // // queue.setCreateDate(now); // queue.setModifiedDate(now); // queue.setGroupId(groupId); // queue.setCompanyId(company.getCompanyId()); // // queue.setNotificationType(NotificationType.DOSSIER_01); // queue.setClassName(Dossier.class.getName()); // queue.setClassPK(String.valueOf(dossier.getPrimaryKey())); // queue.setToUsername(dossier.getUserName()); // queue.setToUserId(dossier.getUserId()); // queue.setToEmail(dossier.getContactEmail()); // queue.setToTelNo(dossier.getContactTelNo()); // // JSONObject payload = JSONFactoryUtil.createJSONObject(); // try { //// _log.info("START PAYLOAD: "); // payload.put( // "Dossier", JSONFactoryUtil.createJSONObject( // JSONFactoryUtil.looseSerialize(dossier))); // } // catch (JSONException parse) { // _log.error(parse); // } //// _log.info("payloadTest: "+payload.toJSONString()); // queue.setPayload(payload.toJSONString()); // queue.setExpireDate(cal.getTime()); // // NotificationQueueLocalServiceUtil.addNotificationQueue(queue); // } _log.debug("CREATE DOSSIER 6: " + (System.currentTimeMillis() - start) + " ms"); //Add to dossier user based on service process role createDossierUsers(groupId, dossier, process, lstProcessRoles); _log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms"); dossierLocalService.updateDossier(dossier); _log.debug("CREATE DOSSIER 8: " + (System.currentTimeMillis() - start) + " ms"); String payload = StringPool.BLANK; String actionCode = "1100"; if (dossier.getReceiveDate() == null) { JSONObject jsonDate = JSONFactoryUtil.createJSONObject(); jsonDate.put(DossierTerm.RECEIVE_DATE, (new Date()).getTime()); Double durationCount = process.getDurationCount(); if (Validator.isNotNull(String.valueOf(durationCount)) && durationCount > 0d) { Date dueDateCal = HolidayUtils.getDueDate(new Date(), process.getDurationCount(), process.getDurationUnit(), groupId); jsonDate.put(DossierTerm.DUE_DATE, dueDateCal != null ? dueDateCal.getTime() : 0); } if (Validator.isNotNull(jsonDate)) { payload = jsonDate.toJSONString(); } } // ProcessAction proAction = getProcessAction(groupId, dossier, actionCode, serviceProcessId); doAction(groupId, userId, dossier, option, proAction, actionCode, StringPool.BLANK, StringPool.BLANK, payload, StringPool.BLANK, input.getPayment(), 0, serviceContext); } return dossier; } private void processCloneDossierFile(Long dossierFileId, long dossierId, long userId) throws PortalException { DossierFile dossierFileParent = dossierFileLocalService.fetchDossierFile(dossierFileId); if (dossierFileParent != null) { long dossierFileChildrenId = counterLocalService.increment(DossierFile.class.getName()); DossierFile object = dossierFilePersistence.create(dossierFileChildrenId); _log.debug("****End uploadFile file at:" + new Date()); Date now = new Date(); User userAction = null; if (userId != 0) { userAction = userLocalService.getUser(userId); } // Add audit fields object.setCompanyId(dossierFileParent.getCompanyId()); object.setGroupId(dossierFileParent.getGroupId()); object.setCreateDate(now); object.setModifiedDate(now); object.setUserId(userAction != null ? userAction.getUserId() : 0l); object.setUserName(userAction != null ? userAction.getFullName() : StringPool.BLANK); // Add other fields object.setDossierId(dossierId); object.setReferenceUid(PortalUUIDUtil.generate()); object.setDossierTemplateNo(dossierFileParent.getDossierTemplateNo()); object.setFileEntryId(dossierFileParent.getFileEntryId()); object.setDossierPartNo(dossierFileParent.getDossierPartNo()); object.setFileTemplateNo(dossierFileParent.getFileTemplateNo()); object.setDossierPartType(dossierFileParent.getDossierPartType()); _log.debug("****Start autofill file at:" + new Date()); object.setDisplayName(dossierFileParent.getDisplayName()); object.setOriginal(false); object.setIsNew(true); object.setFormData(dossierFileParent.getFormData()); object.setEForm(dossierFileParent.getEForm()); object.setRemoved(false); object.setSignCheck(dossierFileParent.getSignCheck()); object.setFormScript(dossierFileParent.getFormScript()); object.setFormReport(dossierFileParent.getFormReport()); object.setFormSchema(dossierFileParent.getFormSchema()); dossierFilePersistence.update(object); } } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = { SystemException.class, PortalException.class, Exception.class }) public Dossier addFullDossier(long groupId, Company company, User user, ServiceContext serviceContext, DossierMultipleInputModel input) throws UnauthenticationException, PortalException, Exception { BackendAuth auth = new BackendAuthImpl(); DossierPermission dossierPermission = new DossierPermission(); long start = System.currentTimeMillis(); if (!auth.isAuth(serviceContext)) { throw new UnauthenticationException(); } ProcessOption option = getProcessOption(input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo(), groupId); long serviceProcessId = 0; if (option != null) { serviceProcessId = option.getServiceProcessId(); } boolean flag = false; long userId = serviceContext.getUserId(); Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userId); if (employee != null) { long employeeId = employee.getEmployeeId(); if (employeeId > 0) { List<EmployeeJobPos> empJobList = EmployeeJobPosLocalServiceUtil.findByF_EmployeeId(employeeId); if (empJobList != null && empJobList.size() > 0) { for (EmployeeJobPos employeeJobPos : empJobList) { long jobPosId = employeeJobPos.getJobPostId(); if (jobPosId > 0) { JobPos job = JobPosLocalServiceUtil.fetchJobPos(jobPosId); if (job != null) { ServiceProcessRolePK pk = new ServiceProcessRolePK(serviceProcessId, job.getMappingRoleId()); ServiceProcessRole role = serviceProcessRoleLocalService .fetchServiceProcessRole(pk); if (role != null && role.getModerator()) { flag = true; break; } } } } } } } else { flag = true; } if (!flag) { throw new UnauthenticationException("No permission create dossier"); } _log.debug("CREATE DOSSIER 1: " + (System.currentTimeMillis() - start) + " ms"); dossierPermission.hasCreateDossier(groupId, user.getUserId(), input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo()); Dossier dossier = null; if (Validator.isNotNull(input.getDossiers())) { JSONObject jsonDossier = JSONFactoryUtil.createJSONObject(input.getDossiers()); //Get params input dossier String referenceUid = jsonDossier.getString(DossierTerm.REFERENCE_UID); if (Validator.isNull(referenceUid) || referenceUid.trim().length() == 0) referenceUid = DossierNumberGenerator.generateReferenceUID(groupId); int counter = 0; //boolean online = GetterUtil.getBoolean(input.getOnline()); boolean online = false; int originality = input.getOriginality(); int viaPostal = Validator.isNotNull(jsonDossier.getString(DossierTerm.VIA_POSTAL)) ? GetterUtil.getInteger(jsonDossier.getString(DossierTerm.VIA_POSTAL)): 0; ServiceConfig config = serviceConfigLocalService.getBySICodeAndGAC(groupId, input.getServiceCode(), input.getGovAgencyCode()); if (config != null && Validator.isNotNull(viaPostal)) { viaPostal = config.getPostService() ? (viaPostal == 0 ? 1 : viaPostal) : 0; } else if (config != null) { viaPostal = config.getPostService() ? 1 : 0; } //Get service process ServiceProcess process = null; if (option != null) { process = serviceProcessLocalService.getServiceProcess(serviceProcessId); if (process == null) { throw new NotFoundException("Cant find process"); } } ServiceInfo service = serviceInfoLocalService.getByCode(groupId, input.getServiceCode()); String serviceName = service != null ? service.getServiceName(): StringPool.BLANK; String govAgencyName = getDictItemName(groupId, GOVERNMENT_AGENCY, input.getGovAgencyCode()); //DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(ADMINISTRATIVE_REGION, groupId); //String cityName = getDictItemName(groupId, dc, input.getCityCode()); //String districtName = getDictItemName(groupId, dc, input.getDistrictCode()); //String wardName = getDictItemName(groupId, dc, input.getWardCode()); // _log.info("Service code: " + input.getServiceCode()); //_log.debug("===ADD DOSSIER CITY NAME:" + cityName); String password = StringPool.BLANK; if (Validator.isNotNull(jsonDossier.getString("password"))) { password = jsonDossier.getString("password"); } else if (Validator.isNotNull(process.getGeneratePassword()) && process.getGeneratePassword()) { password = PwdGenerator.getPinNumber(); } String postalCityName = StringPool.BLANK; if (Validator.isNotNull(jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE))) { postalCityName = getDictItemName(groupId, VNPOST_CITY_CODE, jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE)); } int sampleCount = (option != null ? (int) option.getSampleCount() : 1); String registerBookCode = (option != null ? (Validator.isNotNull(option.getRegisterBookCode()) ? option.getRegisterBookCode() : StringPool.BLANK) : StringPool.BLANK); String registerBookName = (Validator.isNotNull(registerBookCode) ? getDictItemName(groupId, REGISTER_BOOK, registerBookCode) : StringPool.BLANK); _log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms"); Long appIdDateLong = jsonDossier.getLong(DossierTerm.APPLICANT_ID_DATE); Date appIdDate = null; if (appIdDateLong > 0) { appIdDate = new Date(appIdDateLong); } // Params add dossier String applicantName = jsonDossier.getString(DossierTerm.APPLICANT_NAME); String applicantIdType = jsonDossier.getString(DossierTerm.APPLICANT_ID_TYPE); String applicantIdNo = jsonDossier.getString(DossierTerm.APPLICANT_ID_NO); String address = jsonDossier.getString(DossierTerm.ADDRESS); String contactName = jsonDossier.getString(DossierTerm.CONTACT_NAME); String contactTelNo = jsonDossier.getString(DossierTerm.CONTACT_TEL_NO); String contactEmail = jsonDossier.getString(DossierTerm.CONTACT_EMAIL); // String postalServiceCode = jsonDossier.getString(DossierTerm.POSTAL_SERVICE_CODE); String postalServiceName = jsonDossier.getString(DossierTerm.POSTAL_SERVICE_NAME); String postalAddress = jsonDossier.getString(DossierTerm.POSTAL_ADDRESS); String postalCityCode = jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE); String postalDistrictCode = jsonDossier.getString(DossierTerm.POSTAL_DISTRICT_CODE); String postalDistrictName = jsonDossier.getString(DossierTerm.POSTAL_DISTRICT_NAME); String postalWardCode = jsonDossier.getString(DossierTerm.POSTAL_WARD_CODE); String postalWardName = jsonDossier.getString(DossierTerm.POSTAL_WARD_NAME); String postalTelNo = jsonDossier.getString(DossierTerm.POSTAL_TEL_NO); String applicantNote = jsonDossier.getString(DossierTerm.APPLICANT_NOTE); String delegateIdNo = jsonDossier.getString(DossierTerm.DELEGATE_ID_NO); String delegateName = jsonDossier.getString(DossierTerm.DELEGATE_NAME); String delegateTelNo = jsonDossier.getString(DossierTerm.DELEGATE_TELNO); String delegateEmail = jsonDossier.getString(DossierTerm.DELEGATE_EMAIL); String delegateAddress = jsonDossier.getString(DossierTerm.DELEGATE_ADDRESS); //TODO String delegateCityCode = jsonDossier.getString(DossierTerm.DELEGATE_CITYCODE); String delegateCityName = StringPool.BLANK; if (Validator.isNotNull(delegateCityCode)) { delegateCityName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateCityCode); } String delegateDistrictCode = jsonDossier.getString(DossierTerm.DELEGATE_DISTRICTCODE); String delegateDistrictName = StringPool.BLANK; if (Validator.isNotNull(delegateDistrictCode)) { delegateDistrictName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateDistrictCode); } String delegateWardCode = jsonDossier.getString(DossierTerm.DELEGATE_WARDCODE); String delegateWardName = StringPool.BLANK; if (Validator.isNotNull(delegateWardCode)) { delegateWardName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateWardCode); } // String dossierName = Validator.isNotNull(jsonDossier.getString(DossierTerm.DOSSIER_NAME)) ? jsonDossier.getString(DossierTerm.DOSSIER_NAME) : serviceName; Long receiveDateTimeStamp = jsonDossier.getLong(DossierTerm.RECEIVE_DATE); Date receiveDate = null; if (receiveDateTimeStamp > 0) { receiveDate = new Date(receiveDateTimeStamp); } Long dueDateTimeStamp = jsonDossier.getLong(DossierTerm.DUE_DATE); Date dueDate = null; if (dueDateTimeStamp > 0) { dueDate = new Date(dueDateTimeStamp); } String metaData = jsonDossier.getString(DossierTerm.META_DATA); dossier = dossierLocalService.initMultipleDossier(groupId, 0l, referenceUid, counter, input.getServiceCode(), serviceName, input.getGovAgencyCode(), govAgencyName, applicantName, applicantIdType, applicantIdNo, appIdDate, address, contactName, contactTelNo, contactEmail, input.getDossierTemplateNo(), password, viaPostal, postalServiceCode, postalServiceName, postalAddress, postalCityCode, postalCityName, postalDistrictCode, postalDistrictName, postalWardCode, postalWardName, postalTelNo, online, process.getDirectNotification(), applicantNote, input.getOriginality(), delegateIdNo, delegateName, delegateTelNo, delegateEmail, delegateAddress, delegateCityCode, delegateCityName, delegateDistrictCode, delegateDistrictName, delegateWardCode, delegateWardName, registerBookCode, registerBookName, sampleCount, dossierName, service, process, option, serviceContext); if (receiveDate != null) dossier.setReceiveDate(receiveDate); if (dueDate != null) dossier.setDueDate(dueDate); if (Validator.isNotNull(metaData)) dossier.setMetaData(metaData); //TODO: Process then //updateDelegateApplicant(dossier, input); _log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms"); if (originality != DossierTerm.ORIGINALITY_LIENTHONG) { Applicant applicant = ApplicantLocalServiceUtil.fetchByMappingID(serviceContext.getUserId()); if (applicant != null) { updateApplicantInfo(dossier, applicant.getApplicantIdDate(), applicant.getApplicantIdNo(), applicant.getApplicantIdType(), applicant.getApplicantName(), applicant.getAddress(), applicant.getCityCode(), applicant.getCityName(), applicant.getDistrictCode(), applicant.getDistrictName(), applicant.getWardCode(), applicant.getWardName(), applicant.getContactEmail(), applicant.getContactTelNo() ); } } if (Validator.isNull(dossier)) { throw new NotFoundException("Cant add DOSSIER"); } _log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms"); //TODO /** Create DossierMark */ //_log.debug("flagOldDossier: "+flagOldDossier); _log.debug("originality: "+originality); String templateNo = dossier.getDossierTemplateNo(); _log.debug("templateNo: "+templateNo); long dossierId = dossier.getDossierId(); if (originality == DossierTerm.ORIGINALITY_MOTCUA || originality == DossierTerm.ORIGINALITY_LIENTHONG) { if (Validator.isNotNull(input.getDossierMarkArr())) { JSONArray markArr = JSONFactoryUtil.createJSONArray(input.getDossierMarkArr()); if (markArr != null && markArr.length() > 0) { List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossierId); Map<String, DossierMark> mapMarks = new HashMap<>(); for (DossierMark dm : lstMarks) { mapMarks.put(dm.getDossierPartNo(), dm); } org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[markArr.length()]; for (int i = 0; i < markArr.length(); i++) { JSONObject jsonMark = markArr.getJSONObject(i); //System.out.println("jsonMark: "+jsonMark); org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel(); model.setDossierId(dossier.getDossierId()); model.setDossierPartNo(jsonMark.getString("partNo")); model.setFileCheck(0); model.setFileMark(jsonMark.getInt("fileMark")); model.setFileComment(StringPool.BLANK); model.setRecordCount(StringPool.BLANK); marks[i] = model; } dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext); } } else if (Validator.isNotNull(templateNo)) { List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo); // _log.info("partList: "+partList); if (partList != null && partList.size() > 0) { _log.debug("partList.size(): "+partList.size()); _log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms"); org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()]; int count = 0; List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossierId); Map<String, DossierMark> mapMarks = new HashMap<>(); for (DossierMark dm : lstMarks) { mapMarks.put(dm.getDossierPartNo(), dm); } for (DossierPart dossierPart : partList) { int fileMark = dossierPart.getFileMark(); String dossierPartNo = dossierPart.getPartNo(); org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel(); model.setDossierId(dossier.getDossierId()); model.setDossierPartNo(dossierPartNo); model.setFileCheck(0); model.setFileMark(fileMark); model.setFileComment(StringPool.BLANK); model.setRecordCount(StringPool.BLANK); marks[count++] = model; } dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext); _log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms"); } } } /** * Add dossier file */ if (Validator.isNotNull(input.getDossierFileArr())) { JSONArray dossierFileArr = JSONFactoryUtil.createJSONArray(input.getDossierFileArr()); if (dossierFileArr != null && dossierFileArr.length() > 0) { for (int j = 0; j < dossierFileArr.length(); j++) { JSONObject jsonFile = dossierFileArr.getJSONObject(j); System.out.println("jsonFile: "+jsonFile.getString("eform")); boolean eform = Boolean.valueOf(jsonFile.getString("eform")); System.out.println("eform"+eform); if (eform) { //EFORM _log.info("In dossier file create by eform"); try { // String referenceUidFile = UUID.randomUUID().toString(); String partNo = jsonFile.getString(DossierPartTerm.PART_NO); String formData = jsonFile.getString("formData"); DossierFile dossierFile = null; // DossierFileActions action = new DossierFileActionsImpl(); DossierPart dossierPart = dossierPartLocalService.fetchByTemplatePartNo(groupId, templateNo, partNo); //_log.info("__file:" + file); //DataHandler dataHandler = (file != null) ? file.getDataHandler() : null; dossierFile = DossierFileLocalServiceUtil.getByGID_DID_PART_EFORM(groupId, dossierId, partNo, true, false); if (dossierFile == null) { _log.info("dossierFile NULL"); dossierFile = dossierFileLocalService.addDossierFileEForm(groupId, dossierId, referenceUid, templateNo, partNo, dossierPart.getFileTemplateNo(), dossierPart.getPartName(), dossierPart.getPartName(), 0, null, StringPool.BLANK, "true", serviceContext); } if(Validator.isNotNull(formData)) { dossierFile.setFormData(formData); } if(Validator.isNotNull(eform)) { dossierFile.setEForm(eform); } _log.info("__Start update dossier file at:" + new Date()); DossierFileLocalServiceUtil.updateDossierFile(dossierFile); dossierFile = dossierFileLocalService.updateFormData(groupId, dossierId, dossierFile.getReferenceUid(), formData, serviceContext); _log.info("__End update dossier file at:" + new Date()); } catch (Exception e) { _log.debug(e); } } } } } /**Create dossier user */ List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId()); List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId()); if (lstDus.size() == 0) { DossierUserActions duActions = new DossierUserActionsImpl(); duActions.initDossierUser(groupId, dossier, process, lstProcessRoles); } if (originality == DossierTerm.ORIGINALITY_DVCTT) { dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true); } _log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms"); // if (dossier != null) { // // // long notificationQueueId = CounterLocalServiceUtil.increment(NotificationQueue.class.getName()); // // NotificationQueue queue = NotificationQueueLocalServiceUtil.createNotificationQueue(notificationQueueId); // //Process add notification queue // Date now = new Date(); // // Calendar cal = Calendar.getInstance(); // cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) + 1); // // queue.setCreateDate(now); // queue.setModifiedDate(now); // queue.setGroupId(groupId); // queue.setCompanyId(company.getCompanyId()); // // queue.setNotificationType(NotificationType.DOSSIER_01); // queue.setClassName(Dossier.class.getName()); // queue.setClassPK(String.valueOf(dossier.getPrimaryKey())); // queue.setToUsername(dossier.getUserName()); // queue.setToUserId(dossier.getUserId()); // queue.setToEmail(dossier.getContactEmail()); // queue.setToTelNo(dossier.getContactTelNo()); // // JSONObject payload = JSONFactoryUtil.createJSONObject(); // try { //// _log.info("START PAYLOAD: "); // payload.put( // "Dossier", JSONFactoryUtil.createJSONObject( // JSONFactoryUtil.looseSerialize(dossier))); // } // catch (JSONException parse) { // _log.error(parse); // } //// _log.info("payloadTest: "+payload.toJSONString()); // queue.setPayload(payload.toJSONString()); // queue.setExpireDate(cal.getTime()); // // NotificationQueueLocalServiceUtil.addNotificationQueue(queue); // } _log.debug("CREATE DOSSIER 6: " + (System.currentTimeMillis() - start) + " ms"); //Add to dossier user based on service process role createDossierUsers(groupId, dossier, process, lstProcessRoles); _log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms"); dossierLocalService.updateDossier(dossier); _log.debug("CREATE DOSSIER 8: " + (System.currentTimeMillis() - start) + " ms"); String payload = StringPool.BLANK; String actionCode = "1100"; if (dossier.getReceiveDate() == null) { JSONObject jsonDate = JSONFactoryUtil.createJSONObject(); jsonDate.put(DossierTerm.RECEIVE_DATE, (new Date()).getTime()); Double durationCount = process.getDurationCount(); if (Validator.isNotNull(String.valueOf(durationCount)) && durationCount > 0d) { Date dueDateCal = HolidayUtils.getDueDate(new Date(), process.getDurationCount(), process.getDurationUnit(), groupId); jsonDate.put(DossierTerm.DUE_DATE, dueDateCal != null ? dueDateCal.getTime() : 0); } if (Validator.isNotNull(jsonDate)) { payload = jsonDate.toJSONString(); } } // ProcessAction proAction = getProcessAction(groupId, dossier, actionCode, serviceProcessId); doAction(groupId, userId, dossier, option, proAction, actionCode, StringPool.BLANK, StringPool.BLANK, payload, StringPool.BLANK, input.getPayment(), 0, serviceContext); } return dossier; } private void createDossierUsers(long groupId, Dossier dossier, ServiceProcess process, List<ServiceProcessRole> lstProcessRoles) { List<DossierUser> lstDaus = dossierUserLocalService.findByDID(dossier.getDossierId()); int count = 0; long[] roleIds = new long[lstProcessRoles.size()]; for (ServiceProcessRole spr : lstProcessRoles) { long roleId = spr.getRoleId(); roleIds[count++] = roleId; } List<JobPos> lstJobPoses = JobPosLocalServiceUtil.findByF_mappingRoleIds(groupId, roleIds); Map<Long, JobPos> mapJobPoses = new HashMap<>(); long[] jobPosIds = new long[lstJobPoses.size()]; count = 0; for (JobPos jp : lstJobPoses) { mapJobPoses.put(jp.getJobPosId(), jp); jobPosIds[count++] = jp.getJobPosId(); } List<EmployeeJobPos> lstTemp = EmployeeJobPosLocalServiceUtil.findByF_G_jobPostIds(groupId, jobPosIds); Map<Long, List<EmployeeJobPos>> mapEJPS = new HashMap<>(); for (EmployeeJobPos ejp : lstTemp) { if (mapEJPS.get(ejp.getJobPostId()) != null) { mapEJPS.get(ejp.getJobPostId()).add(ejp); } else { List<EmployeeJobPos> lstEJPs = new ArrayList<>(); lstEJPs.add(ejp); mapEJPS.put(ejp.getJobPostId(), lstEJPs); } } for (ServiceProcessRole spr : lstProcessRoles) { long roleId = spr.getRoleId(); int moderator = spr.getModerator() ? 1 : 0; // JobPos jp = JobPosLocalServiceUtil.fetchByF_mappingRoleId(groupId, roleId); JobPos jp = mapJobPoses.get(roleId); if (jp != null) { // List<EmployeeJobPos> lstEJPs = EmployeeJobPosLocalServiceUtil.getByJobPostId(groupId, jp.getJobPosId()); List<EmployeeJobPos> lstEJPs = mapEJPS.get(jp.getJobPosId()); long[] employeeIds = new long[lstEJPs.size()]; int countEmp = 0; for (EmployeeJobPos ejp : lstEJPs) { employeeIds[countEmp++] = ejp.getEmployeeId(); } List<Employee> lstEmpls = EmployeeLocalServiceUtil.findByG_EMPID(groupId, employeeIds); HashMap<Long, Employee> mapEmpls = new HashMap<>(); for (Employee e : lstEmpls) { mapEmpls.put(e.getEmployeeId(), e); } List<Employee> lstEmployees = new ArrayList<>(); // for (EmployeeJobPos ejp : lstEJPs) { // Employee employee = EmployeeLocalServiceUtil.fetchEmployee(ejp.getEmployeeId()); // if (employee != null) { // lstEmployees.add(employee); // } // } for (EmployeeJobPos ejp : lstEJPs) { if (mapEmpls.get(ejp.getEmployeeId()) != null) { lstEmployees.add(mapEmpls.get(ejp.getEmployeeId())); } } HashMap<Long, DossierUser> mapDaus = new HashMap<>(); for (DossierUser du : lstDaus) { mapDaus.put(du.getUserId(), du); } for (Employee e : lstEmployees) { // DossierUserPK pk = new DossierUserPK(); // pk.setDossierId(dossier.getDossierId()); // pk.setUserId(e.getMappingUserId()); // DossierUser ds = DossierUserLocalServiceUtil.fetchDossierUser(pk); if (mapDaus.get(e.getMappingUserId()) == null) { // if (ds == null) { dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), e.getMappingUserId(), moderator, Boolean.FALSE); } else { DossierUser ds = mapDaus.get(e.getMappingUserId()); if (moderator == 1 && ds.getModerator() == 0) { ds.setModerator(1); dossierUserLocalService.updateDossierUser(ds); } } } } } } private void updateApplicantInfo(Dossier dossier, Date applicantIdDate, String applicantIdNo, String applicantIdType, String applicantName, String address, String cityCode, String cityName, String districtCode, String districtName, String wardCode, String wardName, String contactEmail, String contactTelNo) { dossier.setApplicantIdDate(applicantIdDate); dossier.setApplicantIdNo(applicantIdNo); dossier.setApplicantIdType(applicantIdType); dossier.setApplicantName(applicantName); dossier.setAddress(address); dossier.setCityCode(cityCode); dossier.setCityName(cityName); dossier.setDistrictCode(districtCode); dossier.setDistrictName(districtName); dossier.setWardCode(wardCode); dossier.setWardName(wardName); dossier.setContactEmail(contactEmail); dossier.setContactTelNo(contactTelNo); dossier.setDelegateAddress(address); dossier.setDelegateCityCode(cityCode); dossier.setDelegateCityName(cityName); dossier.setDelegateDistrictCode(districtCode); dossier.setDelegateDistrictName(districtName); dossier.setDelegateEmail(contactEmail); dossier.setDelegateIdNo(applicantIdNo); dossier.setDelegateName(applicantName); dossier.setDelegateTelNo(contactTelNo); dossier.setDelegateWardCode(wardCode); dossier.setDelegateWardName(wardName); } private void updateDelegateApplicant(Dossier dossier, DossierInputModel input) { if (Validator.isNotNull(input.getDelegateName())) { dossier.setDelegateName(input.getDelegateName()); } if (Validator.isNotNull(input.getDelegateIdNo())) { dossier.setDelegateIdNo(input.getDelegateIdNo()); } if (Validator.isNotNull(input.getDelegateTelNo())) { dossier.setDelegateTelNo(input.getDelegateTelNo()); } if (Validator.isNotNull(input.getDelegateEmail())) { dossier.setDelegateEmail(input.getDelegateEmail()); } if (Validator.isNotNull(input.getDelegateAddress())) { dossier.setDelegateAddress(input.getDelegateAddress()); } if (Validator.isNotNull(input.getDelegateCityCode())) { dossier.setDelegateCityCode(input.getDelegateCityCode()); } if (Validator.isNotNull(input.getDelegateCityName())) { dossier.setDelegateCityName(input.getDelegateCityName()); } if (Validator.isNotNull(input.getDelegateDistrictCode())) { dossier.setDelegateDistrictCode(input.getDelegateDistrictCode()); } if (Validator.isNotNull(input.getDelegateDistrictName())) { dossier.setDelegateDistrictName(input.getDelegateDistrictName()); } if (Validator.isNotNull(input.getDelegateWardCode())) { dossier.setDelegateWardCode(input.getDelegateWardCode()); } if (Validator.isNotNull(input.getDelegateWardName())) { dossier.setDelegateWardCode(input.getDelegateWardName()); } } private String getDictItemName(long groupId, DictCollection dc, String itemCode) { if (Validator.isNotNull(dc)) { DictItem it = DictItemLocalServiceUtil.fetchByF_dictItemCode(itemCode, dc.getPrimaryKey(), groupId); if(Validator.isNotNull(it)){ return it.getItemName(); }else{ return StringPool.BLANK; } } else { return StringPool.BLANK; } } @Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class }) public DossierFile addDossierFileByDossierId(long groupId, Company company, User user, ServiceContext serviceContext, Attachment file, String id, String referenceUid, String dossierTemplateNo, String dossierPartNo, String fileTemplateNo, String displayName, String fileType, String isSync, String formData, String removed, String eForm, Long modifiedDate) throws UnauthenticationException, PortalException, Exception { BackendAuth auth = new BackendAuthImpl(); if (!auth.isAuth(serviceContext)) { throw new UnauthenticationException(); } long dossierId = GetterUtil.getLong(id); Dossier dossier = null; if (dossierId != 0) { dossier = dossierLocalService.fetchDossier(dossierId); if (Validator.isNull(dossier)) { dossier = dossierLocalService.getByRef(groupId, id); } } else { dossier = dossierLocalService.getByRef(groupId, id); } DataHandler dataHandler = (file != null) ? file.getDataHandler() : null; long originDossierId = dossier.getOriginDossierId(); if (originDossierId != 0) { //HSLT Dossier hsltDossier = dossierLocalService.fetchDossier(dossier.getDossierId()); dossier = dossierLocalService.fetchDossier(dossier.getOriginDossierId()); ServiceConfig serviceConfig = serviceConfigLocalService.getBySICodeAndGAC(groupId, dossier.getServiceCode(), hsltDossier.getGovAgencyCode()); List<ProcessOption> lstOptions = processOptionLocalService.getByServiceProcessId(serviceConfig.getServiceConfigId()); if (serviceConfig != null) { if (lstOptions.size() > 0) { ProcessOption processOption = lstOptions.get(0); DossierTemplate dossierTemplate = dossierTemplateLocalService.fetchDossierTemplate(processOption.getDossierTemplateId()); List<DossierPart> lstParts = dossierPartLocalService.getByTemplateNo(groupId, dossierTemplate.getTemplateNo()); for (DossierPart dp : lstParts) { if (dp.getPartNo().equals(dossierPartNo) && dp.getFileTemplateNo().equals(fileTemplateNo)) { dossierTemplateNo = dp.getTemplateNo(); } } } } } else { List<DossierPart> lstParts = dossierPartLocalService.getByTemplateNo(groupId, dossier.getDossierTemplateNo()); for (DossierPart dp : lstParts) { if (dp.getPartNo().equals(dossierPartNo)) { fileTemplateNo = dp.getFileTemplateNo(); dossierTemplateNo = dossier.getDossierTemplateNo(); } } } if (originDossierId > 0) { _log.debug("__Start add file at:" + new Date()); DossierFile dossierFile = null; DossierFile oldDossierFile = null; if (Validator.isNotNull(referenceUid)) { oldDossierFile = dossierFileLocalService.getByDossierAndRef(dossier.getDossierId(), referenceUid); } if (oldDossierFile != null && modifiedDate != null) { if (oldDossierFile.getModifiedDate() != null && oldDossierFile.getModifiedDate().getTime() < modifiedDate) { if (dataHandler != null && dataHandler.getInputStream() != null) { dossierFile = dossierFileLocalService.updateDossierFile(groupId, dossier.getDossierId(), referenceUid, displayName, StringPool.BLANK, dataHandler.getInputStream(), serviceContext); } else { dossierFile = dossierFileLocalService.updateDossierFile(groupId, dossier.getDossierId(), referenceUid, displayName, StringPool.BLANK, null, serviceContext); } _log.debug("__End add file at:" + new Date()); if(Validator.isNotNull(formData)) { dossierFile.setFormData(formData); } _log.debug("REMOVED:" + removed); if(Validator.isNotNull(removed)) { dossierFile.setRemoved(Boolean.parseBoolean(removed)); } if(Validator.isNotNull(eForm)) { dossierFile.setEForm(Boolean.parseBoolean(eForm)); } _log.debug("__Start update dossier file at:" + new Date()); dossierFileLocalService.updateDossierFile(dossierFile); _log.debug("__End update dossier file at:" + new Date()); _log.debug("__End bind to dossierFile" + new Date()); return dossierFile; } else { throw new DataConflictException("Conflict dossier file"); } } else { _log.debug("__Start add file at:" + new Date()); if (dataHandler != null && dataHandler.getInputStream() != null) { dossierFile = dossierFileLocalService.addDossierFile(groupId, dossier.getDossierId(), referenceUid, dossierTemplateNo, dossierPartNo, fileTemplateNo, displayName, dataHandler.getName(), 0, dataHandler.getInputStream(), fileType, isSync, serviceContext); } else { dossierFile = dossierFileLocalService.addDossierFile(groupId, dossier.getDossierId(), referenceUid, dossierTemplateNo, dossierPartNo, fileTemplateNo, displayName, displayName, 0, null, fileType, isSync, serviceContext); } _log.debug("__End add file at:" + new Date()); if(Validator.isNotNull(formData)) { dossierFile.setFormData(formData); } if(Validator.isNotNull(removed)) { dossierFile.setRemoved(Boolean.parseBoolean(removed)); } if(Validator.isNotNull(eForm)) { dossierFile.setEForm(Boolean.parseBoolean(eForm)); } _log.debug("__Start update dossier file at:" + new Date()); dossierFileLocalService.updateDossierFile(dossierFile); _log.debug("__End update dossier file at:" + new Date()); _log.debug("__End bind to dossierFile" + new Date()); return dossierFile; } } else { // DossierFile lastDossierFile = DossierFileLocalServiceUtil.findLastDossierFile(dossier.getDossierId(), fileTemplateNo, dossierTemplateNo); //_log.info("lastDossierFile: "+lastDossierFile); DossierFile oldDossierFile = null; if (Validator.isNotNull(referenceUid)) { oldDossierFile = DossierFileLocalServiceUtil.getByDossierAndRef(dossier.getDossierId(), referenceUid); } if (oldDossierFile != null && modifiedDate != null) { if (oldDossierFile.getModifiedDate() != null && oldDossierFile.getModifiedDate().getTime() < modifiedDate) { _log.debug("__Start add file at:" + new Date()); DossierFile dossierFile = null; if (dataHandler != null && dataHandler.getInputStream() != null) { dossierFile = dossierFileLocalService.updateDossierFile(groupId, dossier.getDossierId(), referenceUid, displayName, StringPool.BLANK, dataHandler.getInputStream(), serviceContext); } else { dossierFile = dossierFileLocalService.updateDossierFile(groupId, dossier.getDossierId(), referenceUid, displayName, StringPool.BLANK, null, serviceContext); } _log.debug("__End add file at:" + new Date()); if(Validator.isNotNull(formData)) { dossierFile.setFormData(formData); } if(Validator.isNotNull(removed)) { dossierFile.setRemoved(Boolean.parseBoolean(removed)); } if(Validator.isNotNull(eForm)) { dossierFile.setEForm(Boolean.parseBoolean(eForm)); } _log.debug("__Start update dossier file at:" + new Date()); DossierFileLocalServiceUtil.updateDossierFile(dossierFile); _log.debug("__End update dossier file at:" + new Date()); _log.debug("__End bind to dossierFile" + new Date()); return dossierFile; } else { throw new DataConflictException("Conflict dossier file"); } } else { _log.debug("__Start add file at:" + new Date()); DossierFile dossierFile = null; if (dataHandler != null && dataHandler.getInputStream() != null) { dossierFile = dossierFileLocalService.addDossierFile(groupId, dossier.getDossierId(), referenceUid, dossierTemplateNo, dossierPartNo, fileTemplateNo, displayName, dataHandler.getName(), 0, dataHandler.getInputStream(), fileType, isSync, serviceContext); } else { dossierFile = dossierFileLocalService.addDossierFile(groupId, dossier.getDossierId(), referenceUid, dossierTemplateNo, dossierPartNo, fileTemplateNo, displayName, displayName, 0, null, fileType, isSync, serviceContext); } _log.debug("__End add file at:" + new Date()); if(Validator.isNotNull(formData)) { dossierFile.setFormData(formData); } if(Validator.isNotNull(removed)) { dossierFile.setRemoved(Boolean.parseBoolean(removed)); } if(Validator.isNotNull(eForm)) { dossierFile.setEForm(Boolean.parseBoolean(eForm)); } _log.debug("__Start update dossier file at:" + new Date()); dossierFileLocalService.updateDossierFile(dossierFile); _log.debug("__End update dossier file at:" + new Date()); _log.debug("__End bind to dossierFile" + new Date()); return dossierFile; } } } @Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class }) public DossierFile updateDossierFile(long groupId, Company company, ServiceContext serviceContext, long id, String referenceUid, Attachment file) throws UnauthenticationException, PortalException, Exception { BackendAuth auth = new BackendAuthImpl(); DataHandler dataHandle = file.getDataHandler(); if (!auth.isAuth(serviceContext)) { throw new UnauthenticationException(); } Dossier dossier = dossierLocalService.fetchDossier(id); if (dossier != null) { if (dossier.getOriginDossierId() != 0) { dossier = dossierLocalService.fetchDossier(dossier.getOriginDossierId()); id = dossier.getDossierId(); } } DossierFile dossierFile = dossierFileLocalService.updateDossierFile(groupId, id, referenceUid, dataHandle.getName(), StringPool.BLANK, dataHandle.getInputStream(), serviceContext); return dossierFile; } @Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class }) public DossierFile updateDossierFileFormData(long groupId, Company company, ServiceContext serviceContext, long id, String referenceUid, String formdata) throws UnauthenticationException, PortalException, Exception { BackendAuth auth = new BackendAuthImpl(); if (!auth.isAuth(serviceContext)) { throw new UnauthenticationException(); } Dossier dossier = dossierLocalService.fetchDossier(id); if (dossier != null) { if (dossier.getOriginDossierId() != 0) { dossier = dossierLocalService.fetchDossier(dossier.getOriginDossierId()); id = dossier.getOriginDossierId(); } } DossierFile dossierFile = dossierFileLocalService.updateFormData(groupId, id, referenceUid, formdata, serviceContext); return dossierFile; } @Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class }) public DossierFile resetformdataDossierFileFormData(long groupId, Company company, ServiceContext serviceContext, long id, String referenceUid, String formdata) throws UnauthenticationException, PortalException, Exception { BackendAuth auth = new BackendAuthImpl(); if (!auth.isAuth(serviceContext)) { throw new UnauthenticationException(); } Dossier dossier = dossierLocalService.fetchDossier(id); if (dossier != null) { if (dossier.getOriginDossierId() != 0) { dossier = dossierLocalService.fetchDossier(dossier.getOriginDossierId()); id = dossier.getOriginDossierId(); } } DossierFile dossierFile = dossierFileLocalService.getDossierFileByReferenceUid(dossier.getDossierId(), referenceUid); String defaultData = StringPool.BLANK; if (Validator.isNotNull(dossierFile)) { DossierPart part = dossierPartLocalService.getByFileTemplateNo(groupId, dossierFile.getFileTemplateNo()); defaultData = AutoFillFormData.sampleDataBinding(part.getSampleData(), dossier.getDossierId(), serviceContext); dossierFile = dossierFileLocalService.getByReferenceUid(referenceUid).get(0); JSONObject defaultDataObj = JSONFactoryUtil.createJSONObject(defaultData); defaultDataObj.put("LicenceNo", dossierFile.getDeliverableCode()); defaultData = defaultDataObj.toJSONString(); } dossierFile = dossierFileLocalService.updateFormData(groupId, dossier.getDossierId(), referenceUid, defaultData, serviceContext); String deliverableCode = dossierFile.getDeliverableCode(); if (Validator.isNotNull(deliverableCode)) { Deliverable deliverable = deliverableLocalService.getByCode(deliverableCode); deliverableLocalService.deleteDeliverable(deliverable); } return dossierFile; } @Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class }) public PaymentFile createPaymentFileByDossierId(long groupId, ServiceContext serviceContext, String id, PaymentFileInputModel input) throws UnauthenticationException, PortalException, Exception { long userId = serviceContext.getUserId(); BackendAuth auth = new BackendAuthImpl(); if (!auth.isAuth(serviceContext)) { throw new UnauthenticationException(); } Dossier dossier = getDossier(id, groupId); long dossierId = dossier.getPrimaryKey(); if (!auth.hasResource(serviceContext, PaymentFile.class.getName(), ActionKeys.ADD_ENTRY)) { throw new UnauthorizationException(); } PaymentFile oldPaymentFile = paymentFileLocalService.getByDossierId(groupId, dossier.getDossierId()); String referenceUid = input.getReferenceUid(); PaymentFile paymentFile = null; if (Validator.isNull(referenceUid)) { referenceUid = PortalUUIDUtil.generate(); } if (oldPaymentFile != null) { paymentFile = oldPaymentFile; } else { paymentFile = paymentFileLocalService.createPaymentFiles(userId, groupId, dossierId, referenceUid, input.getPaymentFee(), input.getAdvanceAmount(), input.getFeeAmount(), input.getServiceAmount(), input.getShipAmount(), input.getPaymentAmount(), input.getPaymentNote(), input.getEpaymentProfile(), input.getBankInfo(), 0, input.getPaymentMethod(), serviceContext); } paymentFile.setInvoiceTemplateNo(input.getInvoiceTemplateNo()); if(Validator.isNotNull(input.getConfirmFileEntryId())){ paymentFile.setConfirmFileEntryId(input.getConfirmFileEntryId()); } if(Validator.isNotNull(input.getPaymentStatus())){ paymentFile.setPaymentStatus(input.getPaymentStatus()); } if(Validator.isNotNull(input.getEinvoice())) { paymentFile.setEinvoice(input.getEinvoice()); } if(Validator.isNotNull(input.getPaymentAmount())) { paymentFile.setPaymentAmount(input.getPaymentAmount()); } if(Validator.isNotNull(input.getPaymentMethod())){ paymentFile.setPaymentMethod(input.getPaymentMethod()); } if(Validator.isNotNull(input.getServiceAmount())){ paymentFile.setServiceAmount(input.getServiceAmount()); } if(Validator.isNotNull(input.getShipAmount())){ paymentFile.setShipAmount(input.getShipAmount()); } if(Validator.isNotNull(input.getAdvanceAmount())){ paymentFile.setAdvanceAmount(input.getAdvanceAmount()); } paymentFile = paymentFileLocalService.updatePaymentFile(paymentFile); return paymentFile; } private Dossier getDossier(String id, long groupId) throws PortalException { long dossierId = GetterUtil.getLong(id); Dossier dossier = null; if (dossierId != 0) { dossier = dossierLocalService.fetchDossier(dossierId); } if (Validator.isNull(dossier)) { dossier = dossierLocalService.getByRef(groupId, id); } return dossier; } @Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class }) public Dossier addDossierPublish(long groupId, Company company, User user, ServiceContext serviceContext, org.opencps.dossiermgt.input.model.DossierPublishModel input) throws UnauthenticationException, PortalException, Exception { BackendAuth auth = new BackendAuthImpl(); DossierActions actions = new DossierActionsImpl(); if (!auth.isAuth(serviceContext)) { throw new UnauthenticationException(); } String referenceUid = input.getReferenceUid(); int counter = 0; String serviceCode = input.getServiceCode(); String serviceName = input.getServiceName(); String govAgencyCode = input.getGovAgencyCode(); String govAgencyName = input.getGovAgencyName(); String applicantName = input.getApplicantName(); String applicantType = input.getApplicantIdType(); String applicantIdNo = input.getApplicantIdNo(); String applicantIdDate = input.getApplicantIdDate(); String address = input.getAddress(); String cityCode = input.getCityCode(); String cityName = input.getCityName(); String districtCode = input.getDistrictCode(); String districtName = input.getDistrictName(); String wardCode = input.getWardCode(); String wardName = input.getWardName(); String contactName = input.getContactName(); String contactTelNo = input.getContactTelNo(); String contactEmail = input.getContactEmail(); String dossierTemplateNo = input.getDossierTemplateNo(); String password = input.getPassword(); String online = input.getOnline(); String applicantNote = input.getApplicantNote(); int originality = 0; long createDateLong = GetterUtil.getLong(input.getCreateDate()); long modifiedDateLong = GetterUtil.getLong(input.getModifiedDate()); long submitDateLong = GetterUtil.getLong(input.getSubmitDate()); long receiveDateLong = GetterUtil.getLong(input.getReceiveDate()); long dueDateLong = GetterUtil.getLong(input.getDueDate()); long releaseDateLong = GetterUtil.getLong(input.getReleaseDate()); long finishDateLong = GetterUtil.getLong(input.getFinishDate()); long cancellingDateLong = GetterUtil.getLong(input.getCancellingDate()); long correcttingDateLong = GetterUtil.getLong(input.getCorrecttingDate()); long endorsementDateLong = GetterUtil.getLong(input.getEndorsementDate()); long extendDateLong = GetterUtil.getLong(input.getExtendDate()); long processDateLong = GetterUtil.getLong(input.getProcessDate()); String submissionNote = input.getSubmissionNote(); String lockState = input.getLockState(); String dossierNo = input.getDossierNo(); Dossier oldDossier = null; if (Validator.isNotNull(input.getReferenceUid())) { oldDossier = getDossier(input.getReferenceUid(), groupId); } else { oldDossier = DossierLocalServiceUtil.getByDossierNo(groupId, dossierNo); referenceUid = DossierNumberGenerator.generateReferenceUID(groupId); } if (oldDossier == null || oldDossier.getOriginality() == 0) { Dossier dossier = actions.publishDossier(groupId, 0l, referenceUid, counter, serviceCode, serviceName, govAgencyCode, govAgencyName, applicantName, applicantType, applicantIdNo, applicantIdDate, address, cityCode, cityName, districtCode, districtName, wardCode, wardName, contactName, contactTelNo, contactEmail, dossierTemplateNo, password, 0, StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, Boolean.valueOf(online), false, applicantNote, originality, createDateLong != 0 ? new Date(createDateLong) : null, modifiedDateLong != 0 ? new Date(modifiedDateLong) : null, submitDateLong != 0 ? new Date(submitDateLong) : null, receiveDateLong != 0 ? new Date(receiveDateLong) : null, dueDateLong != 0 ? new Date(dueDateLong) : null, releaseDateLong != 0 ? new Date(releaseDateLong) : null, finishDateLong != 0 ? new Date(finishDateLong) : null, cancellingDateLong != 0 ? new Date(cancellingDateLong) : null, correcttingDateLong != 0 ? new Date(correcttingDateLong) : null, endorsementDateLong != 0 ? new Date(endorsementDateLong) : null, extendDateLong != 0 ? new Date(extendDateLong) : null, processDateLong != 0 ? new Date(processDateLong) : null, input.getDossierNo(), input.getDossierStatus(), input.getDossierStatusText(), input.getDossierSubStatus(), input.getDossierSubStatusText(), input.getDossierActionId() != null ? input.getDossierActionId() : 0, submissionNote, lockState, input.getDelegateName(), input.getDelegateIdNo(), input.getDelegateTelNo(), input.getDelegateEmail(), input.getDelegateAddress(), input.getDelegateCityCode(), input.getDelegateCityName(), input.getDelegateDistrictCode(), input.getDelegateDistrictName(), input.getDelegateWardCode(), input.getDelegateWardName(), input.getDurationCount(), input.getDurationUnit(), input.getDossierName(), input.getProcessNo(), input.getMetaData(), serviceContext); return dossier; } return oldDossier; } @Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class }) public Dossier addFullDossier(long groupId, Company company, User user, ServiceContext serviceContext, DossierInputModel input) throws UnauthenticationException, PortalException, Exception { BackendAuth auth = new BackendAuthImpl(); DossierPermission dossierPermission = new DossierPermission(); long start = System.currentTimeMillis(); if (!auth.isAuth(serviceContext)) { throw new UnauthenticationException(); } ProcessOption option = getProcessOption(input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo(), groupId); long serviceProcessId = 0; if (option != null) { serviceProcessId = option.getServiceProcessId(); } boolean flag = false; long userId = serviceContext.getUserId(); Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userId); if (employee != null) { long employeeId = employee.getEmployeeId(); if (employeeId > 0) { List<EmployeeJobPos> empJobList = EmployeeJobPosLocalServiceUtil.findByF_EmployeeId(employeeId); if (empJobList != null && empJobList.size() > 0) { for (EmployeeJobPos employeeJobPos : empJobList) { long jobPosId = employeeJobPos.getJobPostId(); if (jobPosId > 0) { JobPos job = JobPosLocalServiceUtil.fetchJobPos(jobPosId); if (job != null) { ServiceProcessRolePK pk = new ServiceProcessRolePK(serviceProcessId, job.getMappingRoleId()); ServiceProcessRole role = serviceProcessRoleLocalService .fetchServiceProcessRole(pk); if (role != null && role.getModerator()) { flag = true; break; } } } } } } } else { flag = true; } if (!flag) { throw new UnauthenticationException("No permission create dossier"); } _log.debug("CREATE DOSSIER 1: " + (System.currentTimeMillis() - start) + " ms"); dossierPermission.hasCreateDossier(groupId, user.getUserId(), input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo()); //int counter = DossierNumberGenerator.counterDossier(user.getUserId(), groupId); String referenceUid = input.getReferenceUid(); int counter = 0; // Create dossierNote ServiceProcess process = null; boolean online = GetterUtil.getBoolean(input.getOnline()); int originality = GetterUtil.getInteger(input.getOriginality()); Integer viaPostal = input.getViaPostal(); ServiceConfig config = serviceConfigLocalService.getBySICodeAndGAC(groupId, input.getServiceCode(), input.getGovAgencyCode()); if (config != null && Validator.isNotNull(viaPostal)) { viaPostal = config.getPostService() ? (viaPostal == 0 ? 1 : viaPostal) : 0; } else if (config != null) { viaPostal = config.getPostService() ? 1 : 0; } if (option != null) { process = serviceProcessLocalService.getServiceProcess(serviceProcessId); } if (process == null) { throw new NotFoundException("Cant find process"); } if (Validator.isNull(referenceUid) || referenceUid.trim().length() == 0) referenceUid = DossierNumberGenerator.generateReferenceUID(groupId); //Dossier checkDossier = dossierLocalService.getByRef(groupId, referenceUid); //if (checkDossier != null) { // return checkDossier; //} ServiceInfo service = serviceInfoLocalService.getByCode(groupId, input.getServiceCode()); String serviceName = StringPool.BLANK; if (service != null) { serviceName = service.getServiceName(); } String govAgencyName = getDictItemName(groupId, GOVERNMENT_AGENCY, input.getGovAgencyCode()); DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(ADMINISTRATIVE_REGION, groupId); String cityName = getDictItemName(groupId, dc, input.getCityCode()); String districtName = getDictItemName(groupId, dc, input.getDistrictCode()); String wardName = getDictItemName(groupId, dc, input.getWardCode()); // _log.info("Service code: " + input.getServiceCode()); _log.debug("===ADD DOSSIER CITY NAME:" + cityName); String password = StringPool.BLANK; if (Validator.isNotNull(input.getPassword())) { password = input.getPassword(); } else if (Validator.isNotNull(process.getGeneratePassword()) && process.getGeneratePassword()) { password = PwdGenerator.getPinNumber(); } String postalCityName = StringPool.BLANK; if (Validator.isNotNull(input.getPostalCityCode())) { postalCityName = getDictItemName(groupId, VNPOST_CITY_CODE, input.getPostalCityCode()); } Long sampleCount = (option != null ? option.getSampleCount() : 1l); // Process group dossier if (originality == DossierTerm.ORIGINALITY_HOSONHOM) { _log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms"); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"); Date appIdDate = null; try { appIdDate = sdf.parse(input.getApplicantIdDate()); } catch (Exception e) { _log.debug(e); } Dossier dossier = dossierLocalService.initDossier(groupId, 0l, referenceUid, counter, input.getServiceCode(), serviceName, input.getGovAgencyCode(), govAgencyName, input.getApplicantName(), input.getApplicantIdType(), input.getApplicantIdNo(), appIdDate, input.getAddress(), input.getCityCode(), cityName, input.getDistrictCode(), districtName, input.getWardCode(), wardName, input.getContactName(), input.getContactTelNo(), input.getContactEmail(), input.getDossierTemplateNo(), password, viaPostal, input.getPostalAddress(), input.getPostalCityCode(), postalCityName, input.getPostalTelNo(), online, process.getDirectNotification(), input.getApplicantNote(), Integer.valueOf(input.getOriginality()), service, process, option, serviceContext); if (Validator.isNotNull(input.getDossierName())) { dossier.setDossierName(input.getDossierName()); } else { dossier.setDossierName(serviceName); } dossier.setSampleCount(sampleCount); updateDelegateApplicant(dossier, input); // Process update dossierNo LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>(); params.put(DossierTerm.GOV_AGENCY_CODE, dossier.getGovAgencyCode()); params.put(DossierTerm.SERVICE_CODE, dossier.getServiceCode()); params.put(DossierTerm.DOSSIER_TEMPLATE_NO, dossier.getDossierTemplateNo()); params.put(DossierTerm.DOSSIER_STATUS, StringPool.BLANK); if (option != null) { //Process submition note dossier.setSubmissionNote(option.getSubmissionNote()); String dossierRef = DossierNumberGenerator.generateDossierNumber(groupId, dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(), process.getDossierGroupPattern(), params); dossier.setDossierNo(dossierRef.trim()); } dossier.setViaPostal(1); _log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms"); if (Validator.isNull(dossier)) { throw new NotFoundException("Can't add DOSSIER"); } _log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms"); //Create DossierMark _log.debug("originality: "+originality); String templateNo = dossier.getDossierTemplateNo(); _log.debug("templateNo: "+templateNo); if (Validator.isNotNull(input.getDossierMarkArr())) { JSONArray markArr = JSONFactoryUtil.createJSONArray(input.getDossierMarkArr()); if (markArr != null && markArr.length() > 0) { List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId()); Map<String, DossierMark> mapMarks = new HashMap<>(); for (DossierMark dm : lstMarks) { mapMarks.put(dm.getDossierPartNo(), dm); } for (int i = 0; i < markArr.length(); i++) { JSONObject jsonMark = markArr.getJSONObject(i); org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[markArr.length()]; org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel(); model.setDossierId(dossier.getDossierId()); model.setDossierPartNo(jsonMark.getString("partNo")); model.setFileCheck(0); model.setFileMark(jsonMark.getInt("fileMark")); model.setFileComment(StringPool.BLANK); model.setRecordCount(StringPool.BLANK); marks[i] = model; dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext); } } } else if (Validator.isNotNull(templateNo)) { List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo); // _log.info("partList: "+partList); if (partList != null && partList.size() > 0) { _log.debug("partList.size(): "+partList.size()); _log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms"); org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()]; int count = 0; List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId()); Map<String, DossierMark> mapMarks = new HashMap<>(); for (DossierMark dm : lstMarks) { mapMarks.put(dm.getDossierPartNo(), dm); } for (DossierPart dossierPart : partList) { int fileMark = dossierPart.getFileMark(); String dossierPartNo = dossierPart.getPartNo(); org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel(); model.setDossierId(dossier.getDossierId()); model.setDossierPartNo(dossierPartNo); model.setFileCheck(0); model.setFileMark(fileMark); model.setFileComment(StringPool.BLANK); model.setRecordCount(StringPool.BLANK); marks[count++] = model; } dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext); _log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms"); } } //Create dossier user List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId()); List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId()); if (lstDus.size() == 0) { DossierUserActions duActions = new DossierUserActionsImpl(); duActions.initDossierUser(groupId, dossier, process, lstProcessRoles); } // if (originality == DossierTerm.ORIGINALITY_DVCTT) { // dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true); // } _log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms"); //Add to dossier user based on service process role createDossierUsers(groupId, dossier, process, lstProcessRoles); _log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms"); return dossierLocalService.updateDossier(dossier); } else { List<Dossier> oldDossiers = dossierLocalService.getByU_G_GAC_SC_DTNO_DS_O( userId, groupId, input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo(), StringPool.BLANK, Integer.valueOf(input.getOriginality())); Dossier dossier = null; Dossier oldRefDossier = Validator.isNotNull(input.getReferenceUid()) ? dossierLocalService.getByRef(groupId, input.getReferenceUid()) : null; if (originality == DossierTerm.ORIGINALITY_DVCTT) { online = true; } boolean flagOldDossier = false; String registerBookCode = (option != null ? (Validator.isNotNull(option.getRegisterBookCode()) ? option.getRegisterBookCode() : StringPool.BLANK) : StringPool.BLANK); String registerBookName = (Validator.isNotNull(registerBookCode) ? getDictItemName(groupId, REGISTER_BOOK, registerBookCode) : StringPool.BLANK); _log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms"); if (oldRefDossier != null) { dossier = oldRefDossier; dossier.setSubmitDate(new Date()); ServiceProcess serviceProcess = process; double durationCount = 0; int durationUnit = 0; if (serviceProcess != null ) { durationCount = serviceProcess.getDurationCount(); durationUnit = serviceProcess.getDurationUnit(); dossier.setDurationCount(durationCount); dossier.setDurationUnit(durationUnit); } if (durationCount > 0) { Date dueDate = HolidayUtils.getDueDate(new Date(), durationCount, durationUnit, groupId); dossier.setDueDate(dueDate); } } else if (oldDossiers.size() > 0) { flagOldDossier = true; dossier = oldDossiers.get(0); dossier.setApplicantName(input.getApplicantName()); dossier.setApplicantNote(input.getApplicantNote()); dossier.setApplicantIdNo(input.getApplicantIdNo()); dossier.setAddress(input.getAddress()); dossier.setContactEmail(input.getContactEmail()); dossier.setContactName(input.getContactName()); dossier.setContactTelNo(input.getContactTelNo()); dossier.setDelegateName(input.getDelegateName()); dossier.setDelegateEmail(input.getDelegateEmail()); dossier.setDelegateAddress(input.getDelegateAddress()); dossier.setPostalAddress(input.getPostalAddress()); dossier.setPostalCityCode(input.getPostalCityCode()); dossier.setPostalCityName(postalCityName); dossier.setPostalTelNo(input.getPostalTelNo()); dossier.setPostalServiceCode(input.getPostalServiceCode()); dossier.setPostalServiceName(input.getPostalServiceName()); dossier.setPostalDistrictCode(input.getPostalDistrictCode()); dossier.setPostalDistrictName(input.getPostalDistrictName()); dossier.setPostalWardCode(input.getPostalWardCode()); dossier.setPostalWardName(input.getPostalWardName()); dossier.setPostalTelNo(input.getPostalTelNo()); dossier.setViaPostal(viaPostal); dossier.setOriginDossierNo(input.getOriginDossierNo()); dossier.setRegisterBookCode(registerBookCode); dossier.setRegisterBookName(registerBookName); dossier.setSampleCount(sampleCount); dossier.setServiceCode(input.getServiceCode()); dossier.setGovAgencyCode(input.getGovAgencyCode()); dossier.setDossierTemplateNo(input.getDossierTemplateNo()); updateDelegateApplicant(dossier, input); // dossier.setDossierNo(input.getDossierNo()); dossier.setSubmitDate(new Date()); // ServiceProcess serviceProcess = ServiceProcessLocalServiceUtil.fetchServiceProcess(serviceProcessId); ServiceProcess serviceProcess = process; double durationCount = 0; int durationUnit = 0; if (serviceProcess != null ) { durationCount = serviceProcess.getDurationCount(); durationUnit = serviceProcess.getDurationUnit(); dossier.setDurationCount(durationCount); dossier.setDurationUnit(durationUnit); } if (durationCount > 0) { Date dueDate = HolidayUtils.getDueDate(new Date(), durationCount, durationUnit, groupId); dossier.setDueDate(dueDate); } dossier.setOnline(online); if (Validator.isNotNull(input.getDossierName())) dossier.setDossierName(input.getDossierName()); if (serviceProcess != null) { dossier.setProcessNo(serviceProcess.getProcessNo()); } // dossier = DossierLocalServiceUtil.updateDossier(dossier); } else { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"); Date appIdDate = null; try { appIdDate = sdf.parse(input.getApplicantIdDate()); } catch (Exception e) { _log.debug(e); } dossier = dossierLocalService.initDossier(groupId, 0l, referenceUid, counter, input.getServiceCode(), serviceName, input.getGovAgencyCode(), govAgencyName, input.getApplicantName(), input.getApplicantIdType(), input.getApplicantIdNo(), appIdDate, input.getAddress(), input.getCityCode(), cityName, input.getDistrictCode(), districtName, input.getWardCode(), wardName, input.getContactName(), input.getContactTelNo(), input.getContactEmail(), input.getDossierTemplateNo(), password, viaPostal, input.getPostalAddress(), input.getPostalCityCode(), postalCityName, input.getPostalTelNo(), online, process.getDirectNotification(), input.getApplicantNote(), Integer.valueOf(input.getOriginality()), service, process, option, serviceContext); dossier.setDelegateName(input.getDelegateName()); dossier.setDelegateEmail(input.getDelegateEmail()); dossier.setDelegateAddress(input.getDelegateAddress()); if (Validator.isNotNull(input.getDossierName())) { dossier.setDossierName(input.getDossierName()); } else { dossier.setDossierName(serviceName); } dossier.setPostalCityName(postalCityName); dossier.setPostalTelNo(input.getPostalTelNo()); dossier.setPostalServiceCode(input.getPostalServiceCode()); dossier.setPostalServiceName(input.getPostalServiceName()); dossier.setPostalDistrictCode(input.getPostalDistrictCode()); dossier.setPostalDistrictName(input.getPostalDistrictName()); dossier.setPostalWardCode(input.getPostalWardCode()); dossier.setPostalWardName(input.getPostalWardName()); dossier.setOriginDossierNo(input.getOriginDossierNo()); dossier.setRegisterBookCode(registerBookCode); dossier.setRegisterBookName(registerBookName); dossier.setSampleCount(sampleCount); updateDelegateApplicant(dossier, input); if (process != null) { dossier.setProcessNo(process.getProcessNo()); } // dossier = DossierLocalServiceUtil.updateDossier(dossier); } _log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms"); if (originality != DossierTerm.ORIGINALITY_LIENTHONG) { Applicant applicant = ApplicantLocalServiceUtil.fetchByMappingID(serviceContext.getUserId()); if (applicant != null) { updateApplicantInfo(dossier, applicant.getApplicantIdDate(), applicant.getApplicantIdNo(), applicant.getApplicantIdType(), applicant.getApplicantName(), applicant.getAddress(), applicant.getCityCode(), applicant.getCityName(), applicant.getDistrictCode(), applicant.getDistrictName(), applicant.getWardCode(), applicant.getWardName(), applicant.getContactEmail(), applicant.getContactTelNo() ); } } if (Validator.isNull(dossier)) { throw new NotFoundException("Cant add DOSSIER"); } _log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms"); //Create DossierMark _log.debug("flagOldDossier: "+flagOldDossier); _log.debug("originality: "+originality); if ((originality == DossierTerm.ORIGINALITY_MOTCUA || originality == DossierTerm.ORIGINALITY_LIENTHONG) && !flagOldDossier) { String templateNo = dossier.getDossierTemplateNo(); _log.debug("templateNo: "+templateNo); if (Validator.isNotNull(templateNo)) { List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo); // _log.info("partList: "+partList); if (partList != null && partList.size() > 0) { _log.debug("partList.size(): "+partList.size()); _log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms"); org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()]; int count = 0; List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId()); Map<String, DossierMark> mapMarks = new HashMap<>(); for (DossierMark dm : lstMarks) { mapMarks.put(dm.getDossierPartNo(), dm); } for (DossierPart dossierPart : partList) { int fileMark = dossierPart.getFileMark(); String dossierPartNo = dossierPart.getPartNo(); org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel(); model.setDossierId(dossier.getDossierId()); model.setDossierPartNo(dossierPartNo); model.setFileCheck(0); model.setFileMark(fileMark); model.setFileComment(StringPool.BLANK); marks[count++] = model; // DossierMarkLocalServiceUtil.addDossierMark(groupId, dossier.getDossierId(), dossierPartNo, // fileMark, 0, StringPool.BLANK, serviceContext); } dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext); _log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms"); } } } //Create dossier user List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId()); List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId()); if (lstDus.size() == 0) { DossierUserActions duActions = new DossierUserActionsImpl(); // duActions.initDossierUser(groupId, dossier); duActions.initDossierUser(groupId, dossier, process, lstProcessRoles); } if (originality == DossierTerm.ORIGINALITY_DVCTT) { dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true); } _log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms"); // DossierLocalServiceUtil.updateDossier(dossier); if (dossier != null) { // long notificationQueueId = CounterLocalServiceUtil.increment(NotificationQueue.class.getName()); NotificationQueue queue = NotificationQueueLocalServiceUtil.createNotificationQueue(notificationQueueId); //Process add notification queue Date now = new Date(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) + 1); queue.setCreateDate(now); queue.setModifiedDate(now); queue.setGroupId(groupId); queue.setCompanyId(company.getCompanyId()); queue.setNotificationType(NotificationType.DOSSIER_01); queue.setClassName(Dossier.class.getName()); queue.setClassPK(String.valueOf(dossier.getPrimaryKey())); queue.setToUsername(dossier.getUserName()); queue.setToUserId(dossier.getUserId()); queue.setToEmail(dossier.getContactEmail()); queue.setToTelNo(dossier.getContactTelNo()); JSONObject payload = JSONFactoryUtil.createJSONObject(); try { // _log.info("START PAYLOAD: "); payload.put( "Dossier", JSONFactoryUtil.createJSONObject( JSONFactoryUtil.looseSerialize(dossier))); } catch (JSONException parse) { _log.error(parse); } // _log.info("payloadTest: "+payload.toJSONString()); queue.setPayload(payload.toJSONString()); queue.setExpireDate(cal.getTime()); NotificationQueueLocalServiceUtil.addNotificationQueue(queue); } _log.debug("CREATE DOSSIER 6: " + (System.currentTimeMillis() - start) + " ms"); //Add to dossier user based on service process role createDossierUsers(groupId, dossier, process, lstProcessRoles); _log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms"); dossierLocalService.updateDossier(dossier); _log.debug("CREATE DOSSIER 8: " + (System.currentTimeMillis() - start) + " ms"); return dossier; } } public static final String GOVERNMENT_AGENCY = "GOVERNMENT_AGENCY"; public static final String ADMINISTRATIVE_REGION = "ADMINISTRATIVE_REGION"; public static final String VNPOST_CITY_CODE = "VNPOST_CITY_CODE"; public static final String REGISTER_BOOK = "REGISTER_BOOK"; private static final long VALUE_CONVERT_DATE_TIMESTAMP = 1000 * 60 * 60 * 24; private static final long VALUE_CONVERT_HOUR_TIMESTAMP = 1000 * 60 * 60; private static ProcessAction getProcessAction(long groupId, Dossier dossier, String actionCode, long serviceProcessId) throws PortalException { //_log.debug("GET PROCESS ACTION____"); ProcessAction action = null; DossierAction dossierAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId()); try { List<ProcessAction> actions = ProcessActionLocalServiceUtil.getByActionCode(groupId, actionCode, serviceProcessId); //_log.debug("GET PROCESS ACTION____" + groupId + "," + actionCode + "," + serviceProcessId); String dossierStatus = dossier.getDossierStatus(); String dossierSubStatus = dossier.getDossierSubStatus(); String preStepCode; for (ProcessAction act : actions) { preStepCode = act.getPreStepCode(); //_log.debug("LamTV_preStepCode: "+preStepCode); ProcessStep step = ProcessStepLocalServiceUtil.fetchBySC_GID(preStepCode, groupId, serviceProcessId); // _log.info("LamTV_ProcessStep: "+step); if (Validator.isNull(step) && dossierAction == null) { action = act; break; } else { String stepStatus = step != null ? step.getDossierStatus() : StringPool.BLANK; String stepSubStatus = step != null ? step.getDossierSubStatus() : StringPool.BLANK; boolean flagCheck = false; if (dossierAction != null) { if (act.getPreStepCode().equals(dossierAction.getStepCode())) { flagCheck = true; } } else { flagCheck = true; } //_log.debug("LamTV_preStepCode: "+stepStatus + "," + stepSubStatus + "," + dossierStatus + "," + dossierSubStatus + "," + act.getPreCondition() + "," + flagCheck); if (stepStatus.contentEquals(dossierStatus) && StringUtil.containsIgnoreCase(stepSubStatus, dossierSubStatus) && flagCheck) { if (Validator.isNotNull(act.getPreCondition()) && DossierMgtUtils.checkPreCondition(act.getPreCondition().split(StringPool.COMMA), dossier)) { action = act; break; } else if (Validator.isNull(act.getPreCondition())) { action = act; break; } } } } } catch (Exception e) { //_log.debug("NOT PROCESS ACTION"); //_log.debug(e); } return action; } private Log _log = LogFactoryUtil.getLog(CPSDossierBusinessLocalServiceImpl.class); }
modules/backend-dossiermgt/backend-dossiermgt-service/src/main/java/org/opencps/dossiermgt/service/impl/CPSDossierBusinessLocalServiceImpl.java
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package org.opencps.dossiermgt.service.impl; import com.liferay.counter.kernel.service.CounterLocalServiceUtil; import com.liferay.petra.string.StringPool; import com.liferay.portal.kernel.dao.orm.QueryUtil; import com.liferay.portal.kernel.exception.NoSuchUserException; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.json.JSONArray; import com.liferay.portal.kernel.json.JSONException; import com.liferay.portal.kernel.json.JSONFactoryUtil; import com.liferay.portal.kernel.json.JSONObject; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.messaging.Message; import com.liferay.portal.kernel.messaging.MessageBusUtil; import com.liferay.portal.kernel.model.Company; import com.liferay.portal.kernel.model.User; import com.liferay.portal.kernel.service.ServiceContext; import com.liferay.portal.kernel.service.SubscriptionLocalServiceUtil; import com.liferay.portal.kernel.service.UserLocalServiceUtil; import com.liferay.portal.kernel.transaction.Isolation; import com.liferay.portal.kernel.transaction.Propagation; import com.liferay.portal.kernel.transaction.Transactional; import com.liferay.portal.kernel.util.GetterUtil; import com.liferay.portal.kernel.util.ListUtil; import com.liferay.portal.kernel.util.LocaleUtil; import com.liferay.portal.kernel.util.PwdGenerator; import com.liferay.portal.kernel.util.StringUtil; import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.kernel.uuid.PortalUUIDUtil; import java.io.IOException; import java.io.Serializable; import java.net.URLEncoder; import java.sql.Timestamp; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.activation.DataHandler; import javax.ws.rs.HttpMethod; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.opencps.auth.api.BackendAuth; import org.opencps.auth.api.BackendAuthImpl; import org.opencps.auth.api.exception.UnauthenticationException; import org.opencps.auth.api.exception.UnauthorizationException; import org.opencps.auth.api.keys.ActionKeys; import org.opencps.auth.api.keys.NotificationType; import org.opencps.auth.utils.APIDateTimeUtils; import org.opencps.cache.actions.CacheActions; import org.opencps.cache.actions.impl.CacheActionsImpl; import org.opencps.communication.model.NotificationQueue; import org.opencps.communication.model.Notificationtemplate; import org.opencps.communication.model.ServerConfig; import org.opencps.communication.service.NotificationQueueLocalServiceUtil; import org.opencps.communication.service.NotificationtemplateLocalServiceUtil; import org.opencps.communication.service.ServerConfigLocalServiceUtil; import org.opencps.datamgt.model.DictCollection; import org.opencps.datamgt.model.DictItem; import org.opencps.datamgt.model.Holiday; import org.opencps.datamgt.service.DictCollectionLocalServiceUtil; import org.opencps.datamgt.service.DictItemLocalServiceUtil; import org.opencps.datamgt.service.HolidayLocalServiceUtil; import org.opencps.datamgt.util.ExtendDueDateUtils; import org.opencps.datamgt.util.HolidayUtils; import org.opencps.dossiermgt.action.DossierActions; import org.opencps.dossiermgt.action.DossierUserActions; import org.opencps.dossiermgt.action.impl.DossierActionsImpl; import org.opencps.dossiermgt.action.impl.DossierPermission; import org.opencps.dossiermgt.action.impl.DossierUserActionsImpl; import org.opencps.dossiermgt.action.util.AutoFillFormData; import org.opencps.dossiermgt.action.util.DocumentTypeNumberGenerator; import org.opencps.dossiermgt.action.util.DossierActionUtils; import org.opencps.dossiermgt.action.util.DossierMgtUtils; import org.opencps.dossiermgt.action.util.DossierNumberGenerator; import org.opencps.dossiermgt.action.util.DossierPaymentUtils; import org.opencps.dossiermgt.action.util.KeyPay; import org.opencps.dossiermgt.action.util.OpenCPSConfigUtil; import org.opencps.dossiermgt.action.util.PaymentUrlGenerator; import org.opencps.dossiermgt.constants.ActionConfigTerm; import org.opencps.dossiermgt.constants.DossierActionTerm; import org.opencps.dossiermgt.constants.DossierActionUserTerm; import org.opencps.dossiermgt.constants.DossierDocumentTerm; import org.opencps.dossiermgt.constants.DossierFileTerm; import org.opencps.dossiermgt.constants.DossierPartTerm; import org.opencps.dossiermgt.constants.DossierStatusConstants; import org.opencps.dossiermgt.constants.DossierSyncTerm; import org.opencps.dossiermgt.constants.DossierTerm; import org.opencps.dossiermgt.constants.PaymentFileTerm; import org.opencps.dossiermgt.constants.ProcessActionTerm; import org.opencps.dossiermgt.constants.PublishQueueTerm; import org.opencps.dossiermgt.constants.ServerConfigTerm; import org.opencps.dossiermgt.constants.StepConfigTerm; import org.opencps.dossiermgt.exception.DataConflictException; import org.opencps.dossiermgt.exception.NoSuchDossierUserException; import org.opencps.dossiermgt.exception.NoSuchPaymentFileException; import org.opencps.dossiermgt.input.model.DossierInputModel; import org.opencps.dossiermgt.input.model.DossierMultipleInputModel; import org.opencps.dossiermgt.input.model.PaymentFileInputModel; import org.opencps.dossiermgt.model.ActionConfig; import org.opencps.dossiermgt.model.Deliverable; import org.opencps.dossiermgt.model.DocumentType; import org.opencps.dossiermgt.model.Dossier; import org.opencps.dossiermgt.model.DossierAction; import org.opencps.dossiermgt.model.DossierActionUser; import org.opencps.dossiermgt.model.DossierDocument; import org.opencps.dossiermgt.model.DossierFile; import org.opencps.dossiermgt.model.DossierMark; import org.opencps.dossiermgt.model.DossierPart; import org.opencps.dossiermgt.model.DossierTemplate; import org.opencps.dossiermgt.model.DossierUser; import org.opencps.dossiermgt.model.PaymentConfig; import org.opencps.dossiermgt.model.PaymentFile; import org.opencps.dossiermgt.model.ProcessAction; import org.opencps.dossiermgt.model.ProcessOption; import org.opencps.dossiermgt.model.ProcessSequence; import org.opencps.dossiermgt.model.ProcessStep; import org.opencps.dossiermgt.model.ProcessStepRole; import org.opencps.dossiermgt.model.PublishQueue; import org.opencps.dossiermgt.model.ServiceConfig; import org.opencps.dossiermgt.model.ServiceInfo; import org.opencps.dossiermgt.model.ServiceProcess; import org.opencps.dossiermgt.model.ServiceProcessRole; import org.opencps.dossiermgt.model.StepConfig; import org.opencps.dossiermgt.scheduler.InvokeREST; import org.opencps.dossiermgt.scheduler.RESTFulConfiguration; import org.opencps.dossiermgt.service.DocumentTypeLocalServiceUtil; import org.opencps.dossiermgt.service.DossierActionLocalServiceUtil; import org.opencps.dossiermgt.service.DossierActionUserLocalServiceUtil; import org.opencps.dossiermgt.service.DossierDocumentLocalServiceUtil; import org.opencps.dossiermgt.service.DossierFileLocalServiceUtil; import org.opencps.dossiermgt.service.DossierLocalServiceUtil; import org.opencps.dossiermgt.service.ProcessActionLocalServiceUtil; import org.opencps.dossiermgt.service.ProcessStepLocalServiceUtil; import org.opencps.dossiermgt.service.PublishQueueLocalServiceUtil; import org.opencps.dossiermgt.service.StepConfigLocalServiceUtil; import org.opencps.dossiermgt.service.base.CPSDossierBusinessLocalServiceBaseImpl; import org.opencps.dossiermgt.service.persistence.DossierActionUserPK; import org.opencps.dossiermgt.service.persistence.DossierUserPK; import org.opencps.dossiermgt.service.persistence.ServiceProcessRolePK; import org.opencps.usermgt.model.Applicant; import org.opencps.usermgt.model.Employee; import org.opencps.usermgt.model.EmployeeJobPos; import org.opencps.usermgt.model.JobPos; import org.opencps.usermgt.model.WorkingUnit; import org.opencps.usermgt.service.ApplicantLocalServiceUtil; import org.opencps.usermgt.service.EmployeeJobPosLocalServiceUtil; import org.opencps.usermgt.service.EmployeeLocalServiceUtil; import org.opencps.usermgt.service.JobPosLocalServiceUtil; import org.opencps.usermgt.service.WorkingUnitLocalServiceUtil; import backend.auth.api.exception.NotFoundException; /** * The implementation of the cps dossier business local service. * * <p> * All custom service methods should be put in this class. Whenever methods are added, rerun ServiceBuilder to copy their definitions into the {@link org.opencps.dossiermgt.service.CPSDossierBusinessLocalService} interface. * * <p> * This is a local service. Methods of this service will not have security checks based on the propagated JAAS credentials because this service can only be accessed from within the same VM. * </p> * * @author huymq * @see CPSDossierBusinessLocalServiceBaseImpl * @see org.opencps.dossiermgt.service.CPSDossierBusinessLocalServiceUtil */ @Transactional(isolation = Isolation.PORTAL, rollbackFor = { PortalException.class, SystemException.class }) public class CPSDossierBusinessLocalServiceImpl extends CPSDossierBusinessLocalServiceBaseImpl { /* * NOTE FOR DEVELOPERS: * * Never reference this class directly. Always use {@link org.opencps.dossiermgt.service.CPSDossierBusinessLocalServiceUtil} to access the cps dossier business local service. */ public static final String DOSSIER_SATUS_DC_CODE = "DOSSIER_STATUS"; public static final String DOSSIER_SUB_SATUS_DC_CODE = "DOSSIER_SUB_STATUS"; CacheActions cache = new CacheActionsImpl(); int ttl = OpenCPSConfigUtil.getCacheTTL(); private Dossier createCrossDossier(long groupId, ProcessAction proAction, ProcessStep curStep, DossierAction previousAction, Employee employee, Dossier dossier, User user, ServiceContext context) throws PortalException { if (Validator.isNotNull(proAction.getCreateDossiers())) { //Create new HSLT String GOVERNMENT_AGENCY = "GOVERNMENT_AGENCY"; String govAgencyName = getDictItemName(groupId, GOVERNMENT_AGENCY, proAction.getCreateDossiers()); String createDossiers = proAction.getCreateDossiers(); String govAgencyCode = StringPool.BLANK; String serviceCode = dossier.getServiceCode(); String dossierTemplateNo = dossier.getDossierTemplateNo(); if (createDossiers.contains(StringPool.POUND)) { String[] splitCDs = createDossiers.split(StringPool.POUND); if (splitCDs.length == 2) { govAgencyCode = splitCDs[0]; if (splitCDs[1].contains(StringPool.AT)) { if (splitCDs[1].split(StringPool.AT).length != 2) { throw new PortalException("Cross dossier config error"); } else { dossierTemplateNo = splitCDs[1].split(StringPool.AT)[0]; serviceCode = splitCDs[1].split(StringPool.AT)[1]; } } else { govAgencyCode = splitCDs[0]; } } } else { if (createDossiers.contains(StringPool.AT)) { if (createDossiers.split(StringPool.AT).length != 2) { throw new PortalException("Cross dossier config error"); } else { govAgencyCode = createDossiers.split(StringPool.AT)[0]; serviceCode = createDossiers.split(StringPool.AT)[1]; } } else { govAgencyCode = createDossiers; } } ServiceConfig serviceConfig = serviceConfigLocalService.getBySICodeAndGAC(groupId, dossier.getServiceCode(), govAgencyCode); if (serviceConfig != null) { List<ProcessOption> lstOptions = processOptionLocalService.getByServiceProcessId(serviceConfig.getServiceConfigId()); // ProcessOption foundOption = null; if (createDossiers.contains(StringPool.POUND)) { for (ProcessOption po : lstOptions) { DossierTemplate dt = dossierTemplateLocalService.fetchDossierTemplate(po.getDossierTemplateId()); if (dt.getTemplateNo().equals(dossierTemplateNo)) { foundOption = po; break; } } } else { if (lstOptions.size() > 0) { foundOption = lstOptions.get(0); } } if (foundOption != null) { ServiceProcess ltProcess = serviceProcessLocalService.fetchServiceProcess(foundOption.getServiceProcessId()); DossierTemplate dossierTemplate = dossierTemplateLocalService.fetchDossierTemplate(foundOption.getDossierTemplateId()); // String delegateName = dossier.getDelegateName(); String delegateName = dossier.getGovAgencyName(); String delegateAddress = dossier.getDelegateAddress(); String delegateTelNo = dossier.getDelegateTelNo(); String delegateEmail = dossier.getDelegateEmail(); String delegateIdNo = dossier.getGovAgencyCode(); // Dossier oldHslt = DossierLocalServiceUtil.getByG_AN_SC_GAC_DTNO(groupId, dossier.getApplicantIdNo(), dossier.getServiceCode(), govAgencyCode, dossierTemplate.getTemplateNo()); // long hsltDossierId = (oldHslt != null ? oldHslt.getDossierId() : 0l); Dossier hsltDossier = dossierLocalService.initDossier(groupId, 0l, UUID.randomUUID().toString(), dossier.getCounter(), dossier.getServiceCode(), dossier.getServiceName(), govAgencyCode, govAgencyName, dossier.getApplicantName(), dossier.getApplicantIdType(), dossier.getApplicantIdNo(), dossier.getApplicantIdDate(), dossier.getAddress(), dossier.getCityCode(), dossier.getCityName(), dossier.getDistrictCode(), dossier.getDistrictName(), dossier.getWardCode(), dossier.getWardName(), dossier.getContactName(), dossier.getContactTelNo(), dossier.getContactEmail(), dossierTemplate.getTemplateNo(), dossier.getPassword(), dossier.getViaPostal(), dossier.getPostalAddress(), dossier.getPostalCityCode(), dossier.getPostalCityName(), dossier.getPostalTelNo(), dossier.getOnline(), dossier.getNotification(), dossier.getApplicantNote(), DossierTerm.ORIGINALITY_DVCTT, context); WorkingUnit wu = WorkingUnitLocalServiceUtil.fetchByF_govAgencyCode(dossier.getGroupId(), dossier.getGovAgencyCode()); if (wu != null) { delegateName = wu.getName(); delegateAddress = wu.getAddress(); delegateTelNo = wu.getTelNo(); delegateEmail = wu.getEmail(); delegateIdNo = wu.getGovAgencyCode(); if (hsltDossier != null) { hsltDossier.setDelegateName(delegateName); hsltDossier.setDelegateAddress(delegateAddress); hsltDossier.setDelegateTelNo(delegateTelNo); hsltDossier.setDelegateEmail(delegateEmail); hsltDossier.setDelegateIdNo(delegateIdNo); hsltDossier.setNew(false); hsltDossier = dossierLocalService.updateDossier(hsltDossier); } } else if (user != null) { if (employee != null) { delegateName = employee.getFullName(); delegateAddress = dossier.getGovAgencyName(); delegateTelNo = employee.getTelNo(); delegateEmail = employee.getEmail(); if (hsltDossier != null) { hsltDossier.setDelegateName(delegateName); hsltDossier.setDelegateAddress(delegateAddress); hsltDossier.setDelegateTelNo(delegateTelNo); hsltDossier.setDelegateEmail(delegateEmail); hsltDossier.setDelegateIdNo(delegateIdNo); hsltDossier.setNew(false); hsltDossier = dossierLocalService.updateDossier(hsltDossier); } } } // String dossierNote = StringPool.BLANK; if (previousAction != null) { dossierNote = previousAction.getActionNote(); if (Validator.isNotNull(dossierNote)) { dossierNote = previousAction.getStepInstruction(); } } if (hsltDossier != null) { //Set HSLT dossierId to origin dossier hsltDossier.setOriginDossierId(dossier.getDossierId()); if (ltProcess.getServerNo().contains(StringPool.COMMA)) { if (!serviceCode.equals(dossier.getServiceCode())) { String serverNoProcess = ltProcess.getServerNo().split(StringPool.COMMA)[0]; hsltDossier.setServerNo(serverNoProcess + StringPool.AT + serviceCode + StringPool.COMMA + ltProcess.getServerNo().split(StringPool.COMMA)[1]); hsltDossier = dossierLocalService.updateDossier(hsltDossier); } } else { hsltDossier.setServerNo(ltProcess.getServerNo()); } //Update DossierName hsltDossier.setDossierName(dossier.getDossierName()); hsltDossier.setOriginDossierNo(dossier.getDossierNo()); dossierLocalService.updateDossier(hsltDossier); JSONObject jsonDataStatusText = getStatusText(groupId, DOSSIER_SATUS_DC_CODE, DossierTerm.DOSSIER_STATUS_NEW, StringPool.BLANK); hsltDossier = dossierLocalService.updateStatus(groupId, hsltDossier.getDossierId(), hsltDossier.getReferenceUid(), DossierTerm.DOSSIER_STATUS_NEW, jsonDataStatusText != null ? jsonDataStatusText.getString(DossierTerm.DOSSIER_STATUS_NEW) : StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, dossierNote, context); } else { return null; } JSONObject jsonDataStatusText = getStatusText(groupId, DOSSIER_SATUS_DC_CODE, DossierTerm.DOSSIER_STATUS_INTEROPERATING, StringPool.BLANK); if (curStep != null) { dossier = dossierLocalService.updateStatus(groupId, dossier.getDossierId(), dossier.getReferenceUid(), DossierTerm.DOSSIER_STATUS_INTEROPERATING, jsonDataStatusText != null ? jsonDataStatusText.getString(DossierTerm.DOSSIER_STATUS_INTEROPERATING) : StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, curStep.getLockState(), dossierNote, context); dossier.setDossierStatus(DossierTerm.DOSSIER_STATUS_INTEROPERATING); dossier.setDossierStatusText(jsonDataStatusText != null ? jsonDataStatusText.getString(DossierTerm.DOSSIER_STATUS_INTEROPERATING) : StringPool.BLANK); dossier.setDossierSubStatus(StringPool.BLANK); dossier.setDossierSubStatusText(StringPool.BLANK); dossier.setLockState(curStep.getLockState()); dossier.setDossierNote(dossierNote);; } return hsltDossier; } else { return null; } } else { return null; } } else { return null; } } private void createDossierDocument(long groupId, long userId, ActionConfig actionConfig, Dossier dossier, DossierAction dossierAction, JSONObject payloadObject, Employee employee, User user, ServiceContext context) throws com.liferay.portal.kernel.search.ParseException, JSONException { //Check if generate dossier document ActionConfig ac = actionConfig; if (ac != null) { if (dossier.getOriginality() != DossierTerm.ORIGINALITY_DVCTT) { if (Validator.isNotNull(ac.getDocumentType()) && !ac.getActionCode().startsWith("@")) { //Generate document DocumentType dt = DocumentTypeLocalServiceUtil.getByTypeCode(groupId, ac.getDocumentType()); if (dt != null) { String documentCode = DocumentTypeNumberGenerator.generateDocumentTypeNumber(groupId, ac.getCompanyId(), dt.getDocumentTypeId()); DossierDocument dossierDocument = DossierDocumentLocalServiceUtil.addDossierDoc(groupId, dossier.getDossierId(), UUID.randomUUID().toString(), dossierAction.getDossierActionId(), dt.getTypeCode(), dt.getDocumentName(), documentCode, 0L, dt.getDocSync(), context); //Generate PDF String formData = dossierAction.getPayload(); JSONObject payloadTmp = JSONFactoryUtil.createJSONObject(formData); if (payloadTmp != null && payloadTmp.has("complementDate")) { if (payloadTmp.getLong("complementDate") > 0) { Timestamp ts = new Timestamp(payloadTmp.getLong("complementDate")); SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy"); payloadTmp.put("complementDate", format.format(ts)); } } JSONObject formDataObj = processMergeDossierFormData(dossier, payloadTmp); formDataObj = processMergeDossierProcessRole(dossier, 1, formDataObj, dossierAction); formDataObj.put("url", context.getPortalURL()); if (employee != null) { formDataObj.put("userName", employee.getFullName()); } else { formDataObj.put("userName", user.getFullName()); } Message message = new Message(); // _log.info("Document script: " + dt.getDocumentScript()); JSONObject msgData = JSONFactoryUtil.createJSONObject(); msgData.put("className", DossierDocument.class.getName()); msgData.put("classPK", dossierDocument.getDossierDocumentId()); msgData.put("jrxmlTemplate", dt.getDocumentScript()); msgData.put("formData", formDataObj.toJSONString()); msgData.put("userId", userId); message.put("msgToEngine", msgData); MessageBusUtil.sendMessage("jasper/engine/out/destination", message); payloadObject.put("dossierDocument", dossierDocument.getDossierDocumentId()); } } } } } private void createDossierSync(long groupId, long userId, ActionConfig actionConfig, ProcessAction proAction, DossierAction dossierAction, Dossier dossier, int syncType, ProcessOption option, JSONObject payloadObject, Map<String, Boolean> flagChanged, String actionCode, String actionUser, String actionNote, ServiceProcess serviceProcess, ServiceContext context) throws PortalException { //Create DossierSync String dossierRefUid = dossier.getReferenceUid(); String syncRefUid = UUID.randomUUID().toString(); if (syncType > 0) { int state = DossierActionUtils.getSyncState(syncType, dossier); //If state = 1 set pending dossier if (state == DossierSyncTerm.STATE_WAITING_SYNC) { if (dossierAction != null) { dossierAction.setPending(true); dossierActionLocalService.updateDossierAction(dossierAction); } } else { if (dossierAction != null) { dossierAction.setPending(false); dossierActionLocalService.updateDossierAction(dossierAction); } } //Update payload JSONArray dossierFilesArr = JSONFactoryUtil.createJSONArray(); List<DossierFile> lstFiles = DossierFileLocalServiceUtil.findByDID(dossier.getDossierId()); if (actionConfig.getSyncType() == DossierSyncTerm.SYNCTYPE_REQUEST) { if (dossier.getOriginDossierId() == 0) { if (lstFiles.size() > 0) { for (DossierFile df : lstFiles) { JSONObject dossierFileObj = JSONFactoryUtil.createJSONObject(); dossierFileObj.put(DossierFileTerm.REFERENCE_UID, df.getReferenceUid()); dossierFilesArr.put(dossierFileObj); } } } else { // ServiceConfig serviceConfig = ServiceConfigLocalServiceUtil.getBySICodeAndGAC(groupId, dossier.getServiceCode(), dossier.getGovAgencyCode()); // List<ProcessOption> lstOptions = ProcessOptionLocalServiceUtil.getByServiceProcessId(serviceConfig.getServiceConfigId()); // if (serviceConfig != null) { // if (lstOptions.size() > 0) { // ProcessOption processOption = lstOptions.get(0); ProcessOption processOption = option; DossierTemplate dossierTemplate = dossierTemplateLocalService.fetchDossierTemplate(processOption.getDossierTemplateId()); List<DossierPart> lstParts = dossierPartLocalService.getByTemplateNo(groupId, dossierTemplate.getTemplateNo()); List<DossierFile> lstOriginFiles = dossierFileLocalService.findByDID(dossier.getOriginDossierId()); if (lstOriginFiles.size() > 0) { for (DossierFile df : lstOriginFiles) { boolean flagHslt = false; for (DossierPart dp : lstParts) { if (dp.getPartNo().equals(df.getDossierPartNo())) { flagHslt = true; break; } } if (flagHslt) { JSONObject dossierFileObj = JSONFactoryUtil.createJSONObject(); dossierFileObj.put(DossierFileTerm.REFERENCE_UID, df.getReferenceUid()); dossierFilesArr.put(dossierFileObj); } } } // } // } } } else { //Sync result files } payloadObject.put("dossierFiles", dossierFilesArr); if (Validator.isNotNull(proAction.getReturnDossierFiles())) { List<DossierFile> lsDossierFile = lstFiles; dossierFilesArr = JSONFactoryUtil.createJSONArray(); // check return file List<String> returnDossierFileTemplateNos = ListUtil .toList(StringUtil.split(proAction.getReturnDossierFiles())); for (DossierFile dossierFile : lsDossierFile) { if (returnDossierFileTemplateNos.contains(dossierFile.getFileTemplateNo())) { JSONObject dossierFileObj = JSONFactoryUtil.createJSONObject(); dossierFileObj.put(DossierFileTerm.REFERENCE_UID, dossierFile.getReferenceUid()); dossierFilesArr.put(dossierFileObj); } } payloadObject.put("dossierFiles", dossierFilesArr); } List<DossierDocument> lstDossierDocuments = dossierDocumentLocalService.getDossierDocumentList(dossier.getDossierId(), QueryUtil.ALL_POS, QueryUtil.ALL_POS); JSONArray dossierDocumentArr = JSONFactoryUtil.createJSONArray(); for (DossierDocument dossierDocument : lstDossierDocuments) { JSONObject dossierDocumentObj = JSONFactoryUtil.createJSONObject(); dossierDocumentObj.put(DossierDocumentTerm.REFERENCE_UID, dossierDocument.getReferenceUid()); dossierDocumentArr.put(dossierDocumentObj); } payloadObject.put("dossierFiles", dossierFilesArr); payloadObject.put("dossierDocuments", dossierDocumentArr); //Put dossier note payloadObject.put(DossierTerm.DOSSIER_NOTE, dossier.getDossierNote()); //Put dossier note payloadObject.put(DossierTerm.SUBMIT_DATE, dossier.getSubmitDate() != null ? dossier.getSubmitDate().getTime() : 0); // _log.info("Flag changed: " + flagChanged); payloadObject = DossierActionUtils.buildChangedPayload(payloadObject, flagChanged, dossier); if (Validator.isNotNull(dossier.getServerNo()) && dossier.getServerNo().split(StringPool.COMMA).length > 1) { String serverNo = dossier.getServerNo().split(StringPool.COMMA)[0].split(StringPool.AT)[0]; dossierSyncLocalService.updateDossierSync(groupId, userId, dossier.getDossierId(), dossierRefUid, syncRefUid, dossierAction.getPrimaryKey(), actionCode, proAction.getActionName(), actionUser, actionNote, syncType, actionConfig.getInfoType(), payloadObject.toJSONString(), serverNo, state); } else { dossierSyncLocalService.updateDossierSync(groupId, userId, dossier.getDossierId(), dossierRefUid, syncRefUid, dossierAction.getPrimaryKey(), actionCode, proAction.getActionName(), actionUser, actionNote, syncType, actionConfig.getInfoType(), payloadObject.toJSONString(), dossier.getServerNo(), state); } //Gửi thông tin hồ sơ để tra cứu if (state == DossierSyncTerm.STATE_NOT_SYNC && actionConfig != null && actionConfig.getEventType() == ActionConfigTerm.EVENT_TYPE_SENT) { publishEvent(dossier, context); } } else if (actionConfig != null && actionConfig.getEventType() == ActionConfigTerm.EVENT_TYPE_SENT) { publishEvent(dossier, context); } } private void doMappingAction(long groupId, long userId, Employee employee, Dossier dossier, ActionConfig actionConfig, String actionUser, String actionNote, String payload, String assignUsers, String payment,ServiceContext context) throws PortalException, Exception { if (Validator.isNotNull(actionConfig) && Validator.isNotNull(actionConfig.getMappingAction())) { ActionConfig mappingConfig = actionConfigLocalService.getByCode(groupId, actionConfig.getMappingAction()); if (dossier.getOriginDossierId() != 0) { Dossier hslt = dossierLocalService.fetchDossier(dossier.getOriginDossierId()); ProcessOption optionHslt = getProcessOption(hslt.getServiceCode(), hslt.getGovAgencyCode(), hslt.getDossierTemplateNo(), groupId); ProcessAction actionHslt = getProcessAction(groupId, hslt.getDossierId(), hslt.getReferenceUid(), actionConfig.getMappingAction(), optionHslt.getServiceProcessId()); String actionUserHslt = actionUser; if (employee != null) { actionUserHslt = actionUser; } if (DossierTerm.DOSSIER_STATUS_NEW.equals(hslt.getDossierStatus())) { Date now = new Date(); hslt.setSubmitDate(now); hslt = dossierLocalService.updateDossier(hslt); try { JSONObject payloadObj = JSONFactoryUtil.createJSONObject(payload); payloadObj.put(DossierTerm.SUBMIT_DATE, now.getTime()); payload = payloadObj.toJSONString(); } catch (JSONException e) { _log.debug(e); } } doAction(groupId, userId, hslt, optionHslt, actionHslt, actionConfig.getMappingAction(), actionUserHslt, actionNote, payload, assignUsers, payment, mappingConfig.getSyncType(), context); } else { Dossier originDossier = dossierLocalService.getByOrigin(groupId, dossier.getDossierId()); if (originDossier != null) { ProcessOption optionOrigin = getProcessOption(originDossier.getServiceCode(), originDossier.getGovAgencyCode(), originDossier.getDossierTemplateNo(), groupId); ProcessAction actionOrigin = getProcessAction(groupId, originDossier.getDossierId(), originDossier.getReferenceUid(), actionConfig.getMappingAction(), optionOrigin.getServiceProcessId()); doAction(groupId, userId, originDossier, optionOrigin, actionOrigin, actionConfig.getMappingAction(), actionUser, actionNote, payload, assignUsers, payment, mappingConfig.getSyncType(), context); } } } } private DossierAction createActionAndAssignUser(long groupId, long userId, ProcessStep curStep, ActionConfig actionConfig, DossierAction dossierAction, DossierAction previousAction, ProcessAction proAction, Dossier dossier, String actionCode, String actionUser, String actionNote, String payload, String assignUsers, String payment, ServiceProcess serviceProcess, ProcessOption option, Map<String, Boolean> flagChanged, ServiceContext context) throws PortalException { int actionOverdue = getActionDueDate(groupId, dossier.getDossierId(), dossier.getReferenceUid(), proAction.getProcessActionId()); String actionName = proAction.getActionName(); String prevStatus = dossier.getDossierStatus(); if (curStep != null) { String curStatus = curStep.getDossierStatus(); String curSubStatus = curStep.getDossierSubStatus(); String stepCode = curStep.getStepCode(); String stepName = curStep.getStepName(); String stepInstruction = curStep.getStepInstruction(); String sequenceNo = curStep.getSequenceNo(); JSONObject jsonDataStatusText = getStatusText(groupId, DOSSIER_SATUS_DC_CODE, curStatus, curSubStatus); String fromStepCode = previousAction != null ? previousAction.getStepCode() : StringPool.BLANK; String fromStepName = previousAction != null ? previousAction.getStepName() : StringPool.BLANK; String fromSequenceNo = previousAction != null ? previousAction.getSequenceNo() : StringPool.BLANK; int state = DossierActionTerm.STATE_WAITING_PROCESSING; int eventStatus = (actionConfig != null ? (actionConfig.getEventType() == ActionConfigTerm.EVENT_TYPE_NOT_SENT ? DossierActionTerm.EVENT_STATUS_NOT_CREATED : DossierActionTerm.EVENT_STATUS_WAIT_SENDING) : DossierActionTerm.EVENT_STATUS_NOT_CREATED); boolean rollbackable = false; if (actionConfig != null) { if (actionConfig.getRollbackable()) { rollbackable = true; } else { } } else { if (proAction.isRollbackable()) { rollbackable = true; } else { } } dossierAction = dossierActionLocalService.updateDossierAction(groupId, 0, dossier.getDossierId(), serviceProcess.getServiceProcessId(), dossier.getDossierActionId(), fromStepCode, fromStepName, fromSequenceNo, actionCode, actionUser, actionName, actionNote, actionOverdue, stepCode, stepName, sequenceNo, null, 0l, payload, stepInstruction, state, eventStatus, rollbackable, context); dossier.setDossierActionId(dossierAction.getDossierActionId()); String dossierNote = StringPool.BLANK; if (dossierAction != null) { dossierNote = dossierAction.getActionNote(); if (Validator.isNotNull(dossierNote)) { dossierNote = dossierAction.getStepInstruction(); } } //Update previous action nextActionId Date now = new Date(); if (previousAction != null && dossierAction != null) { previousAction.setNextActionId(dossierAction.getDossierActionId()); previousAction.setState(DossierActionTerm.STATE_ALREADY_PROCESSED); previousAction.setModifiedDate(now); previousAction = dossierActionLocalService.updateDossierAction(previousAction); } updateStatus(dossier, curStatus, jsonDataStatusText != null ? jsonDataStatusText.getString(curStatus) : StringPool.BLANK, curSubStatus, jsonDataStatusText != null ? jsonDataStatusText.getString(curSubStatus) : StringPool.BLANK, curStep.getLockState(), dossierNote, context); //Cập nhật cờ đồng bộ ngày tháng sang các hệ thống khác flagChanged = updateProcessingDate(dossierAction, previousAction, curStep, dossier, curStatus, curSubStatus, prevStatus, actionConfig, option, serviceProcess, context); dossierAction = dossierActionLocalService.fetchDossierAction(dossier.getDossierActionId()); } //Thiết lập quyền thao tác hồ sơ int allowAssignUser = proAction.getAllowAssignUser(); if (allowAssignUser != ProcessActionTerm.NOT_ASSIGNED) { if (Validator.isNotNull(assignUsers)) { JSONArray assignedUsersArray = JSONFactoryUtil.createJSONArray(assignUsers); assignDossierActionUser(dossier, allowAssignUser, dossierAction, userId, groupId, proAction.getAssignUserId(), assignedUsersArray); if (OpenCPSConfigUtil.isNotificationEnable()) { createNotificationSMS(userId, groupId, dossier, assignedUsersArray, dossierAction, context); } } else { initDossierActionUser(proAction, dossier, allowAssignUser, dossierAction, userId, groupId, proAction.getAssignUserId()); } } else { //Process role as step if (Validator.isNotNull(curStep.getRoleAsStep())) { copyRoleAsStep(curStep, dossier); } else { initDossierActionUser(proAction, dossier, allowAssignUser, dossierAction, userId, groupId, proAction.getAssignUserId()); } } return dossierAction; } private DossierAction doActionInsideProcess(long groupId, long userId, Dossier dossier, ActionConfig actionConfig, ProcessOption option, ProcessAction proAction, String actionCode, String actionUser, String actionNote, String payload, String assignUsers, String payment, int syncType, ServiceContext context) throws PortalException, SystemException, Exception { context.setUserId(userId); DossierAction dossierAction = null; Map<String, Boolean> flagChanged = null; JSONObject payloadObject = JSONFactoryUtil.createJSONObject(); User user = userLocalService.fetchUser(userId); String dossierStatus = dossier.getDossierStatus().toLowerCase(); Employee employee = null; Serializable employeeCache = cache.getFromCache("Employee", groupId +"_"+ userId); // _log.info("EMPLOYEE CACHE: " + employeeCache); if (employeeCache == null) { employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userId); if (employee != null) { cache.addToCache("Employee", groupId +"_"+ userId, (Serializable) employee, ttl); } } else { employee = (Employee) employeeCache; } try { JSONFactoryUtil.createJSONObject(payload); } catch (JSONException e) { _log.debug(e); } if (Validator.isNotNull(dossierStatus)) { if(!"new".equals(dossierStatus)) { } else if (dossier.getOriginality() == DossierTerm.ORIGINALITY_DVCTT) { dossier.setSubmitDate(new Date()); } } long dossierId = dossier.getDossierId(); ServiceProcess serviceProcess = null; DossierAction previousAction = null; if (dossier.getDossierActionId() != 0) { previousAction = dossierActionLocalService.fetchDossierAction(dossier.getDossierActionId()); } //Cập nhật thông tin hồ sơ dựa vào payload truyền vào khi thực hiện thao tác if (Validator.isNotNull(payload)) { JSONObject pl = payloadObject; updateDossierPayload(dossier, pl); } if ((option != null || previousAction != null) && proAction != null) { long serviceProcessId = (option != null ? option.getServiceProcessId() : previousAction.getServiceProcessId()); Serializable serviceProcessCache = cache.getFromCache("ServiceProcess", groupId +"_"+ serviceProcessId); if (serviceProcessCache == null) { serviceProcess = serviceProcessLocalService.fetchServiceProcess(serviceProcessId); if (serviceProcess != null) { cache.addToCache("ServiceProcess", groupId +"_"+ serviceProcessId, (Serializable) serviceProcess, ttl); } } else { serviceProcess = (ServiceProcess) serviceProcessCache; } String paymentFee = StringPool.BLANK; String postStepCode = proAction.getPostStepCode(); //Xử lý phiếu thanh toán processPaymentFile(groupId, userId, payment, option, proAction, previousAction, dossier, context); //Bước sau không có thì mặc định quay lại bước trước đó if (Validator.isNull(postStepCode)) { postStepCode = previousAction.getFromStepCode(); ProcessStep backCurStep = processStepLocalService.fetchBySC_GID(postStepCode, groupId, serviceProcessId); String curStatus = backCurStep.getDossierStatus(); String curSubStatus = backCurStep.getDossierSubStatus(); JSONObject jsonDataStatusText = getStatusText(groupId, DOSSIER_SATUS_DC_CODE, curStatus, curSubStatus); //update dossierStatus dossier = DossierLocalServiceUtil.updateStatus(groupId, dossierId, dossier.getReferenceUid(), curStatus, jsonDataStatusText != null ? jsonDataStatusText.getString(curStatus) : StringPool.BLANK, curSubStatus, jsonDataStatusText != null ? jsonDataStatusText.getString(curSubStatus) : StringPool.BLANK, backCurStep.getLockState(), dossier.getDossierNote(), context); dossier.setDossierActionId(previousAction.getPreviousActionId()); dossierLocalService.updateDossier(dossier); return previousAction; } ProcessStep curStep = processStepLocalService.fetchBySC_GID(postStepCode, groupId, serviceProcessId); //Kiểm tra cấu hình cần tạo hồ sơ liên thông Dossier hsltDossier = createCrossDossier(groupId, proAction, curStep, previousAction, employee, dossier, user, context); if (Validator.isNotNull(proAction.getCreateDossiers())) { if (Validator.isNull(hsltDossier)) { return null; } } //Cập nhật hành động và quyền người dùng với hồ sơ dossierAction = createActionAndAssignUser(groupId, userId, curStep, actionConfig, dossierAction, previousAction, proAction, dossier, actionCode, actionUser, actionNote, payload, assignUsers, paymentFee, serviceProcess, option, flagChanged, context); // dossier = dossierLocalService.updateDossier(dossier); //Tạo văn bản đính kèm createDossierDocument(groupId, userId, actionConfig, dossier, dossierAction, payloadObject, employee, user, context); //Kiểm tra xem có gửi dịch vụ vận chuyển hay không if (proAction.getPreCondition().toLowerCase().contains("sendviapostal=1")) { vnpostEvent(dossier); } } else { } //Create notification if (OpenCPSConfigUtil.isNotificationEnable()) { createNotificationQueue(user, groupId, dossier, actionConfig, dossierAction, context); } //Create subcription createSubcription(userId, groupId, dossier, actionConfig, dossierAction, context); //Tạo thông tin đồng bộ hồ sơ createDossierSync(groupId, userId, actionConfig, proAction, dossierAction, dossier, syncType, option, payloadObject, flagChanged, actionCode, actionUser, actionNote, serviceProcess, context); //Thực hiện thao tác lên hồ sơ gốc hoặc hồ sơ liên thông trong trường hợp có cấu hình mappingAction doMappingAction(groupId, userId, employee, dossier, actionConfig, actionUser, actionNote, payload, assignUsers, payment, context); dossier = dossierLocalService.updateDossier(dossier); // Indexer<Dossier> indexer = IndexerRegistryUtil // .nullSafeGetIndexer(Dossier.class); // indexer.reindex(dossier); return dossierAction; } @Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class }) public DossierAction doAction(long groupId, long userId, Dossier dossier, ProcessOption option, ProcessAction proAction, String actionCode, String actionUser, String actionNote, String payload, String assignUsers, String payment, int syncType, ServiceContext context) throws PortalException, SystemException, Exception { context.setUserId(userId); DossierAction dossierAction = null; ActionConfig actionConfig = null; actionConfig = actionConfigLocalService.getByCode(groupId, actionCode); if (actionConfig != null && !actionConfig.getInsideProcess()) { dossierAction = doActionOutsideProcess(groupId, userId, dossier, actionConfig, option, proAction, actionCode, actionUser, actionNote, payload, assignUsers, payment, syncType, context); } else { dossierAction = doActionInsideProcess(groupId, userId, dossier, actionConfig, option, proAction, actionCode, actionUser, actionNote, payload, assignUsers, payment, syncType, context); } return dossierAction; } private void createNotificationQueue(User user, long groupId, Dossier dossier, ActionConfig actionConfig, DossierAction dossierAction, ServiceContext context) throws PortalException { // DossierAction dossierAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId()); // User u = UserLocalServiceUtil.fetchUser(userId); JSONObject payloadObj = JSONFactoryUtil.createJSONObject(); try { payloadObj.put( "Dossier", JSONFactoryUtil.createJSONObject( JSONFactoryUtil.looseSerialize(dossier))); if (dossierAction != null) { payloadObj.put("actionCode", dossierAction.getActionCode()); payloadObj.put("actionUser", dossierAction.getActionUser()); payloadObj.put("actionName", dossierAction.getActionName()); payloadObj.put("actionNote", dossierAction.getActionNote()); } } catch (Exception e) { _log.error(e); } if (actionConfig != null && Validator.isNotNull(actionConfig.getNotificationType())) { // Notificationtemplate notiTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, actionConfig.getNotificationType()); Serializable notiCache = cache.getFromCache("NotificationTemplate", groupId +"_"+ actionConfig.getNotificationType()); Notificationtemplate notiTemplate = null; // notiTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, actionConfig.getNotificationType()); if (notiCache == null) { notiTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, actionConfig.getNotificationType()); if (notiTemplate != null) { cache.addToCache("NotificationTemplate", groupId +"_"+ actionConfig.getNotificationType(), (Serializable) notiTemplate, ttl); } } else { notiTemplate = (Notificationtemplate) notiCache; } Date now = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(now); if (notiTemplate != null) { if ("minutely".equals(notiTemplate.getInterval())) { cal.add(Calendar.MINUTE, notiTemplate.getExpireDuration()); } else if ("hourly".equals(notiTemplate.getInterval())) { cal.add(Calendar.HOUR, notiTemplate.getExpireDuration()); } else { cal.add(Calendar.MINUTE, notiTemplate.getExpireDuration()); } Date expired = cal.getTime(); if (actionConfig.getNotificationType().startsWith("APLC")) { if (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA || dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) { try { // Applicant applicant = ApplicantLocalServiceUtil.fetchByAppId(dossier.getApplicantIdNo()); List<Applicant> applicants = ApplicantLocalServiceUtil.findByAppIds(dossier.getApplicantIdNo()); Applicant foundApplicant = (applicants.isEmpty() ? null : applicants.get(0)); for (Applicant applicant : applicants) { long toUserId = (applicant != null ? applicant.getMappingUserId() : 0l); if (toUserId != 0) { foundApplicant = applicant; break; } } if (foundApplicant != null) { NotificationQueueLocalServiceUtil.addNotificationQueue( user.getUserId(), groupId, actionConfig.getNotificationType(), Dossier.class.getName(), String.valueOf(dossier.getDossierId()), payloadObj.toJSONString(), user.getFullName(), dossier.getApplicantName(), foundApplicant.getMappingUserId(), dossier.getContactEmail(), dossier.getContactTelNo(), now, expired, context); } } catch (NoSuchUserException e) { // e.printStackTrace(); _log.error(e); //_log.error(e); // e.printStackTrace(); } } } else if (actionConfig.getNotificationType().startsWith("USER")) { } } } // Notificationtemplate emplTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, "EMPL-01"); Serializable emplCache = cache.getFromCache("NotificationTemplate", groupId +"_"+ "EMPL-01"); Notificationtemplate emplTemplate = null; emplTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, "EMPL-01"); if (emplCache == null) { emplTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, "EMPL-01"); if (emplTemplate != null) { cache.addToCache("NotificationTemplate", groupId +"_"+ actionConfig.getNotificationType(), (Serializable) emplTemplate, ttl); } } else { emplTemplate = (Notificationtemplate) emplCache; } Date now = new Date(); Calendar calEmpl = Calendar.getInstance(); calEmpl.setTime(now); if (emplTemplate != null) { if ("minutely".equals(emplTemplate.getInterval())) { calEmpl.add(Calendar.MINUTE, emplTemplate.getExpireDuration()); } else if ("hourly".equals(emplTemplate.getInterval())) { calEmpl.add(Calendar.HOUR, emplTemplate.getExpireDuration()); } else { calEmpl.add(Calendar.MINUTE, emplTemplate.getExpireDuration()); } Date expired = calEmpl.getTime(); if (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA || dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) { try { String stepCode = dossierAction.getStepCode(); StringBuilder buildX = new StringBuilder(stepCode); if (stepCode.length() > 0) { buildX.setCharAt(stepCode.length() - 1, 'x'); } String stepCodeX = buildX.toString(); StepConfig stepConfig = StepConfigLocalServiceUtil.getByCode(groupId, dossierAction.getStepCode()); StepConfig stepConfigX = StepConfigLocalServiceUtil.getByCode(groupId, stepCodeX); if ((stepConfig != null && stepConfig.getStepType() == StepConfigTerm.STEP_TYPE_DISPLAY_MENU_BY_PROCESSED) || (stepConfigX != null && stepConfigX.getStepType() == StepConfigTerm.STEP_TYPE_DISPLAY_MENU_BY_PROCESSED)) { List<DossierActionUser> lstDaus = DossierActionUserLocalServiceUtil.getByDossierAndStepCode(dossier.getDossierId(), dossierAction.getStepCode()); for (DossierActionUser dau : lstDaus) { if (dau.getAssigned() == DossierActionUserTerm.ASSIGNED_TH || dau.getAssigned() == DossierActionUserTerm.ASSIGNED_PH) { // Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, dau.getUserId()); Serializable employeeCache = cache.getFromCache("Employee", groupId +"_"+ dau.getUserId()); Employee employee = null; // employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, dau.getUserId()); if (employeeCache == null) { employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, dau.getUserId()); if (employee != null) { cache.addToCache("Employee", groupId +"_"+ dau.getUserId(), (Serializable) employee, ttl); } } else { employee = (Employee) employeeCache; } if (employee != null) { String telNo = employee != null ? employee.getTelNo() : StringPool.BLANK; String fullName = employee != null ? employee.getFullName() : StringPool.BLANK; long start = System.currentTimeMillis(); NotificationQueueLocalServiceUtil.addNotificationQueue( user.getUserId(), groupId, "EMPL-01", Dossier.class.getName(), String.valueOf(dossier.getDossierId()), payloadObj.toJSONString(), user.getFullName(), fullName, dau.getUserId(), employee.getEmail(), telNo, now, expired, context); _log.debug("ADD NOTI QUEUE: " + (System.currentTimeMillis() - start)); } } } } } catch (NoSuchUserException e) { _log.error(e); //_log.error(e); // e.printStackTrace(); } } } } private void updateDossierPayload(Dossier dossier, JSONObject obj) { if (obj.has(DossierTerm.DOSSIER_NOTE)) { if (!obj.getString(DossierTerm.DOSSIER_NOTE).equals(dossier.getDossierNote())) { dossier.setDossierNote(obj.getString(DossierTerm.DOSSIER_NOTE)); } } if (obj.has(DossierTerm.EXTEND_DATE) && Validator.isNotNull(obj.get(DossierTerm.EXTEND_DATE)) && GetterUtil.getLong(obj.get(DossierTerm.EXTEND_DATE)) > 0) { if (dossier.getExtendDate() == null || obj.getLong(DossierTerm.EXTEND_DATE) != dossier.getExtendDate().getTime()) { dossier.setExtendDate(new Date(obj.getLong(DossierTerm.EXTEND_DATE))); } } if (obj.has(DossierTerm.DOSSIER_NO)) { //_log.info("Sync dossier no"); if (Validator.isNotNull(obj.getString(DossierTerm.DOSSIER_NO)) && !obj.getString(DossierTerm.DOSSIER_NO).equals(dossier.getDossierNo())) { //_log.info("Sync set dossier no"); dossier.setDossierNo(obj.getString(DossierTerm.DOSSIER_NO)); } } if (obj.has(DossierTerm.DUE_DATE) && Validator.isNotNull(obj.get(DossierTerm.DUE_DATE)) && GetterUtil.getLong(obj.get(DossierTerm.DUE_DATE)) > 0) { if (dossier.getDueDate() == null || obj.getLong(DossierTerm.DUE_DATE) != dossier.getDueDate().getTime()) { dossier.setDueDate(new Date(obj.getLong(DossierTerm.DUE_DATE))); } } if (obj.has(DossierTerm.FINISH_DATE) && Validator.isNotNull(obj.get(DossierTerm.FINISH_DATE)) && GetterUtil.getLong(obj.get(DossierTerm.FINISH_DATE)) > 0) { if (dossier.getFinishDate() == null || obj.getLong(DossierTerm.FINISH_DATE) != dossier.getFinishDate().getTime()) { dossier.setFinishDate(new Date(obj.getLong(DossierTerm.FINISH_DATE))); } } if (obj.has(DossierTerm.RECEIVE_DATE) && Validator.isNotNull(obj.get(DossierTerm.RECEIVE_DATE)) && GetterUtil.getLong(obj.get(DossierTerm.RECEIVE_DATE)) > 0) { if (dossier.getReceiveDate() == null || obj.getLong(DossierTerm.RECEIVE_DATE) != dossier.getReceiveDate().getTime()) { dossier.setReceiveDate(new Date(obj.getLong(DossierTerm.RECEIVE_DATE))); } } if (obj.has(DossierTerm.SUBMIT_DATE) && Validator.isNotNull(obj.get(DossierTerm.SUBMIT_DATE)) && GetterUtil.getLong(obj.get(DossierTerm.SUBMIT_DATE)) > 0) { if (dossier.getSubmitDate() == null || (dossier.getSubmitDate() != null && obj.getLong(DossierTerm.SUBMIT_DATE) != dossier.getSubmitDate().getTime())) { dossier.setSubmitDate(new Date(obj.getLong(DossierTerm.SUBMIT_DATE))); } } if (obj.has(DossierTerm.EXTEND_DATE) && Validator.isNotNull(obj.get(DossierTerm.EXTEND_DATE)) && GetterUtil.getLong(obj.get(DossierTerm.EXTEND_DATE)) > 0) { if (dossier.getExtendDate() == null || obj.getLong(DossierTerm.EXTEND_DATE) != dossier.getExtendDate().getTime()) { dossier.setExtendDate(new Date(obj.getLong(DossierTerm.EXTEND_DATE))); } } if (obj.has(DossierTerm.DOSSIER_NOTE)) { if (dossier.getDossierNote() == null || !obj.getString(DossierTerm.DOSSIER_NOTE).equals(dossier.getDossierNote())) { dossier.setDossierNote(obj.getString(DossierTerm.DOSSIER_NOTE)); } } if (obj.has(DossierTerm.SUBMISSION_NOTE)) { if (!obj.getString(DossierTerm.SUBMISSION_NOTE).equals(dossier.getDossierNote())) { dossier.setSubmissionNote(obj.getString(DossierTerm.SUBMISSION_NOTE)); } } if (obj.has(DossierTerm.RELEASE_DATE) && Validator.isNotNull(obj.get(DossierTerm.RELEASE_DATE)) && GetterUtil.getLong(obj.get(DossierTerm.RELEASE_DATE)) > 0) { if (dossier.getReleaseDate() == null || obj.getLong(DossierTerm.RELEASE_DATE) != dossier.getReleaseDate().getTime()) { dossier.setReleaseDate(new Date(obj.getLong(DossierTerm.RELEASE_DATE))); } } if (obj.has(DossierTerm.LOCK_STATE)) { if (!obj.getString(DossierTerm.LOCK_STATE).equals(dossier.getLockState())) { dossier.setLockState(obj.getString(DossierTerm.LOCK_STATE)); } } if (obj.has(DossierTerm.BRIEF_NOTE)) { if (!obj.getString(DossierTerm.BRIEF_NOTE).equals(dossier.getBriefNote())) { dossier.setBriefNote(obj.getString(DossierTerm.BRIEF_NOTE)); } } } private void processPaymentFile(long groupId, long userId, String payment, ProcessOption option, ProcessAction proAction, DossierAction previousAction, Dossier dossier, ServiceContext context) throws PortalException { // long serviceProcessId = (option != null ? option.getServiceProcessId() : previousAction.getServiceProcessId()); // ServiceProcess serviceProcess = ServiceProcessLocalServiceUtil.fetchServiceProcess(serviceProcessId); String paymentFee = StringPool.BLANK; //Yêu cầu nộp tạm ứng if (proAction.getRequestPayment() == ProcessActionTerm.REQUEST_PAYMENT_YEU_CAU_NOP_TAM_UNG || proAction.getRequestPayment() == ProcessActionTerm.REQUEST_PAYMENT_YEU_CAU_QUYET_TOAN_PHI && Validator.isNotNull(payment)) { Long feeAmount = 0l, serviceAmount = 0l, shipAmount = 0l; String paymentNote = StringPool.BLANK; long advanceAmount = 0l; long paymentAmount = 0l; String epaymentProfile = StringPool.BLANK; String bankInfo = StringPool.BLANK; int paymentStatus = 0; String paymentMethod = StringPool.BLANK; NumberFormat fmt = NumberFormat.getNumberInstance(LocaleUtil.getDefault()); DecimalFormatSymbols customSymbol = new DecimalFormatSymbols(); customSymbol.setDecimalSeparator(','); customSymbol.setGroupingSeparator('.'); ((DecimalFormat)fmt).setDecimalFormatSymbols(customSymbol); fmt.setGroupingUsed(true); try { JSONObject paymentObj = JSONFactoryUtil.createJSONObject(payment); if (paymentObj.has("paymentNote")) { paymentNote = paymentObj.getString("paymentNote"); } if (paymentObj.has("feeAmount")) { feeAmount = (Long)fmt.parse(paymentObj.getString("feeAmount")); } if (paymentObj.has("serviceAmount")) { serviceAmount = (Long)fmt.parse(paymentObj.getString("serviceAmount")); } if (paymentObj.has("shipAmount")) { shipAmount = (Long)fmt.parse(paymentObj.getString("shipAmount")); } if (paymentObj.has("requestPayment")) { paymentStatus = paymentObj.getInt("requestPayment"); } if (paymentObj.has("advanceAmount")) { advanceAmount = (Long)fmt.parse(paymentObj.getString("advanceAmount")); } JSONObject paymentObj2 = JSONFactoryUtil.createJSONObject(proAction.getPaymentFee()); if (paymentObj2.has("paymentFee")) { paymentFee = paymentObj2.getString("paymentFee"); } } catch (JSONException e) { _log.debug(e); } catch (ParseException e) { _log.debug(e); } PaymentFile oldPaymentFile = paymentFileLocalService.getByDossierId(groupId, dossier.getDossierId()); if (oldPaymentFile != null) { if (Validator.isNotNull(paymentNote)) oldPaymentFile.setPaymentNote(paymentNote); try { PaymentFile paymentFile = paymentFileLocalService.updateApplicantFeeAmount( oldPaymentFile.getPaymentFileId(), proAction.getRequestPayment(), feeAmount, serviceAmount, shipAmount, paymentNote, dossier.getOriginality()); String generatorPayURL = PaymentUrlGenerator.generatorPayURL(groupId, paymentFile.getPaymentFileId(), paymentFee, dossier.getDossierId()); JSONObject epaymentProfileJsonNew = JSONFactoryUtil.createJSONObject(paymentFile.getEpaymentProfile()); epaymentProfileJsonNew.put("keypayUrl", generatorPayURL); paymentFileLocalService.updateEProfile(dossier.getDossierId(), paymentFile.getReferenceUid(), epaymentProfileJsonNew.toJSONString(), context); } catch (IOException e) { _log.error(e); } catch (JSONException e) { _log.debug(e); } } else { paymentAmount = feeAmount + serviceAmount + shipAmount - advanceAmount; PaymentFile paymentFile = paymentFileLocalService.createPaymentFiles(userId, groupId, dossier.getDossierId(), dossier.getReferenceUid(), paymentFee, advanceAmount, feeAmount, serviceAmount, shipAmount, paymentAmount, paymentNote, epaymentProfile, bankInfo, paymentStatus, paymentMethod, context); long counterPaymentFile = CounterLocalServiceUtil.increment(PaymentFile.class.getName() + "paymentFileNo"); Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); int prefix = cal.get(Calendar.YEAR); String invoiceNo = Integer.toString(prefix) + String.format("%010d", counterPaymentFile); paymentFile.setInvoiceNo(invoiceNo); PaymentConfig paymentConfig = paymentConfigLocalService.getPaymentConfigByGovAgencyCode(groupId, dossier.getGovAgencyCode()); if (Validator.isNotNull(paymentConfig)) { paymentFile.setInvoiceTemplateNo(paymentConfig.getInvoiceTemplateNo()); paymentFile.setGovAgencyTaxNo(paymentConfig.getGovAgencyTaxNo()); paymentFile.setGovAgencyCode(paymentConfig.getGovAgencyCode()); paymentFile.setGovAgencyName(paymentConfig.getGovAgencyName()); } paymentFileLocalService.updatePaymentFile(paymentFile); JSONObject epaymentConfigJSON = paymentConfig != null ? JSONFactoryUtil.createJSONObject(paymentConfig.getEpaymentConfig()) : JSONFactoryUtil.createJSONObject(); JSONObject epaymentProfileJSON = JSONFactoryUtil.createJSONObject(); if (epaymentConfigJSON.has("paymentKeypayDomain")) { try { String generatorPayURL = PaymentUrlGenerator.generatorPayURL(groupId, paymentFile.getPaymentFileId(), paymentFee, dossier.getDossierId()); epaymentProfileJSON.put("keypayUrl", generatorPayURL); String pattern1 = "good_code="; String pattern2 = "&"; String regexString = Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2); Pattern p = Pattern.compile(regexString); Matcher m = p.matcher(generatorPayURL); if (m.find()) { String goodCode = m.group(1); epaymentProfileJSON.put("keypayGoodCode", goodCode); } else { epaymentProfileJSON.put("keypayGoodCode", StringPool.BLANK); } epaymentProfileJSON.put("keypayMerchantCode", epaymentConfigJSON.get("paymentMerchantCode")); epaymentProfileJSON.put("bank", "true"); epaymentProfileJSON.put("paygate", "true"); epaymentProfileJSON.put("serviceAmount", serviceAmount); epaymentProfileJSON.put("paymentNote", paymentNote); epaymentProfileJSON.put("paymentFee", paymentFee); paymentFileLocalService.updateEProfile(dossier.getDossierId(), paymentFile.getReferenceUid(), epaymentProfileJSON.toJSONString(), context); } catch (IOException e) { _log.error(e); } } else { paymentFileLocalService.updateEProfile(dossier.getDossierId(), paymentFile.getReferenceUid(), epaymentProfileJSON.toJSONString(), context); } } } else if (proAction.getRequestPayment() == ProcessActionTerm.REQUEST_PAYMENT_XAC_NHAN_HOAN_THANH_THU_PHI) { String CINVOICEUrl = "postal/invoice"; JSONObject resultObj = null; Map<String, Object> params = new HashMap<>(); PaymentFile oldPaymentFile = paymentFileLocalService.getByDossierId(groupId, dossier.getDossierId()); int intpaymentMethod = 0; if (Validator.isNotNull(proAction.getPreCondition())) { intpaymentMethod = checkPaymentMethodinPrecondition(proAction.getPreCondition()); } if (oldPaymentFile != null && proAction.getPreCondition().toLowerCase().contains("sendinvoice=1")){ params = createParamsInvoice(oldPaymentFile, dossier, intpaymentMethod); InvokeREST callRest = new InvokeREST(); String baseUrl = RESTFulConfiguration.SERVER_PATH_BASE; HashMap<String, String> properties = new HashMap<String, String>(); resultObj = callRest.callPostAPI(groupId, HttpMethod.POST, "application/json", baseUrl, CINVOICEUrl, "", "", properties, params, context); } if (Validator.isNotNull(oldPaymentFile) ) { String paymentMethod = ""; if (intpaymentMethod != 0) { paymentMethod = checkPaymentMethod(intpaymentMethod); } if(Validator.isNotNull(resultObj)) { oldPaymentFile.setEinvoice(resultObj.toString()); oldPaymentFile.setInvoicePayload(params.toString()); if (Validator.isNotNull(paymentMethod)) { oldPaymentFile.setPaymentMethod(paymentMethod); } } if (Validator.isNotNull(payment)) { try { JSONObject paymentObj = JSONFactoryUtil.createJSONObject(payment); if (paymentObj.has("paymentNote")) { oldPaymentFile.setPaymentNote(paymentObj.getString("paymentNote")); String epaymentProfile = oldPaymentFile.getEpaymentProfile(); if (Validator.isNotNull(epaymentProfile)) { JSONObject jsonEpayment = JSONFactoryUtil.createJSONObject(epaymentProfile); jsonEpayment.put("paymentNote", paymentObj.getString("paymentNote")); oldPaymentFile.setEpaymentProfile(jsonEpayment.toJSONString()); } } } catch (JSONException e) { _log.debug(e); } } oldPaymentFile.setPaymentStatus(proAction.getRequestPayment()); paymentFileLocalService.updatePaymentFile(oldPaymentFile); } } else if (proAction.getRequestPayment() == ProcessActionTerm.REQUEST_PAYMENT_BAO_DA_NOP_PHI) { PaymentFile oldPaymentFile = paymentFileLocalService.getByDossierId(groupId, dossier.getDossierId()); int intpaymentMethod = checkPaymentMethodinPrecondition(proAction.getPreCondition()); String paymentMethod = checkPaymentMethod(intpaymentMethod); if (oldPaymentFile != null) { oldPaymentFile.setPaymentStatus(proAction.getRequestPayment()); oldPaymentFile.setPaymentMethod(paymentMethod); paymentFileLocalService.updatePaymentFile(oldPaymentFile); } } } private void createNotificationSMS(long userId, long groupId, Dossier dossier, JSONArray assignedUsers, DossierAction dossierAction, ServiceContext context) { // DossierAction dossierAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId()); User u = UserLocalServiceUtil.fetchUser(userId); JSONObject payloadObj = JSONFactoryUtil.createJSONObject(); try { payloadObj.put( "Dossier", JSONFactoryUtil.createJSONObject( JSONFactoryUtil.looseSerialize(dossier))); if (dossierAction != null) { payloadObj.put("actionCode", dossierAction.getActionCode()); payloadObj.put("actionUser", dossierAction.getActionUser()); payloadObj.put("actionName", dossierAction.getActionName()); payloadObj.put("actionNote", dossierAction.getActionNote()); } } catch (Exception e) { _log.error(e); } Notificationtemplate emplTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, "EMPL-03"); Date now = new Date(); Calendar calEmpl = Calendar.getInstance(); calEmpl.setTime(now); if (emplTemplate != null) { if ("minutely".equals(emplTemplate.getInterval())) { calEmpl.add(Calendar.MINUTE, emplTemplate.getExpireDuration()); } else if ("hourly".equals(emplTemplate.getInterval())) { calEmpl.add(Calendar.HOUR, emplTemplate.getExpireDuration()); } else { calEmpl.add(Calendar.MINUTE, emplTemplate.getExpireDuration()); } Date expired = calEmpl.getTime(); if (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA || dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) { try { String stepCode = dossierAction.getStepCode(); StringBuilder buildX = new StringBuilder(stepCode); if (stepCode.length() > 0) { buildX.setCharAt(stepCode.length() - 1, 'x'); } String stepCodeX = buildX.toString(); StepConfig stepConfig = StepConfigLocalServiceUtil.getByCode(groupId, dossierAction.getStepCode()); StepConfig stepConfigX = StepConfigLocalServiceUtil.getByCode(groupId, stepCodeX); if ((stepConfig != null && stepConfig.getStepType() == StepConfigTerm.STEP_TYPE_DISPLAY_MENU_BY_PROCESSED) || (stepConfigX != null && stepConfigX.getStepType() == StepConfigTerm.STEP_TYPE_DISPLAY_MENU_BY_PROCESSED)) { for (int n = 0; n < assignedUsers.length(); n++) { JSONObject subUser = assignedUsers.getJSONObject(n); if (subUser != null && subUser.has(DossierActionUserTerm.ASSIGNED) && subUser.getInt(DossierActionUserTerm.ASSIGNED) == DossierActionUserTerm.ASSIGNED_TH) { long userIdAssigned = subUser.getLong("userId"); Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userIdAssigned); if (employee != null) { String telNo = employee != null ? employee.getTelNo() : StringPool.BLANK; String fullName = employee != null ? employee.getFullName() : StringPool.BLANK; NotificationQueueLocalServiceUtil.addNotificationQueue( userId, groupId, "EMPL-03", Dossier.class.getName(), String.valueOf(dossier.getDossierId()), payloadObj.toJSONString(), u.getFullName(), fullName, userIdAssigned, employee.getEmail(), telNo, now, expired, context); } } } } } catch (NoSuchUserException e) { _log.error(e); //_log.error(e); // e.printStackTrace(); } } } } private void createSubcription(long userId, long groupId, Dossier dossier, ActionConfig actionConfig, DossierAction dossierAction, ServiceContext context) { if (actionConfig != null && Validator.isNotNull(actionConfig.getNotificationType())) { // DossierAction dossierAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId()); // User u = UserLocalServiceUtil.fetchUser(userId); Notificationtemplate notiTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, actionConfig.getNotificationType()); if (notiTemplate != null) { if (actionConfig.getDocumentType().startsWith("APLC")) { if (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA || dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) { } } else if (actionConfig.getDocumentType().startsWith("EMPL")) { if ((dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA || dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) && dossierAction != null) { StepConfig stepConfig = stepConfigLocalService.getByCode(groupId, dossierAction.getStepCode()); List<DossierActionUser> lstDaus = dossierActionUserLocalService.getByDID_DAI_SC_AS(dossier.getDossierId(), dossierAction.getDossierActionId(), dossierAction.getStepCode(), new int[] { 1, 2 }); if ("EMPL-01".equals(actionConfig.getDocumentType()) && stepConfig != null && "1".equals(stepConfig.getStepType())) { for (DossierActionUser dau : lstDaus) { try { SubscriptionLocalServiceUtil.addSubscription(dau.getUserId(), groupId, "EMPL-01", 0); } catch (PortalException e) { _log.debug(e); } } } } } else if (actionConfig.getDocumentType().startsWith("USER")) { } } } } private List<String> _putPaymentMessage(String pattern) { List<String> lsDesc = new ArrayList<String>(); lsDesc.add(0, StringPool.BLANK); lsDesc.add(1, StringPool.BLANK); lsDesc.add(2, StringPool.BLANK); lsDesc.add(3, StringPool.BLANK); lsDesc.add(4, StringPool.BLANK); List<String> lsMsg = DossierPaymentUtils.getMessagePayment(pattern); for (int i = 0; i < lsMsg.size(); i++) { lsDesc.set(1, lsMsg.get(i)); } return lsDesc; } private long _genetatorTransactionId() { long transactionId = 0; try { transactionId = counterLocalService.increment(PaymentFile.class.getName() + ".genetatorTransactionId"); } catch (SystemException e) { _log.error(e); } return transactionId; } private String generatorPayURL(long groupId, long paymentFileId, String pattern, Dossier dossier) throws IOException { String result = ""; try { PaymentFile paymentFile = paymentFileLocalService.getPaymentFile(paymentFileId); PaymentConfig paymentConfig = paymentConfigLocalService.getPaymentConfigByGovAgencyCode(groupId, dossier.getGovAgencyCode()); if (Validator.isNotNull(paymentConfig)) { List<String> lsMessages = _putPaymentMessage(pattern); long merchant_trans_id = _genetatorTransactionId(); JSONObject epaymentConfigJSON = JSONFactoryUtil.createJSONObject(paymentConfig.getEpaymentConfig()); String merchant_code = epaymentConfigJSON.getString("paymentMerchantCode"); String good_code = generatorGoodCode(10); String net_cost = String.valueOf(paymentFile.getPaymentAmount()); String ship_fee = "0"; String tax = "0"; String bank_code = StringPool.BLANK; String service_code = epaymentConfigJSON.getString("paymentServiceCode"); String version = epaymentConfigJSON.getString("paymentVersion"); String command = epaymentConfigJSON.getString("paymentCommand"); String currency_code = epaymentConfigJSON.getString("paymentCurrencyCode"); String desc_1 = StringPool.BLANK; String desc_2 = StringPool.BLANK; String desc_3 = StringPool.BLANK; String desc_4 = StringPool.BLANK; String desc_5 = StringPool.BLANK; if (lsMessages.size() > 0) { desc_1 = lsMessages.get(0); desc_2 = lsMessages.get(1); desc_3 = lsMessages.get(2); desc_4 = lsMessages.get(3); desc_5 = lsMessages.get(4); if (desc_1.length() >= 20) { desc_1 = desc_1.substring(0, 19); } if (desc_2.length() >= 30) { desc_2 = desc_2.substring(0, 29); } if (desc_3.length() >= 40) { desc_3 = desc_3.substring(0, 39); } if (desc_4.length() >= 100) { desc_4 = desc_4.substring(0, 89); } if (desc_5.length() > 15) { desc_5 = desc_5.substring(0, 15); if (!Validator.isDigit(desc_5)) { desc_5 = StringPool.BLANK; } } } String xml_description = StringPool.BLANK; String current_locale = epaymentConfigJSON.getString("paymentCurrentLocale"); String country_code = epaymentConfigJSON.getString("paymentCountryCode"); String internal_bank = epaymentConfigJSON.getString("paymentInternalBank"); String merchant_secure_key = epaymentConfigJSON.getString("paymentMerchantSecureKey"); // dossier = _getDossier(dossierId); // TODO : update returnURL keyPay String return_url; _log.info("SONDT GENURL paymentReturnUrl ====================== "+ JSONFactoryUtil.looseSerialize(epaymentConfigJSON)); // return_url = epaymentConfigJSON.getString("paymentReturnUrl")+ "/" + dossier.getReferenceUid() + "/" + paymentFile.getReferenceUid(); return_url = epaymentConfigJSON.getString("paymentReturnUrl")+ "&dossierId=" + dossier.getDossierId() + "&goodCode=" + good_code + "&transId=" + merchant_trans_id + "&referenceUid=" + dossier.getReferenceUid(); _log.info("SONDT GENURL paymentReturnUrl ====================== "+ return_url); // http://119.17.200.66:2681/web/bo-van-hoa/dich-vu-cong/#/thanh-toan-thanh-cong?paymentPortal=KEYPAY&dossierId=77603&goodCode=123&transId=555 KeyPay keypay = new KeyPay(String.valueOf(merchant_trans_id), merchant_code, good_code, net_cost, ship_fee, tax, bank_code, service_code, version, command, currency_code, desc_1, desc_2, desc_3, desc_4, desc_5, xml_description, current_locale, country_code, return_url, internal_bank, merchant_secure_key); // keypay.setKeypay_url(paymentConfig.getKeypayDomain()); StringBuffer param = new StringBuffer(); param.append("merchant_code=").append(URLEncoder.encode(keypay.getMerchant_code(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("merchant_secure_key=").append(URLEncoder.encode(keypay.getMerchant_secure_key(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("bank_code=").append(URLEncoder.encode(keypay.getBank_code(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("internal_bank=").append(URLEncoder.encode(keypay.getInternal_bank(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("merchant_trans_id=").append(URLEncoder.encode(keypay.getMerchant_trans_id(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("good_code=").append(URLEncoder.encode(keypay.getGood_code(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("net_cost=").append(URLEncoder.encode(keypay.getNet_cost(), "UTF-8") ) .append(StringPool.AMPERSAND); param.append("ship_fee=").append(URLEncoder.encode(keypay.getShip_fee(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("tax=").append(URLEncoder.encode(keypay.getTax(), "UTF-8")).append(StringPool.AMPERSAND); param.append("return_url=").append(URLEncoder.encode(keypay.getReturn_url(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("version=").append(URLEncoder.encode(keypay.getVersion(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("command=").append(URLEncoder.encode(keypay.getCommand(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("current_locale=").append(URLEncoder.encode(keypay.getCurrent_locale(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("currency_code=").append(URLEncoder.encode(keypay.getCurrency_code(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("service_code=").append(URLEncoder.encode(keypay.getService_code(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("country_code=").append(URLEncoder.encode(keypay.getCountry_code(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("desc_1=").append(URLEncoder.encode(keypay.getDesc_1(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("desc_2=").append(URLEncoder.encode(keypay.getDesc_2(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("desc_3=").append(URLEncoder.encode(keypay.getDesc_3(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("desc_4=").append(URLEncoder.encode(keypay.getDesc_4(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("desc_5=").append(URLEncoder.encode(keypay.getDesc_5(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("xml_description=").append(URLEncoder.encode(keypay.getXml_description(), "UTF-8")) .append(StringPool.AMPERSAND); param.append("secure_hash=").append(keypay.getSecure_hash()); result = epaymentConfigJSON.getString("paymentKeypayDomain") + StringPool.QUESTION + param.toString(); } } catch (NoSuchPaymentFileException e) { _log.debug(e); } catch (Exception e) { _log.debug(e); } return result; } private Map<String, Object> createParamsInvoice(PaymentFile oldPaymentFile, Dossier dossier, int intpaymentMethod) { Map<String, Object> params = new HashMap<>(); StringBuilder address = new StringBuilder(); address.append(dossier.getAddress());address.append(", "); address.append(dossier.getWardName());address.append(", "); address.append(dossier.getDistrictName());address.append(", "); address.append(dossier.getCityName()); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY"); String dateformatted = sdf.format(new Date()); _log.info("SONDT CINVOICE DATEFORMATED ============= " + dateformatted); params.put("userName", "HA"); params.put("passWord", "1"); params.put("soid", "0"); params.put("maHoadon", "01GTKT0/001"); params.put("ngayHd", dateformatted); //"01/08/2018" params.put("seri", "12314"); params.put("maNthue", "01"); params.put("kieuSo", "G"); params.put("maKhackHang", Long.toString(dossier.getUserId())); params.put("ten", dossier.getApplicantName()); params.put("phone", dossier.getContactTelNo()); if(dossier.getApplicantIdType().contentEquals("business")) { params.put("tax", dossier.getApplicantIdNo()); } else { params.put("tax", ""); } params.put("dchi", address); params.put("maTk", ""); params.put("tenNh", ""); params.put("mailH", GetterUtil.getString(dossier.getContactEmail())); params.put("phoneH", GetterUtil.getString(dossier.getContactTelNo())); params.put("tenM", GetterUtil.getString(dossier.getDelegateName())); params.put("maKhL", "K"); params.put("maNt", "VND"); params.put("tg", "1"); if(intpaymentMethod == 3) { params.put("hthuc", "M"); }else { params.put("hthuc", "C"); } params.put("han", ""); params.put("tlGgia", "0"); params.put("ggia", "0"); params.put("phi", "0"); params.put("noidung", dossier.getDossierNo()); params.put("tien", Long.toString(oldPaymentFile.getPaymentAmount())); params.put("ttoan", Long.toString(oldPaymentFile.getPaymentAmount())); params.put("maVtDetail", dossier.getDossierNo()); params.put("tenDetail", GetterUtil.getString(dossier.getServiceName())); params.put("dvtDetail", "bo"); params.put("luongDetail", "1"); params.put("giaDetail", Long.toString(oldPaymentFile.getPaymentAmount())); params.put("tienDetail", Long.toString(oldPaymentFile.getPaymentAmount())); params.put("tsDetail", "0"); params.put("thueDetail", "0"); params.put("ttoanDetail", Long.toString(oldPaymentFile.getPaymentAmount())); return params; } private int checkPaymentMethodinPrecondition(String preCondition) { int paymentMethod = 0; String[] preConditions = StringUtil.split(preCondition); for(String pre : preConditions) { pre = pre.trim(); if (pre.toLowerCase().contains("paymentmethod=")) { String[] splitPaymentMethod = pre.split("="); if (splitPaymentMethod.length == 2) { paymentMethod = Integer.parseInt(splitPaymentMethod[1]); } break; } } return paymentMethod; } private String checkPaymentMethod(int mt) { String pmMethod = ""; if (mt == 1) { pmMethod = "Chuyển khoản"; //KeyPay } else if (mt == 2) { pmMethod = "Chuyển khoản"; } else if (mt == 3) { pmMethod = "Tiền mặt"; } return pmMethod; } private JSONObject getStatusText(long groupId, String collectionCode, String curStatus, String curSubStatus) { JSONObject jsonData = null; DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(collectionCode, groupId); if (Validator.isNotNull(dc) && Validator.isNotNull(curStatus)) { jsonData = JSONFactoryUtil.createJSONObject(); DictItem it = DictItemLocalServiceUtil.fetchByF_dictItemCode(curStatus, dc.getPrimaryKey(), groupId); if (Validator.isNotNull(it)) { jsonData.put(curStatus, it.getItemName()); if (Validator.isNotNull(curSubStatus)) { DictItem dItem = DictItemLocalServiceUtil.fetchByF_dictItemCode(curSubStatus, dc.getPrimaryKey(), groupId); if (Validator.isNotNull(dItem)) { jsonData.put(curSubStatus, dItem.getItemName()); } } } } return jsonData; } private int getActionDueDate(long groupId, long dossierId, String refId, long processActionId) { return 0; } protected String getDictItemName(long groupId, String collectionCode, String itemCode) { DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(collectionCode, groupId); if (Validator.isNotNull(dc)) { DictItem it = DictItemLocalServiceUtil.fetchByF_dictItemCode(itemCode, dc.getPrimaryKey(), groupId); if(Validator.isNotNull(it)){ return it.getItemName(); }else{ return StringPool.BLANK; } } else { return StringPool.BLANK; } } private void updateStatus(Dossier dossier, String status, String statusText, String subStatus, String subStatusText, String lockState, String stepInstruction, ServiceContext context) throws PortalException { Date now = new Date(); dossier.setModifiedDate(now); dossier.setDossierStatus(status); dossier.setDossierStatusText(statusText); dossier.setDossierSubStatus(subStatus); dossier.setDossierSubStatusText(subStatusText); dossier.setLockState(lockState); dossier.setDossierNote(stepInstruction); if (status.equalsIgnoreCase(DossierStatusConstants.RELEASING)) { dossier.setReleaseDate(now); } if (status.equalsIgnoreCase(DossierStatusConstants.DONE)) { dossier.setFinishDate(now); } } private Map<String, Boolean> updateProcessingDate(DossierAction dossierAction, DossierAction prevAction, ProcessStep processStep, Dossier dossier, String curStatus, String curSubStatus, String prevStatus, ActionConfig actionConfig, ProcessOption option, ServiceProcess serviceProcess, ServiceContext context) { Date now = new Date(); Map<String, Boolean> bResult = new HashMap<>(); LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>(); params.put(DossierTerm.GOV_AGENCY_CODE, dossier.getGovAgencyCode()); params.put(DossierTerm.SERVICE_CODE, dossier.getServiceCode()); params.put(DossierTerm.DOSSIER_TEMPLATE_NO, dossier.getDossierTemplateNo()); params.put(DossierTerm.DOSSIER_STATUS, StringPool.BLANK); // ServiceProcess serviceProcess = null; // // long serviceProcessId = (option != null ? option.getServiceProcessId() : prevAction.getServiceProcessId()); // serviceProcess = ServiceProcessLocalServiceUtil.fetchServiceProcess(serviceProcessId); // if ((Validator.isNull(prevStatus) && DossierTerm.DOSSIER_STATUS_NEW.equals(curStatus) // && (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA)) if ((DossierTerm.DOSSIER_STATUS_RECEIVING.equals(curStatus) || DossierTerm.DOSSIER_STATUS_NEW.equals(curStatus)) && dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) { try { if (Validator.isNotNull(option) && Validator.isNull(dossier.getDossierNo())) { String dossierRef = DossierNumberGenerator.generateDossierNumber(dossier.getGroupId(), dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(), serviceProcess.getDossierNoPattern(), params); dossier.setDossierNo(dossierRef.trim()); // DossierLocalServiceUtil.updateDossier(dossier); bResult.put(DossierTerm.DOSSIER_NO, true); } } catch (PortalException e) { _log.debug(e); //_log.error(e); // e.printStackTrace(); } } if ((DossierTerm.DOSSIER_STATUS_NEW.equals(prevStatus) && DossierTerm.DOSSIER_STATUS_RECEIVING.equals(curStatus)) || (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA && DossierTerm.DOSSIER_STATUS_NEW.equals(curStatus))) { // try { // DossierLocalServiceUtil.updateSubmittingDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context); if (Validator.isNull(dossier.getSubmitDate())) { dossier.setSubmitDate(now); bResult.put(DossierTerm.SUBMIT_DATE, true); } // } catch (PortalException e) { // _log.error(e); // e.printStackTrace(); // } } if (dossier.getOriginality() != DossierTerm.ORIGINALITY_DVCTT && ((DossierTerm.DOSSIER_STATUS_PROCESSING.equals(curStatus) && dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) || (DossierTerm.DOSSIER_STATUS_NEW.equals(curStatus) && dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA) || (DossierTerm.DOSSIER_STATUS_NEW.equals(curStatus) && dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) || (actionConfig != null && actionConfig.getDateOption() == 2)) && dossier.getReceiveDate() == null) { // try { // DossierLocalServiceUtil.updateReceivingDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context); dossier.setReceiveDate(now); bResult.put(DossierTerm.RECEIVE_DATE, true); Double durationCount = serviceProcess.getDurationCount(); int durationUnit = serviceProcess.getDurationUnit(); Date dueDate = null; if (Validator.isNotNull(durationCount) && durationCount > 0 && !areEqualDouble(durationCount, 0.00d, 3)) { dueDate = HolidayUtils.getDueDate(now, durationCount, durationUnit, dossier.getGroupId()); } if (Validator.isNotNull(dueDate)) { dossier.setDueDate(dueDate); // DossierLocalServiceUtil.updateDueDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), dueDate, context); bResult.put(DossierTerm.DUE_DATE, true); } dossier.setDurationCount(durationCount); dossier.setDurationUnit(durationUnit); if (dossier.getCounter() == 0 && Validator.isNotNull(dossier.getRegisterBookCode())) { long counterCode = DossierNumberGenerator.countByRegiterBookCode(dossier.getGroupId(), dossier.getRegisterBookCode()); dossier.setCounter(counterCode); } if (Validator.isNull(dossier.getDossierNo())) { try { String dossierRef = DossierNumberGenerator.generateDossierNumber(dossier.getGroupId(), dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(), serviceProcess.getDossierNoPattern(), params); dossier.setDossierNo(dossierRef.trim()); } catch (Exception e) { //_log.debug(e); } } // dossier = DossierLocalServiceUtil.updateDossier(dossier); // } catch (PortalException e) { // _log.error(e); // e.printStackTrace(); // } } //Update counter and dossierNo if (actionConfig != null && actionConfig.getDateOption() == 2) { if (dossier.getCounter() == 0 && Validator.isNotNull(dossier.getRegisterBookCode())) { long counterCode = DossierNumberGenerator.countByRegiterBookCode(dossier.getGroupId(), dossier.getRegisterBookCode()); dossier.setCounter(counterCode); } if (Validator.isNull(dossier.getDossierNo())) { try { String dossierRef = DossierNumberGenerator.generateDossierNumber(dossier.getGroupId(), dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(), serviceProcess.getDossierNoPattern(), params); dossier.setDossierNo(dossierRef.trim()); } catch (Exception e) { // _log.debug(e); } } } if (DossierTerm.DOSSIER_STATUS_RECEIVING.equals(prevStatus) && DossierTerm.DOSSIER_STATUS_PROCESSING.equals(curStatus)) { // try { // DossierLocalServiceUtil.updateProcessDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context); dossier.setProcessDate(now); bResult.put(DossierTerm.PROCESS_DATE, true); // } catch (PortalException e) { // _log.error(e); // e.printStackTrace(); // } } // if (DossierTerm.DOSSIER_STATUS_RELEASING.equals(curStatus) // || DossierTerm.DOSSIER_STATUS_DENIED.equals(curStatus) // || DossierTerm.DOSSIER_STATUS_UNRESOLVED.equals(curStatus) // || DossierTerm.DOSSIER_STATUS_CANCELLED.equals(curStatus) // || DossierTerm.DOSSIER_STATUS_DONE.equals(curStatus)) { if (DossierTerm.DOSSIER_STATUS_RELEASING.equals(curStatus) || DossierTerm.DOSSIER_STATUS_UNRESOLVED.equals(curStatus) || DossierTerm.DOSSIER_STATUS_CANCELLED.equals(curStatus) || (actionConfig != null && actionConfig.getDateOption() == 4) ) { if (Validator.isNull(dossier.getReleaseDate())) { // try { // DossierLocalServiceUtil.updateReleaseDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context); dossier.setReleaseDate(now); bResult.put(DossierTerm.RELEASE_DATE, true); // } catch (PortalException e) { // _log.error(e); // e.printStackTrace(); // } } } // _log.info("========STEP DUE CUR STATUS: " + curStatus); if (DossierTerm.DOSSIER_STATUS_DENIED.equals(curStatus) || DossierTerm.DOSSIER_STATUS_UNRESOLVED.equals(curStatus) || DossierTerm.DOSSIER_STATUS_CANCELLED.equals(curStatus) || DossierTerm.DOSSIER_STATUS_DONE.equals(curStatus)) { // _log.info("========STEP DUE CUR STATUS UPDATING STATE DONE"); // dossierAction.setState(DossierActionTerm.STATE_ALREADY_PROCESSED); // dossierAction.setModifiedDate(new Date()); dossierAction = dossierActionLocalService.updateState(dossierAction.getDossierActionId(), DossierActionTerm.STATE_ALREADY_PROCESSED); } // if (DossierTerm.DOSSIER_STATUS_DENIED.equals(curStatus) // || DossierTerm.DOSSIER_STATUS_UNRESOLVED.equals(curStatus) // || DossierTerm.DOSSIER_STATUS_CANCELLED.equals(curStatus) // || DossierTerm.DOSSIER_STATUS_DONE.equals(curStatus)) { if (DossierTerm.DOSSIER_STATUS_DENIED.equals(curStatus) || DossierTerm.DOSSIER_STATUS_DONE.equals(curStatus) || DossierTerm.DOSSIER_STATUS_UNRESOLVED.equals(curStatus) || DossierTerm.DOSSIER_STATUS_CANCELLED.equals(curStatus) || (actionConfig != null && actionConfig.getDateOption() == 5)) { if (Validator.isNull(dossier.getFinishDate())) { // try { // DossierLocalServiceUtil.updateFinishDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context); dossier.setFinishDate(now); bResult.put(DossierTerm.FINISH_DATE, true); // dossierAction.setState(DossierActionTerm.STATE_ALREADY_PROCESSED); // dossierAction.setModifiedDate(new Date()); dossierAction = dossierActionLocalService.updateState(dossierAction.getDossierActionId(), DossierActionTerm.STATE_ALREADY_PROCESSED); // } catch (PortalException e) { // _log.error(e); // e.printStackTrace(); // } } if (Validator.isNull(dossier.getReleaseDate())) { // try { // DossierLocalServiceUtil.updateReleaseDate(dossier.getGroupId(), dossier.getDossierId(), dossier.getReferenceUid(), now, context); dossier.setReleaseDate(now); bResult.put(DossierTerm.RELEASE_DATE, true); // } catch (PortalException e) { // _log.error(e); // e.printStackTrace(); // } } } if (DossierTerm.DOSSIER_STATUS_PROCESSING.equals(curStatus) || DossierTerm.DOSSIER_STATUS_INTEROPERATING.equals(curStatus) || DossierTerm.DOSSIER_STATUS_WAITING.equals(curStatus)) { if (Validator.isNotNull(dossier.getFinishDate())) { dossier.setFinishDate(null); bResult.put(DossierTerm.FINISH_DATE, true); } if (Validator.isNotNull(dossier.getReleaseDate())) { dossier.setReleaseDate(null); bResult.put(DossierTerm.RELEASE_DATE, true); } } if (DossierTerm.DOSSIER_STATUS_RECEIVING.equals(prevStatus)) { bResult.put(DossierTerm.DOSSIER_NO, true); bResult.put(DossierTerm.RECEIVE_DATE, true); bResult.put(DossierTerm.PROCESS_DATE, true); bResult.put(DossierTerm.RELEASE_DATE, true); bResult.put(DossierTerm.FINISH_DATE, true); } if (DossierTerm.DOSSIER_STATUS_NEW.equals(prevStatus) && dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG && Validator.isNotNull(dossier.getReceiveDate())) { bResult.put(DossierTerm.RECEIVE_DATE, true); } int dateOption = actionConfig.getDateOption(); _log.debug("dateOption: "+dateOption); if (dateOption == DossierTerm.DATE_OPTION_CAL_WAITING) { DossierAction dActEnd = dossierActionLocalService .fetchDossierAction(dossierAction.getDossierActionId()); // DossierAction dActEnd = dossierAction; if (dActEnd != null) { _log.debug("dActEnd.getPreviousActionId(): "+dActEnd.getPreviousActionId()); DossierAction dActStart = dossierActionLocalService .fetchDossierAction(dActEnd.getPreviousActionId()); // DossierAction dActStart = prevAction; if (dActStart != null) { long createEnd = dActEnd.getCreateDate().getTime(); long createStart = dActStart.getCreateDate().getTime(); _log.debug("createStart: "+createStart); _log.debug("createEnd: "+createEnd); if (createEnd > createStart) { long extendDateTimeStamp = ExtendDueDateUtils.getTimeWaitingByHoliday(createStart, createEnd, dossier.getGroupId()); _log.debug("extendDateTimeStamp: "+extendDateTimeStamp); if (extendDateTimeStamp > 0) { long hoursCount = (long) (extendDateTimeStamp / (1000 * 60 * 60)); _log.debug("hoursCount: "+hoursCount); //_log.info("dossier.getExtendDate(): "+dossier.getExtendDate()); List<Holiday> holidayList = HolidayLocalServiceUtil .getHolidayByGroupIdAndType(dossier.getGroupId(), 0); List<Holiday> extendWorkDayList = HolidayLocalServiceUtil .getHolidayByGroupIdAndType(dossier.getGroupId(), 1); Date dueDateExtend = HolidayUtils.getEndDate(dossier.getGroupId(), dossier.getDueDate(), hoursCount, holidayList, extendWorkDayList); _log.debug("dueDateExtend: "+dueDateExtend); if (dueDateExtend != null) { dossier.setDueDate(dueDateExtend); //dossier.setCorrecttingDate(null); bResult.put(DossierTerm.DUE_DATE, true); } } } } } } else if (dateOption == DossierTerm.DATE_OPTION_CHANGE_DUE_DATE) { if (dossier.getDueDate() != null) { //dossier.setCorrecttingDate(dossier.getDueDate()); //dossier.setDueDate(null); dossier.setLockState(DossierTerm.PAUSE_STATE); } } else if (dateOption == DossierTerm.DATE_OPTION_RESET_DUE_DATE) { dossier.setLockState(StringPool.BLANK); if (dossier.getDueDate() != null) { if (serviceProcess != null) { Date newDueDate = HolidayUtils.getDueDate(new Date(), serviceProcess.getDurationCount(), serviceProcess.getDurationUnit(), dossier.getGroupId()); if (newDueDate != null) { dossier.setReceiveDate(new Date()); dossier.setDueDate(newDueDate); bResult.put(DossierTerm.DUE_DATE, true); } } } } //Check if dossier is done if (DossierTerm.DOSSIER_STATUS_DONE.equals(curStatus)) { List<DossierFile> lstFiles = dossierFileLocalService.getAllDossierFile(dossier.getDossierId()); for (DossierFile df : lstFiles) { if (!df.getRemoved()) { df.setOriginal(true); } dossierFileLocalService.updateDossierFile(df); } } //Calculate step due date // DossierAction dossierAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId()); // _log.info("dossierAction: "+dossierAction); dossierAction = dossierActionLocalService.fetchDossierAction(dossier.getDossierActionId()); Date rootDate = now; Date dueDate = null; // if (prevAction != null) { // if (prevAction.getDueDate() != null) { // if (rootDate.getTime() < prevAction.getDueDate().getTime()) { // rootDate = prevAction.getDueDate(); // } // } // } Double durationCount = processStep.getDurationCount(); // _log.info("durationCountStep: "+durationCount); int durationUnit = serviceProcess.getDurationUnit(); // _log.info("Calculate do action duration count: " + durationCount); if (Validator.isNotNull(durationCount) && durationCount > 0 && !areEqualDouble(durationCount, 0.00d, 3)) { // _log.info("========STEP DUE DATE CACULATE DUE DATE"); dueDate = HolidayUtils.getDueDate(rootDate, durationCount, durationUnit, dossier.getGroupId()); // _log.info("dueDateAction: "+dueDate); } // _log.info("========STEP DUE DATE:" + dueDate); // DossierLocalServiceUtil.updateDossier(dossier); // _log.info("dossierAction: " + dossierAction); if (dossierAction != null) { // _log.info("========STEP DUE DATE ACTION:" + dueDate); if (dueDate != null) { long dateNowTimeStamp = now.getTime(); Long dueDateTimeStamp = dueDate.getTime(); int overdue = 0; // _log.info("dueDateTEST: "+dueDate); // _log.info("Due date timestamp: " + dueDateTimeStamp); if (dueDateTimeStamp != null && dueDateTimeStamp > 0) { long subTimeStamp = dueDateTimeStamp - dateNowTimeStamp; if (subTimeStamp > 0) { overdue = calculatorOverDue(durationUnit, subTimeStamp); // overdue = calculatorOverDue(durationUnit, subTimeStamp, dateNowTimeStamp, dueDateTimeStamp, // dossierAction.getGroupId(), true); } else { overdue = -calculatorOverDue(durationUnit, subTimeStamp); //// calculatorOverDue(int durationUnit, long subTimeStamp, long releaseDateTimeStamp, //// long dueDateTimeStamp, long groupId, true); // overdue = -calculatorOverDue(durationUnit, subTimeStamp, dateNowTimeStamp, dueDateTimeStamp, // dossierAction.getGroupId(), true); } } else { } // _log.info("dueDateTEST111: "+dueDate); dossierAction.setActionOverdue(overdue); dossierAction.setDueDate(dueDate); // _log.info("========STEP DUE DATE SET DUE DATE: " + dossierAction.getStepCode()); // DossierAction dActTest = DossierActionLocalServiceUtil.updateDossierAction(dossierAction); dossierActionLocalService.updateDossierAction(dossierAction); // _log.info("dActTest: "+dActTest); } else { dossierActionLocalService.updateDossierAction(dossierAction); } } return bResult; } public static boolean areEqualDouble(double a, double b, int precision) { return Math.abs(a - b) <= Math.pow(10, -precision); } private static int calculatorOverDue(int durationUnit, long subTimeStamp) { if (subTimeStamp < 0) { subTimeStamp = Math.abs(subTimeStamp); } double dueCount; double overDue; int retval = Double.compare(durationUnit, 1.0); if (retval < 0) { dueCount = (double) subTimeStamp / VALUE_CONVERT_DATE_TIMESTAMP; double subDueCount = (double) Math.round(dueCount * 100) / 100; overDue = (double) Math.ceil(subDueCount * 4) / 4; return (int)overDue; } else { dueCount = (double) subTimeStamp / VALUE_CONVERT_HOUR_TIMESTAMP; overDue = (double) Math.round(dueCount); } return (int)overDue; } private JSONObject processMergeDossierFormData(Dossier dossier, JSONObject jsonData) { jsonData.put(DossierTerm.GOV_AGENCY_CODE, dossier.getGovAgencyCode()); jsonData.put(DossierTerm.GOV_AGENCY_NAME, dossier.getGovAgencyName()); jsonData.put(DossierTerm.APPLICANT_ID_NO, dossier.getApplicantIdNo()); jsonData.put(DossierTerm.APPLICANT_ID_TYPE, dossier.getApplicantIdType()); jsonData.put(DossierTerm.APPLICANT_ID_DATE, APIDateTimeUtils.convertDateToString(dossier.getApplicantIdDate(), APIDateTimeUtils._NORMAL_PARTTERN)); jsonData.put(DossierTerm.CITY_CODE, dossier.getCityCode()); jsonData.put(DossierTerm.CITY_NAME, dossier.getCityName()); jsonData.put(DossierTerm.DISTRICT_CODE, dossier.getDistrictCode()); jsonData.put(DossierTerm.DISTRICT_NAME, dossier.getDistrictName()); jsonData.put(DossierTerm.WARD_CODE, dossier.getWardCode()); jsonData.put(DossierTerm.WARD_NAME, dossier.getWardName()); jsonData.put(DossierTerm.DOSSIER_NO, dossier.getDossierNo()); jsonData.put(DossierTerm.APPLICANT_NAME, dossier.getApplicantName()); jsonData.put(DossierTerm.ADDRESS, dossier.getAddress()); jsonData.put(DossierTerm.CONTACT_TEL_NO, dossier.getContactTelNo()); jsonData.put(DossierTerm.CONTACT_EMAIL, dossier.getContactEmail()); jsonData.put(DossierTerm.CONTACT_NAME, dossier.getContactName()); jsonData.put(DossierTerm.DELEGATE_ADDRESS, dossier.getDelegateAddress()); jsonData.put(DossierTerm.SERVICE_CODE, dossier.getServiceCode()); jsonData.put(DossierTerm.SERVICE_NAME, dossier.getServiceName()); jsonData.put(DossierTerm.SAMPLE_COUNT, dossier.getSampleCount()); jsonData.put(DossierTerm.DURATION_UNIT, dossier.getDurationUnit()); jsonData.put(DossierTerm.DURATION_COUNT, dossier.getDurationCount()); jsonData.put(DossierTerm.SECRET_KEY, dossier.getPassword()); jsonData.put(DossierTerm.RECEIVE_DATE, APIDateTimeUtils.convertDateToString(dossier.getReceiveDate(), APIDateTimeUtils._NORMAL_PARTTERN)); jsonData.put(DossierTerm.DELEGATE_NAME, dossier.getDelegateName()); jsonData.put(DossierTerm.DELEGATE_EMAIL, dossier.getDelegateEmail()); jsonData.put(DossierTerm.DELEGATE_TELNO, dossier.getDelegateTelNo()); jsonData.put(DossierTerm.DOSSIER_NAME, dossier.getDossierName()); jsonData.put(DossierTerm.VIA_POSTAL, dossier.getViaPostal()); jsonData.put(DossierTerm.POSTAL_ADDRESS, dossier.getPostalAddress()); // Date dueDate = dossier.getDueDate(); if (dueDate != null) { ServiceProcess process = serviceProcessLocalService.getByG_PNO(dossier.getGroupId(), dossier.getProcessNo()); if (process != null) { String dueDatePattern = process.getDueDatePattern(); //_log.info("dueDatePattern: " + dueDatePattern); // _log.info("START DUEDATE TEST"); if (Validator.isNotNull(dueDatePattern)) { //_log.info("START DUEDATE TEST"); // _log.info("dueDatePattern: "+dueDatePattern); try { JSONObject jsonDueDate = JSONFactoryUtil.createJSONObject(dueDatePattern); //_log.info("jsonDueDate: " + jsonDueDate); if (jsonDueDate != null) { JSONObject hours = jsonDueDate.getJSONObject("hour"); JSONObject processHours = jsonDueDate.getJSONObject("processHour"); //_log.info("hours: " + hours); if (hours != null && hours.has("AM") && hours.has("PM")) { //_log.info("AM-PM: "); Calendar receiveCalendar = Calendar.getInstance(); receiveCalendar.setTime(dossier.getReceiveDate()); Calendar dueCalendar = Calendar.getInstance(); //_log.info("hours: " + receiveCalendar.get(Calendar.HOUR_OF_DAY)); if (receiveCalendar.get(Calendar.HOUR_OF_DAY) < 12) { dueCalendar.setTime(dossier.getDueDate()); String hoursAfterNoon = hours.getString("AM"); //_log.info("hoursAfterNoon: " + hoursAfterNoon); if (Validator.isNotNull(hoursAfterNoon)) { String[] splitAfter = StringUtil.split(hoursAfterNoon, StringPool.COLON); if (splitAfter != null) { dueCalendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(splitAfter[0])); dueCalendar.set(Calendar.MINUTE, Integer.valueOf(splitAfter[1])); } } } else { dueCalendar.setTime(dossier.getDueDate()); String hoursAfterNoon = hours.getString("PM"); if (Validator.isNotNull(hoursAfterNoon)) { String[] splitAfter = StringUtil.split(hoursAfterNoon, StringPool.COLON); if (splitAfter != null) { if (Integer.valueOf(splitAfter[0]) < 12) { dueCalendar.add(Calendar.DAY_OF_MONTH, 1); dueCalendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(splitAfter[0])); dueCalendar.set(Calendar.MINUTE, Integer.valueOf(splitAfter[1])); } else { //dueCalendar.add(Calendar.DAY_OF_MONTH, 1); dueCalendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(splitAfter[0])); dueCalendar.set(Calendar.MINUTE, Integer.valueOf(splitAfter[1])); } } } } jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils .convertDateToString(dueCalendar.getTime(), APIDateTimeUtils._NORMAL_PARTTERN)); } else if (processHours != null && processHours.has("startHour") && processHours.has("dueHour")) { //_log.info("STRART check new: "); Calendar receiveCalendar = Calendar.getInstance(); receiveCalendar.setTime(dossier.getReceiveDate()); // String receiveHour = processHours.getString("startHour"); //_log.info("receiveHour: " + receiveHour); if (Validator.isNotNull(receiveHour)) { String[] splitHour = StringUtil.split(receiveHour, StringPool.COLON); if (splitHour != null) { int hourStart = GetterUtil.getInteger(splitHour[0]); if (receiveCalendar.get(Calendar.HOUR_OF_DAY) < hourStart) { String[] splitdueHour = StringUtil.split(processHours.getString("dueHour"), StringPool.COLON); Calendar dueCalendar = Calendar.getInstance(); if (splitdueHour != null) { dueCalendar.set(Calendar.HOUR_OF_DAY, GetterUtil.getInteger(splitdueHour[0])); dueCalendar.set(Calendar.MINUTE, GetterUtil.getInteger(splitdueHour[1])); } else { jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils.convertDateToString( dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN)); } jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils.convertDateToString( dueCalendar.getTime(), APIDateTimeUtils._NORMAL_PARTTERN)); } else { jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils.convertDateToString( dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN)); } } } } else { jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils .convertDateToString(dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN)); } } else { jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils .convertDateToString(dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN)); } } catch (JSONException e) { _log.error(e); jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils.convertDateToString(dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN)); } } else { jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils.convertDateToString(dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN)); } } else { jsonData.put(DossierTerm.DUE_DATE, APIDateTimeUtils.convertDateToString(dossier.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN)); } } else { jsonData.put(DossierTerm.DUE_DATE, StringPool.BLANK); } // jsonData.put(DossierTerm.POSTAL_ADDRESS, dossier.getPostalAddress()); jsonData.put(DossierTerm.COUNTER, dossier.getCounter()); jsonData.put(DossierTerm.REGISTER_BOOK_CODE, dossier.getRegisterBookCode()); jsonData.put(DossierTerm.SECRET, dossier.getPassword()); jsonData.put(DossierTerm.BRIEF_NOTE, dossier.getBriefNote()); jsonData.put(DossierTerm.DOSSIER_ID, dossier.getDossierId()); // long groupId = dossier.getGroupId(); JSONArray dossierMarkArr = JSONFactoryUtil.createJSONArray(); long dossierId = dossier.getDossierId(); String templateNo = dossier.getDossierTemplateNo(); List<DossierMark> dossierMarkList = dossierMarkLocalService.getDossierMarksByFileMark(groupId, dossierId, 0); if (dossierMarkList != null && dossierMarkList.size() > 0) { JSONObject jsonMark = null; String partNo; for (DossierMark dossierMark : dossierMarkList) { jsonMark = JSONFactoryUtil.createJSONObject(); partNo = dossierMark.getDossierPartNo(); if (Validator.isNotNull(partNo)) { DossierPart part = dossierPartLocalService.getByTempAndPartNo(groupId, templateNo, partNo); if (part != null) { jsonMark.put(DossierPartTerm.DOSSIERPART_ID, part.getDossierPartId()); jsonMark.put(DossierPartTerm.PART_NAME, part.getPartName()); jsonMark.put(DossierPartTerm.PART_TIP, part.getPartTip()); jsonMark.put(DossierPartTerm.PART_TYPE, part.getPartType()); } } jsonMark.put(DossierPartTerm.PART_NO, partNo); jsonMark.put(DossierPartTerm.FILE_MARK, dossierMark.getFileMark()); jsonMark.put(DossierPartTerm.FILE_CHECK, dossierMark.getFileCheck()); jsonMark.put(DossierPartTerm.FILE_COMMENT, dossierMark.getFileComment()); // String strDossierMark = JSONFactoryUtil.looseSerialize(dossierMark); dossierMarkArr.put(jsonMark); } } //Hot fix TP99 DossierMark dossierMark = dossierMarkLocalService.getDossierMarkbyDossierId(groupId, dossierId, "TP99"); if (dossierMark != null) { JSONObject jsonMark = null; String partNo = dossierMark.getDossierPartNo(); if (Validator.isNotNull(partNo)) { List<DossierFile> fileList = dossierFileLocalService.getDossierFileByDID_DPNO(dossierId, partNo, false); DossierPart part = dossierPartLocalService.getByTempAndPartNo(groupId, templateNo, partNo); if (fileList != null && part != null) { for (DossierFile dossierFile : fileList) { jsonMark = JSONFactoryUtil.createJSONObject(); jsonMark.put(DossierPartTerm.PART_NAME, dossierFile.getDisplayName()); jsonMark.put(DossierPartTerm.DOSSIERPART_ID, part.getDossierPartId()); jsonMark.put(DossierPartTerm.PART_TIP, part.getPartTip()); jsonMark.put(DossierPartTerm.PART_TYPE, part.getPartType()); jsonMark.put(DossierPartTerm.PART_NO, partNo); jsonMark.put(DossierPartTerm.FILE_MARK, dossierMark.getFileMark()); jsonMark.put(DossierPartTerm.FILE_CHECK, dossierMark.getFileCheck()); jsonMark.put(DossierPartTerm.FILE_COMMENT, dossierMark.getFileComment()); // String strDossierMark = JSONFactoryUtil.looseSerialize(dossierMark); dossierMarkArr.put(jsonMark); } } } } jsonData.put(DossierTerm.DOSSIER_MARKS, dossierMarkArr); PaymentFile payment = paymentFileLocalService.getByDossierId(groupId, dossierId); if (payment != null) { jsonData.put(PaymentFileTerm.ADVANCE_AMOUNT, payment.getAdvanceAmount()); jsonData.put(PaymentFileTerm.PAYMENT_AMOUNT, payment.getPaymentAmount()); jsonData.put(PaymentFileTerm.PAYMENT_FEE, payment.getPaymentFee()); jsonData.put(PaymentFileTerm.SERVICE_AMOUNT, payment.getServiceAmount()); jsonData.put(PaymentFileTerm.SHIP_AMOUNT, payment.getShipAmount()); } if (dossier.getOriginality() == DossierTerm.ORIGINALITY_HOSONHOM) { JSONArray groupDossierArr = JSONFactoryUtil.createJSONArray(); List<Dossier> lstDossiers = dossierLocalService.findByG_GDID(groupId, dossier.getDossierId()); for (Dossier d : lstDossiers) { JSONObject dObject = JSONFactoryUtil.createJSONObject(); dObject.put(DossierTerm.DOSSIER_NO, d.getDossierNo()); dObject.put(DossierTerm.APPLICANT_NAME, d.getApplicantName()); dObject.put(DossierTerm.ADDRESS, d.getAddress()); dObject.put(DossierTerm.CONTACT_TEL_NO, d.getContactTelNo()); dObject.put(DossierTerm.CONTACT_EMAIL, d.getContactEmail()); dObject.put(DossierTerm.CONTACT_NAME, d.getContactName()); dObject.put(DossierTerm.DELEGATE_ADDRESS, d.getDelegateAddress()); dObject.put(DossierTerm.SERVICE_CODE, d.getServiceCode()); dObject.put(DossierTerm.SERVICE_NAME, d.getServiceName()); dObject.put(DossierTerm.SAMPLE_COUNT, d.getSampleCount()); dObject.put(DossierTerm.DURATION_UNIT, d.getDurationUnit()); dObject.put(DossierTerm.DURATION_COUNT, d.getDurationCount()); dObject.put(DossierTerm.SECRET_KEY, d.getPassword()); dObject.put(DossierTerm.RECEIVE_DATE, APIDateTimeUtils.convertDateToString(d.getReceiveDate(), APIDateTimeUtils._NORMAL_PARTTERN)); dObject.put(DossierTerm.DELEGATE_NAME, d.getDelegateName()); dObject.put(DossierTerm.DELEGATE_EMAIL, d.getDelegateEmail()); dObject.put(DossierTerm.DELEGATE_TELNO, d.getDelegateTelNo()); dObject.put(DossierTerm.DOSSIER_NAME, d.getDossierName()); dObject.put(DossierTerm.VIA_POSTAL, d.getViaPostal()); dObject.put(DossierTerm.POSTAL_ADDRESS, d.getPostalAddress()); groupDossierArr.put(dObject); } jsonData.put(DossierTerm.GROUP_DOSSIERS, groupDossierArr); } return jsonData; } //LamTV_ Mapping process dossier and formData private JSONObject processMergeDossierProcessRole(Dossier dossier, int length, JSONObject jsonData, DossierAction dAction) { // long groupId = dossier.getGroupId(); if (dAction != null) { long serviceProcessId = dAction.getServiceProcessId(); jsonData.put(DossierTerm.GOV_AGENCY_NAME, dossier.getGovAgencyName()); jsonData.put(DossierTerm.TOTAL, length); jsonData.put(DossierTerm.ACTION_USER, dAction.getActionUser()); String sequenceNo = dAction.getSequenceNo(); if (Validator.isNotNull(sequenceNo)) { ProcessSequence sequence = processSequenceLocalService.findBySID_SNO(groupId, serviceProcessId, sequenceNo); if (sequence != null) { jsonData.put(DossierTerm.SEQUENCE_ROLE, sequence.getSequenceRole()); } else { jsonData.put(DossierTerm.SEQUENCE_ROLE, StringPool.BLANK); } } else { jsonData.put(DossierTerm.SEQUENCE_ROLE, StringPool.BLANK); } // Process get Next sequence Role List<ProcessSequence> sequenceList = processSequenceLocalService.getByServiceProcess(groupId, serviceProcessId); String[] sequenceArr = null; if (sequenceList != null && !sequenceList.isEmpty()) { int lengthSeq = sequenceList.size(); sequenceArr = new String[lengthSeq]; for (int i = 0; i < lengthSeq; i++) { ProcessSequence processSequence = sequenceList.get(i); if (processSequence != null) { sequenceArr[i] = processSequence.getSequenceNo(); } } } if (sequenceArr != null && sequenceArr.length > 0) { for (int i = 0; i < sequenceArr.length; i++) { // _log.info("sequenceArr[i]: "+sequenceArr[i]); } Arrays.sort(sequenceArr); for (int i = 0; i < sequenceArr.length - 1; i++) { String seq = sequenceArr[i]; if (sequenceNo.equals(seq)) { String nextSequenceNo = sequenceArr[i + 1]; if (Validator.isNotNull(nextSequenceNo)) { ProcessSequence sequence = processSequenceLocalService.findBySID_SNO(groupId, serviceProcessId, nextSequenceNo); if (sequence != null) { jsonData.put(DossierTerm.NEXT_SEQUENCE_ROLE, sequence.getSequenceRole()); } else { jsonData.put(DossierTerm.NEXT_SEQUENCE_ROLE, StringPool.BLANK); } } else { jsonData.put(DossierTerm.NEXT_SEQUENCE_ROLE, StringPool.BLANK); } } } } else { jsonData.put(DossierTerm.NEXT_SEQUENCE_ROLE, StringPool.BLANK); } } return jsonData; } private void vnpostEvent(Dossier dossier) { Message message = new Message(); JSONObject msgData = JSONFactoryUtil.createJSONObject(); message.put("msgToEngine", msgData); message.put("dossier", DossierMgtUtils.convertDossierToJSON(dossier)); MessageBusUtil.sendMessage("vnpost/dossier/in/destination", message); } private void publishEvent(Dossier dossier, ServiceContext context) { if (dossier.getOriginDossierId() != 0 || Validator.isNotNull(dossier.getOriginDossierNo())) { return; } Message message = new Message(); JSONObject msgData = JSONFactoryUtil.createJSONObject(); message.put("msgToEngine", msgData); message.put("dossier", DossierMgtUtils.convertDossierToJSON(dossier)); // MessageBusUtil.sendMessage(DossierTerm.PUBLISH_DOSSIER_DESTINATION, message); Message lgspMessage = new Message(); JSONObject lgspMsgData = msgData; lgspMessage.put("msgToEngine", lgspMsgData); lgspMessage.put("dossier", DossierMgtUtils.convertDossierToJSON(dossier)); // MessageBusUtil.sendMessage(DossierTerm.LGSP_DOSSIER_DESTINATION, lgspMessage); //Add publish queue List<ServerConfig> lstScs = ServerConfigLocalServiceUtil.getByProtocol(dossier.getGroupId(), ServerConfigTerm.PUBLISH_PROTOCOL); for (ServerConfig sc : lstScs) { try { List<PublishQueue> lstQueues = PublishQueueLocalServiceUtil.getByG_DID_SN_ST(dossier.getGroupId(), dossier.getDossierId(), sc.getServerNo(), new int[] { PublishQueueTerm.STATE_WAITING_SYNC, PublishQueueTerm.STATE_ALREADY_SENT }); if (lstQueues == null || lstQueues.isEmpty()) { publishQueueLocalService.updatePublishQueue(dossier.getGroupId(), 0, dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context); } // PublishQueue pq = PublishQueueLocalServiceUtil.getByG_DID_SN(dossier.getGroupId(), dossier.getDossierId(), sc.getServerNo()); // if (pq == null) { // PublishQueueLocalServiceUtil.updatePublishQueue(dossier.getGroupId(), 0, dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context); // } // else { // if (pq.getStatus() == PublishQueueTerm.STATE_ACK_ERROR) { // PublishQueueLocalServiceUtil.updatePublishQueue(dossier.getGroupId(), pq.getPublishQueueId(), dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context); // } // } } catch (PortalException e) { _log.debug(e); } } lstScs = ServerConfigLocalServiceUtil.getByProtocol(dossier.getGroupId(), ServerConfigTerm.LGSP_PROTOCOL); for (ServerConfig sc : lstScs) { try { List<PublishQueue> lstQueues = publishQueueLocalService.getByG_DID_SN_ST(dossier.getGroupId(), dossier.getDossierId(), sc.getServerNo(), new int[] { PublishQueueTerm.STATE_WAITING_SYNC, PublishQueueTerm.STATE_ALREADY_SENT }); if (lstQueues == null || lstQueues.isEmpty()) { publishQueueLocalService.updatePublishQueue(dossier.getGroupId(), 0, dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context); } // PublishQueue pq = PublishQueueLocalServiceUtil.getByG_DID_SN(dossier.getGroupId(), dossier.getDossierId(), sc.getServerNo()); // if (pq == null) { // PublishQueueLocalServiceUtil.updatePublishQueue(dossier.getGroupId(), 0, dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context); // } // else { // if (pq.getStatus() == PublishQueueTerm.STATE_ACK_ERROR) { // PublishQueueLocalServiceUtil.updatePublishQueue(dossier.getGroupId(), pq.getPublishQueueId(), dossier.getDossierId(), sc.getServerNo(), PublishQueueTerm.STATE_WAITING_SYNC, 0, context); // } // } } catch (PortalException e) { _log.debug(e); } } } private ProcessOption getProcessOption(String serviceInfoCode, String govAgencyCode, String dossierTemplateNo, long groupId) throws PortalException { ServiceConfig config = serviceConfigLocalService.getBySICodeAndGAC(groupId, serviceInfoCode, govAgencyCode); return processOptionLocalService.getByDTPLNoAndServiceCF(groupId, dossierTemplateNo, config.getServiceConfigId()); } protected ProcessAction getProcessAction(long groupId, long dossierId, String refId, String actionCode, long serviceProcessId) throws PortalException { ProcessAction action = null; try { List<ProcessAction> actions = processActionLocalService.getByActionCode(groupId, actionCode, serviceProcessId); Dossier dossier = getDossier(groupId, dossierId, refId); String dossierStatus = dossier.getDossierStatus(); String dossierSubStatus = Validator.isNull(dossier.getDossierSubStatus()) ? StringPool.BLANK : dossier.getDossierSubStatus(); for (ProcessAction act : actions) { String preStepCode = act.getPreStepCode(); ProcessStep step = processStepLocalService.fetchBySC_GID(preStepCode, groupId, serviceProcessId); String subStepStatus = StringPool.BLANK; if (Validator.isNotNull(step)) { subStepStatus = Validator.isNull(step.getDossierSubStatus()) ? StringPool.BLANK : step.getDossierSubStatus(); } if (Validator.isNull(step)) { action = act; break; } else { if (step.getDossierStatus().contentEquals(dossierStatus) && subStepStatus.contentEquals(dossierSubStatus)) { action = act; break; } } } } catch (Exception e) { _log.debug(e); //_log.error(e); throw new NotFoundException("ProcessActionNotFoundException with actionCode= " + actionCode + "|serviceProcessId= " + serviceProcessId + "|referenceUid= " + refId + "|groupId= " + groupId); } return action; } protected Dossier getDossier(long groupId, long dossierId, String refId) throws PortalException { Dossier dossier = null; if (dossierId != 0) { dossier = dossierLocalService.fetchDossier(dossierId); } else { dossier = dossierLocalService.getByRef(groupId, refId); } return dossier; } private String generatorGoodCode(int length) { String tempGoodCode = _generatorUniqueString(length); String goodCode; while (_checkContainsGoodCode(tempGoodCode)) { tempGoodCode = _generatorUniqueString(length); } /* * while(_testCheck(tempGoodCode)) { tempGoodCode = * _generatorUniqueString(length); } */ goodCode = tempGoodCode; return goodCode; } private boolean _checkContainsGoodCode(String keypayGoodCode) { boolean isContains = false; try { PaymentFile paymentFile = null;//PaymentFileLocalServiceUtil.getByGoodCode(keypayGoodCode); if (Validator.isNotNull(paymentFile)) { isContains = true; } } catch (Exception e) { _log.error(e); isContains = true; } return isContains; } private DossierAction doActionOutsideProcess(long groupId, long userId, Dossier dossier, ActionConfig actionConfig, ProcessOption option, ProcessAction proAction, String actionCode, String actionUser, String actionNote, String payload, String assignUsers, String payment, int syncType, ServiceContext context) throws PortalException, SystemException, Exception { context.setUserId(userId); DossierAction dossierAction = null; String dossierStatus = dossier.getDossierStatus().toLowerCase(); if (Validator.isNotNull(dossierStatus) && !"new".equals(dossierStatus)) { dossier = dossierLocalService.updateDossier(dossier); } ServiceProcess serviceProcess = null; if (option != null) { long serviceProcessId = option.getServiceProcessId(); serviceProcess = serviceProcessLocalService.fetchServiceProcess(serviceProcessId); } dossierAction = dossierActionLocalService.fetchDossierAction(dossier.getDossierActionId()); // ActionConfig ac = actionConfigLocalService.getByCode(groupId, actionCode); ActionConfig ac = actionConfig; JSONObject payloadObject = JSONFactoryUtil.createJSONObject(payload); if (Validator.isNotNull(payload)) { if (DossierActionTerm.OUTSIDE_ACTION_9100.equals(actionCode)) { dossier = dossierLocalService.updateDossierSpecial(dossier.getDossierId(), payloadObject); } else { dossier = dossierLocalService.updateDossier(dossier.getDossierId(), payloadObject); } } if (DossierActionTerm.OUTSIDE_ACTION_ROLLBACK.equals(actionCode)) { if (dossierAction != null && dossierAction.isRollbackable()) { dossierActionLocalService.updateState(dossierAction.getDossierActionId(), DossierActionTerm.STATE_ROLLBACK); DossierAction previousAction = dossierActionLocalService.fetchDossierAction(dossierAction.getPreviousActionId()); if (previousAction != null) { dossierActionLocalService.updateState(previousAction.getDossierActionId(), DossierActionTerm.STATE_WAITING_PROCESSING); dossierActionLocalService.updateNextActionId(previousAction.getDossierActionId(), 0); dossierLocalService.rollback(dossier, previousAction); } else { dossierActionLocalService.removeAction(dossierAction.getDossierActionId()); dossier.setDossierActionId(0); dossierLocalService.updateDossier(dossier); } } } //Create DossierSync String dossierRefUid = dossier.getReferenceUid(); String syncRefUid = UUID.randomUUID().toString(); if (syncType > 0) { int state = DossierActionUtils.getSyncState(syncType, dossier); //Update payload if (Validator.isNotNull(dossier.getServerNo()) && dossier.getServerNo().split(StringPool.BLANK).length > 1) { String serverNo = dossier.getServerNo().split(StringPool.COMMA)[0].split(StringPool.AT)[0]; dossierSyncLocalService.updateDossierSync(groupId, userId, dossier.getDossierId(), dossierRefUid, syncRefUid, dossierAction.getPrimaryKey(), actionCode, ac.getActionName(), actionUser, actionNote, syncType, ac.getInfoType(), payloadObject.toJSONString(), serverNo, state); } else { dossierSyncLocalService.updateDossierSync(groupId, userId, dossier.getDossierId(), dossierRefUid, syncRefUid, dossierAction.getPrimaryKey(), actionCode, ac.getActionName(), actionUser, actionNote, syncType, ac.getInfoType(), payloadObject.toJSONString(), dossier.getServerNo(), state); } } if (ac != null && dossierAction != null) { //Only create dossier document if 2 && 3 if (dossier.getOriginality() != DossierTerm.ORIGINALITY_DVCTT) { if (Validator.isNotNull(ac.getDocumentType()) && !ac.getActionCode().startsWith("@")) { //Generate document DocumentType dt = documentTypeLocalService.getByTypeCode(groupId, ac.getDocumentType()); if (dt != null) { String documentCode = DocumentTypeNumberGenerator.generateDocumentTypeNumber(groupId, ac.getCompanyId(), dt.getDocumentTypeId()); DossierDocument dossierDocument = dossierDocumentLocalService.addDossierDoc(groupId, dossier.getDossierId(), UUID.randomUUID().toString(), dossierAction.getDossierActionId(), dt.getTypeCode(), dt.getDocumentName(), documentCode, 0L, dt.getDocSync(), context); //Generate PDF String formData = payload; JSONObject formDataObj = processMergeDossierFormData(dossier, JSONFactoryUtil.createJSONObject(formData)); // _log.info("Dossier document form data action outside: " + formDataObj.toJSONString()); Message message = new Message(); // _log.info("Document script: " + dt.getDocumentScript()); JSONObject msgData = JSONFactoryUtil.createJSONObject(); msgData.put("className", DossierDocument.class.getName()); msgData.put("classPK", dossierDocument.getDossierDocumentId()); msgData.put("jrxmlTemplate", dt.getDocumentScript()); msgData.put("formData", formDataObj.toJSONString()); msgData.put("userId", userId); message.put("msgToEngine", msgData); MessageBusUtil.sendMessage("jasper/engine/out/destination", message); } } } } if (ac != null && ac.getEventType() == ActionConfigTerm.EVENT_TYPE_SENT) { publishEvent(dossier, context); } if (OpenCPSConfigUtil.isNotificationEnable()) { createNotificationQueueOutsideProcess(userId, groupId, dossier, actionConfig, context); } if (DossierActionTerm.OUTSIDE_ACTION_ROLLBACK.equals(actionCode)) { if (dossier.getOriginDossierId() != 0) { Dossier hslt = dossierLocalService.fetchDossier(dossier.getOriginDossierId()); ProcessOption optionHslt = getProcessOption(hslt.getServiceCode(), hslt.getGovAgencyCode(), hslt.getDossierTemplateNo(), groupId); String actionUserHslt = actionUser; if (DossierTerm.DOSSIER_STATUS_NEW.equals(hslt.getDossierStatus())) { Date now = new Date(); hslt.setSubmitDate(now); hslt = dossierLocalService.updateDossier(hslt); try { JSONObject payloadObj = JSONFactoryUtil.createJSONObject(payload); payloadObj.put(DossierTerm.SUBMIT_DATE, now.getTime()); payload = payloadObj.toJSONString(); } catch (JSONException e) { _log.debug(e); } } doAction(groupId, userId, hslt, optionHslt, null, DossierActionTerm.OUTSIDE_ACTION_ROLLBACK, actionUserHslt, actionNote, payload, assignUsers, payment, 0, context); } } return dossierAction; } private void createNotificationQueueOutsideProcess(long userId, long groupId, Dossier dossier, ActionConfig actionConfig, ServiceContext context) { DossierAction dossierAction = dossierActionLocalService.fetchDossierAction(dossier.getDossierActionId()); User u = UserLocalServiceUtil.fetchUser(userId); JSONObject payloadObj = JSONFactoryUtil.createJSONObject(); try { payloadObj.put( "Dossier", JSONFactoryUtil.createJSONObject( JSONFactoryUtil.looseSerialize(dossier))); if (dossierAction != null) { payloadObj.put("actionCode", dossierAction.getActionCode()); payloadObj.put("actionUser", dossierAction.getActionUser()); payloadObj.put("actionName", dossierAction.getActionName()); payloadObj.put("actionNote", dossierAction.getActionNote()); } } catch (Exception e) { _log.error(e); } if (actionConfig != null && Validator.isNotNull(actionConfig.getNotificationType())) { Notificationtemplate notiTemplate = NotificationtemplateLocalServiceUtil.fetchByF_NotificationtemplateByType(groupId, actionConfig.getNotificationType()); Date now = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(now); if (notiTemplate != null) { if ("minutely".equals(notiTemplate.getInterval())) { cal.add(Calendar.MINUTE, notiTemplate.getExpireDuration()); } else if ("hourly".equals(notiTemplate.getInterval())) { cal.add(Calendar.HOUR, notiTemplate.getExpireDuration()); } else { cal.add(Calendar.MINUTE, notiTemplate.getExpireDuration()); } Date expired = cal.getTime(); if (actionConfig.getNotificationType().startsWith("APLC")) { if (dossier.getOriginality() == DossierTerm.ORIGINALITY_MOTCUA || dossier.getOriginality() == DossierTerm.ORIGINALITY_LIENTHONG) { try { Applicant applicant = ApplicantLocalServiceUtil.fetchByAppId(dossier.getApplicantIdNo()); long toUserId = (applicant != null ? applicant.getMappingUserId() : 0l); NotificationQueueLocalServiceUtil.addNotificationQueue( userId, groupId, actionConfig.getNotificationType(), Dossier.class.getName(), String.valueOf(dossier.getDossierId()), payloadObj.toJSONString(), u.getFullName(), dossier.getApplicantName(), toUserId, dossier.getContactEmail(), dossier.getContactTelNo(), now, expired, context); } catch (NoSuchUserException e) { _log.error(e); } } } else if (actionConfig.getNotificationType().startsWith("USER")) { } } } } /** * @param pattern * @param lenght * @return */ private String _generatorUniqueString(int lenght) { char[] chars = "0123456789".toCharArray(); StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < lenght; i++) { char c = chars[random.nextInt(chars.length)]; sb.append(c); } return sb.toString(); } private void assignDossierActionUser(Dossier dossier, int allowAssignUser, DossierAction dossierAction, long userId, long groupId, long assignUserId, JSONArray assignedUsers) throws PortalException { int moderator = 1; List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId()); HashMap<Long, DossierUser> mapDus = new HashMap<>(); for (DossierUser du : lstDus) { mapDus.put(du.getUserId(), du); } List<org.opencps.dossiermgt.model.DossierActionUser> lstDaus = dossierActionUserLocalService.getByDossierId(dossier.getDossierId()); HashMap<Long, Map<Long, org.opencps.dossiermgt.model.DossierActionUser>> mapDaus = new HashMap<>(); for (org.opencps.dossiermgt.model.DossierActionUser dau : lstDaus) { if (mapDaus.get(dau.getDossierActionId()) != null) { Map<Long, org.opencps.dossiermgt.model.DossierActionUser> temp = mapDaus.get(dau.getDossierActionId()); temp.put(dau.getUserId(), dau); } else { Map<Long, org.opencps.dossiermgt.model.DossierActionUser> temp = new HashMap<>(); temp.put(dau.getUserId(), dau); mapDaus.put(dau.getDossierActionId(), temp); } } for (int n = 0; n < assignedUsers.length(); n++) { JSONObject subUser = assignedUsers.getJSONObject(n); if (subUser != null && subUser.has(DossierActionUserTerm.ASSIGNED) && subUser.getInt(DossierActionUserTerm.ASSIGNED) == DossierActionUserTerm.ASSIGNED_TH) { DossierActionUserPK pk = new DossierActionUserPK(); long userIdAssigned = subUser.getLong("userId"); pk.setDossierActionId(dossierAction.getDossierActionId()); pk.setUserId(subUser.getLong("userId")); DossierUser dossierUser = null; dossierUser = mapDus.get(subUser.getLong("userId")); if (dossierUser != null) { //Update dossier user if assigned if (allowAssignUser != ProcessActionTerm.NOT_ASSIGNED) { dossierUser.setModerator(1); dossierUserLocalService.updateDossierUser(dossierUser.getDossierId(), dossierUser.getUserId(), dossierUser.getModerator(), dossierUser.getVisited()); // model.setModerator(dossierUser.getModerator()); moderator = dossierUser.getModerator(); } } else { if (allowAssignUser != ProcessActionTerm.NOT_ASSIGNED) { dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userIdAssigned, 1, true); } } // org.opencps.dossiermgt.model.DossierActionUser dau = DossierActionUserLocalServiceUtil.fetchDossierActionUser(pk); org.opencps.dossiermgt.model.DossierActionUser dau = null; // dau = mapDaus.get(userIdAssigned); if (mapDaus.get(dossierAction.getDossierActionId()) != null) { dau = mapDaus.get(dossierAction.getDossierActionId()).get(userIdAssigned); } if (Validator.isNull(dau)) { // DossierAction dAction = DossierActionLocalServiceUtil.fetchDossierAction(dossierAction.getDossierActionId()); DossierAction dAction = dossierAction; if (dAction != null) { addDossierActionUserByAssigned(allowAssignUser, userIdAssigned, dossierAction.getDossierActionId(), moderator, false, dAction.getStepCode(), dossier.getDossierId()); } else { addDossierActionUserByAssigned(allowAssignUser, userIdAssigned, dossierAction.getDossierActionId(), moderator, false, StringPool.BLANK, dossier.getDossierId()); } } else { dau.setModerator(1); dossierActionUserLocalService.updateDossierActionUser(dau); } } else if (subUser != null && subUser.has(DossierActionUserTerm.ASSIGNED) && subUser.getInt(DossierActionUserTerm.ASSIGNED) == DossierActionUserTerm.NOT_ASSIGNED) { // model = new org.opencps.dossiermgt.model.impl.DossierActionUserImpl(); DossierActionUserPK pk = new DossierActionUserPK(); pk.setDossierActionId(dossierAction.getDossierActionId()); pk.setUserId(subUser.getLong("userId")); org.opencps.dossiermgt.model.DossierActionUser dau = dossierActionUserLocalService.fetchDossierActionUser(pk); if (Validator.isNull(dau)) { } else { dau.setModerator(0); dossierActionUserLocalService.updateDossierActionUser(dau); } } } } private void addDossierActionUserByAssigned(int allowAssignUser, long userId, long dossierActionId, int moderator, boolean visited, String stepCode, long dossierId) { org.opencps.dossiermgt.model.DossierActionUser model = new org.opencps.dossiermgt.model.impl.DossierActionUserImpl(); int assigned = DossierActionUserTerm.NOT_ASSIGNED; model.setVisited(visited); model.setDossierId(dossierId); model.setStepCode(stepCode); //Check employee is exits and wokingStatus Employee employee = EmployeeLocalServiceUtil.fetchByFB_MUID(userId); _log.debug("Employee : " + employee); if (employee != null && employee.getWorkingStatus() == 1) { DossierActionUserPK pk = new DossierActionUserPK(dossierActionId, userId); org.opencps.dossiermgt.model.DossierActionUser dau = dossierActionUserLocalService.fetchDossierActionUser(pk); if (allowAssignUser == ProcessActionTerm.NOT_ASSIGNED) { model.setUserId(userId); model.setDossierActionId(dossierActionId); model.setModerator(moderator); if (moderator == 1) { model.setAssigned(1); } else { model.setAssigned(assigned); } // Add User // _log.info("Add assigned user by step role: " + model); if (dau == null) { dossierActionUserLocalService.addDossierActionUser(model); } else { if (dau.getModerator() != DossierActionUserTerm.ASSIGNED_TH && model.getModerator() == DossierActionUserTerm.ASSIGNED_TH) { dossierActionUserLocalService.updateDossierActionUser(model); } } } else if (allowAssignUser == ProcessActionTerm.ASSIGNED_TH) { _log.debug("Assign dau: " + userId); model.setUserId(userId); model.setDossierActionId(dossierActionId); model.setModerator(moderator); assigned = DossierActionUserTerm.ASSIGNED_TH; model.setAssigned(assigned); // Add User if (dau == null) { _log.debug("Assign add dau: " + userId); dossierActionUserLocalService.addDossierActionUser(model); } else { if (dau.getModerator() != DossierActionUserTerm.ASSIGNED_TH && model.getModerator() == DossierActionUserTerm.ASSIGNED_TH) { _log.debug("Assign update dau: " + userId); dossierActionUserLocalService.updateDossierActionUser(model); } } } else if (allowAssignUser == ProcessActionTerm.ASSIGNED_TH_PH) { model.setUserId(userId); model.setDossierActionId(dossierActionId); model.setModerator(moderator); assigned = DossierActionUserTerm.ASSIGNED_TH; model.setAssigned(assigned); // Add User dossierActionUserLocalService.addDossierActionUser(model); model.setUserId(userId); model.setDossierActionId(dossierActionId); model.setModerator(moderator); model.setVisited(true); assigned = DossierActionUserTerm.ASSIGNED_PH; model.setAssigned(assigned); // Add User if (dau == null) { dossierActionUserLocalService.addDossierActionUser(model); } else { if (dau.getModerator() != DossierActionUserTerm.ASSIGNED_TH && model.getModerator() == DossierActionUserTerm.ASSIGNED_TH) { dossierActionUserLocalService.updateDossierActionUser(model); } } } else if (allowAssignUser == ProcessActionTerm.ASSIGNED_TH_PH_TD) { model.setUserId(userId); model.setDossierActionId(dossierActionId); model.setModerator(moderator); assigned = DossierActionUserTerm.ASSIGNED_TH; model.setAssigned(assigned); // Add User dossierActionUserLocalService.addDossierActionUser(model); model.setUserId(userId); model.setDossierActionId(dossierActionId); model.setModerator(moderator); assigned = DossierActionUserTerm.ASSIGNED_PH; model.setAssigned(assigned); // Add User dossierActionUserLocalService.addDossierActionUser(model); model.setUserId(userId); model.setDossierActionId(dossierActionId); model.setModerator(moderator); assigned = DossierActionUserTerm.ASSIGNED_TD; model.setAssigned(assigned); // Add User if (dau == null) { dossierActionUserLocalService.addDossierActionUser(model); } else { if (dau.getModerator() != DossierActionUserTerm.ASSIGNED_TH && model.getModerator() == DossierActionUserTerm.ASSIGNED_TH) { dossierActionUserLocalService.updateDossierActionUser(model); } } } } } public void initDossierActionUser(ProcessAction processAction, Dossier dossier, int allowAssignUser, DossierAction dossierAction, long userId, long groupId, long assignUserId) throws PortalException { // Delete record in dossierActionUser List<org.opencps.dossiermgt.model.DossierActionUser> dossierActionUser = dossierActionUserLocalService .getListUser(dossierAction.getDossierActionId()); if (dossierActionUser != null && dossierActionUser.size() > 0) { dossierActionUserLocalService.deleteByDossierAction(dossierAction.getDossierActionId()); } long serviceProcessId = dossierAction.getServiceProcessId(); String stepCode = processAction.getPostStepCode(); // Get ProcessStep ProcessStep processStep = processStepLocalService.fetchBySC_GID(stepCode, groupId, serviceProcessId); long processStepId = processStep.getProcessStepId(); // Get List ProcessStepRole List<ProcessStepRole> listProcessStepRole = processStepRoleLocalService.findByP_S_ID(processStepId); ProcessStepRole processStepRole = null; List<DossierAction> lstStepActions = dossierActionLocalService.getByDID_FSC_NOT_DAI(dossier.getDossierId(), stepCode, dossierAction.getDossierActionId()); if (listProcessStepRole.size() != 0) { for (int i = 0; i < listProcessStepRole.size(); i++) { processStepRole = listProcessStepRole.get(i); long roleId = processStepRole.getRoleId(); boolean moderator = processStepRole.getModerator(); int mod = 0; if (moderator) { mod = 1; } // Get list user List<User> users = UserLocalServiceUtil.getRoleUsers(roleId); for (User user : users) { Employee employee = EmployeeLocalServiceUtil.fetchByFB_MUID(userId); //_log.debug("Employee : " + employee); if (employee != null && employee.getWorkingStatus() == 1) { List<DossierAction> lstDoneActions = dossierActionLocalService .getByDID_U_FSC(dossier.getDossierId(), user.getUserId(), stepCode); if (!lstStepActions.isEmpty()) { if (!lstDoneActions.isEmpty()) mod = 1; else mod = 0; } updateDossierUser(dossier, processStepRole, user); addDossierActionUserByAssigned(processAction.getAllowAssignUser(), user.getUserId(), dossierAction.getDossierActionId(), mod, false, stepCode, dossier.getDossierId()); } } } } else { //Get role from service process initDossierActionUserByServiceProcessRole(dossier, allowAssignUser, dossierAction, userId, groupId, assignUserId); } } private void updateDossierUser(Dossier dossier, ProcessStepRole processStepRole, User user) { DossierUserPK pk = new DossierUserPK(); pk.setDossierId(dossier.getDossierId()); pk.setUserId(user.getUserId()); DossierUser du = dossierUserLocalService.fetchDossierUser(pk); if (du == null) { dossierUserLocalService.addDossierUser(dossier.getGroupId(), dossier.getDossierId(), user.getUserId(), processStepRole.getModerator() ? 1 : 0, true); } else { try { if ((processStepRole.getModerator() && du.getModerator() != DossierActionUserTerm.ASSIGNED_PH) || (!processStepRole.getModerator() && du.getModerator() != DossierActionUserTerm.ASSIGNED_PH)) { dossierUserLocalService.updateDossierUser(dossier.getDossierId(), user.getUserId(), du.getModerator() == 0 ? (processStepRole.getModerator() ? 1 : 0) : 1, true); } } catch (NoSuchDossierUserException e) { _log.error(e); } } } private void initDossierActionUserByServiceProcessRole(Dossier dossier, int allowAssignUser, DossierAction dossierAction, long userId, long groupId, long assignUserId) { try { ServiceProcess serviceProcess = serviceProcessLocalService.getServiceByCode(groupId, dossier.getServiceCode(), dossier.getGovAgencyCode(), dossier.getDossierTemplateNo()); List<ServiceProcessRole> listSprs = serviceProcessRoleLocalService.findByS_P_ID(serviceProcess.getServiceProcessId()); DossierAction da = dossierAction; for (ServiceProcessRole spr : listSprs) { int mod = 0; boolean moderator = spr.getModerator(); if (moderator) { mod = 1; } List<User> users = UserLocalServiceUtil.getRoleUsers(spr.getRoleId()); for (User user : users) { int assigned = user.getUserId() == assignUserId ? allowAssignUser : ProcessActionTerm.NOT_ASSIGNED; org.opencps.dossiermgt.model.DossierActionUser dau = dossierActionUserLocalService.getByDossierAndUser(dossierAction.getDossierActionId(), user.getUserId()); if (dau != null) { dau.setModerator(mod); if (moderator) { dau.setAssigned(1); } else { dau.setAssigned(assigned); } dossierActionUserLocalService.updateDossierActionUser(dau); } else { addDossierActionUserByAssigned(allowAssignUser, user.getUserId(), dossierAction.getDossierActionId(), mod, false, da.getStepCode(), dossier.getDossierId()); } } } } catch (PortalException e) { _log.error(e); } } private void copyRoleAsStep(ProcessStep curStep, Dossier dossier) { if (Validator.isNull(curStep.getRoleAsStep())) return; String[] stepCodeArr = StringUtil.split(curStep.getRoleAsStep()); if (stepCodeArr.length > 0) { for (String stepCode : stepCodeArr) { if (stepCode.startsWith("!")) { int index = stepCode.indexOf("!"); String stepCodePunc = stepCode.substring(index + 1); List<org.opencps.dossiermgt.model.DossierActionUser> lstDaus = dossierActionUserLocalService.getByDossierAndStepCode(dossier.getDossierId(), stepCodePunc); List<DossierAction> lstDossierActions = dossierActionLocalService.findDossierActionByDID_STEP(dossier.getDossierId(), stepCodePunc); try { for (org.opencps.dossiermgt.model.DossierActionUser dau : lstDaus) { boolean flagDA = false; for (DossierAction da : lstDossierActions) { if (da.getUserId() == dau.getUserId()) { flagDA = true; break; } } if (flagDA) { DossierUserPK duPk = new DossierUserPK(); duPk.setDossierId(dossier.getDossierId()); duPk.setUserId(dau.getUserId()); int moderator = dau.getModerator(); DossierUser duModel = dossierUserLocalService.fetchDossierUser(duPk); if (duModel == null) { dossierUserLocalService.addDossierUser(dossier.getGroupId(), dossier.getDossierId(), dau.getUserId(), moderator, true); } else { try { if (duModel.getModerator() == 0 && moderator == 1) { dossierUserLocalService.updateDossierUser(dossier.getDossierId(), dau.getUserId(), moderator, true); } } catch (NoSuchDossierUserException e) { // e.printStackTrace(); _log.error(e); } } DossierActionUserPK dauPk = new DossierActionUserPK(); dauPk.setDossierActionId(dossier.getDossierActionId()); dauPk.setUserId(dau.getUserId()); int assigned = moderator == 1 ? 1 : 0; dossierActionUserLocalService.addOrUpdateDossierActionUser(dau.getUserId(), dossier.getGroupId(), dossier.getDossierActionId(), dossier.getDossierId(), curStep.getStepCode(), moderator, assigned, true); } } } catch (Exception e) { _log.error(e); } } else { ServiceProcess serviceProcess = null; try { serviceProcess = serviceProcessLocalService.getServiceByCode(dossier.getGroupId(), dossier.getServiceCode(), dossier.getGovAgencyCode(), dossier.getDossierTemplateNo()); if (serviceProcess != null) { ProcessStep processStep = processStepLocalService.fetchBySC_GID(stepCode, dossier.getGroupId(), serviceProcess.getServiceProcessId()); if (processStep == null) continue; List<ProcessStepRole> lstRoles = processStepRoleLocalService.findByP_S_ID(processStep.getProcessStepId()); for (ProcessStepRole psr : lstRoles) { List<User> users = UserLocalServiceUtil.getRoleUsers(psr.getRoleId()); for (User u : users) { DossierUserPK duPk = new DossierUserPK(); duPk.setDossierId(dossier.getDossierId()); duPk.setUserId(u.getUserId()); int moderator = (psr.getModerator() ? 1 : 0); DossierUser duModel = dossierUserLocalService.fetchDossierUser(duPk); if (duModel == null) { dossierUserLocalService.addDossierUser(dossier.getGroupId(), dossier.getDossierId(), u.getUserId(), moderator, true); } else { try { if (duModel.getModerator() == 0 && moderator == 1) { dossierUserLocalService.updateDossierUser(dossier.getDossierId(), u.getUserId(), moderator, true); } } catch (NoSuchDossierUserException e) { _log.error(e); } } DossierActionUserPK dauPk = new DossierActionUserPK(); dauPk.setDossierActionId(dossier.getDossierActionId()); dauPk.setUserId(u.getUserId()); int assigned = moderator == 1 ? 1 : 0; dossierActionUserLocalService.addOrUpdateDossierActionUser(u.getUserId(), dossier.getGroupId(), dossier.getDossierActionId(), dossier.getDossierId(), curStep.getStepCode(), moderator, assigned, true); } } } } catch (PortalException e) { _log.error(e); } } } } } @Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class }) public Dossier addDossier(long groupId, Company company, User user, ServiceContext serviceContext, DossierInputModel input) throws UnauthenticationException, PortalException, Exception { BackendAuth auth = new BackendAuthImpl(); DossierPermission dossierPermission = new DossierPermission(); long start = System.currentTimeMillis(); if (!auth.isAuth(serviceContext)) { throw new UnauthenticationException(); } ProcessOption option = getProcessOption(input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo(), groupId); long serviceProcessId = 0; if (option != null) { serviceProcessId = option.getServiceProcessId(); } boolean flag = false; long userId = serviceContext.getUserId(); Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userId); if (employee != null) { long employeeId = employee.getEmployeeId(); if (employeeId > 0) { List<EmployeeJobPos> empJobList = EmployeeJobPosLocalServiceUtil.findByF_EmployeeId(employeeId); if (empJobList != null && empJobList.size() > 0) { for (EmployeeJobPos employeeJobPos : empJobList) { long jobPosId = employeeJobPos.getJobPostId(); if (jobPosId > 0) { JobPos job = JobPosLocalServiceUtil.fetchJobPos(jobPosId); if (job != null) { ServiceProcessRolePK pk = new ServiceProcessRolePK(serviceProcessId, job.getMappingRoleId()); ServiceProcessRole role = serviceProcessRoleLocalService .fetchServiceProcessRole(pk); if (role != null && role.getModerator()) { flag = true; break; } } } } } } } else { flag = true; } if (!flag) { throw new UnauthenticationException("No permission create dossier"); } _log.debug("CREATE DOSSIER 1: " + (System.currentTimeMillis() - start) + " ms"); dossierPermission.hasCreateDossier(groupId, user.getUserId(), input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo()); //int counter = DossierNumberGenerator.counterDossier(user.getUserId(), groupId); String referenceUid = input.getReferenceUid(); int counter = 0; // Create dossierNote ServiceProcess process = null; boolean online = GetterUtil.getBoolean(input.getOnline()); int originality = GetterUtil.getInteger(input.getOriginality()); Integer viaPostal = input.getViaPostal(); ServiceConfig config = serviceConfigLocalService.getBySICodeAndGAC(groupId, input.getServiceCode(), input.getGovAgencyCode()); if (config != null && Validator.isNotNull(viaPostal)) { viaPostal = config.getPostService() ? (viaPostal == 0 ? 1 : viaPostal) : 0; } else if (config != null) { viaPostal = config.getPostService() ? 1 : 0; } if (option != null) { process = serviceProcessLocalService.getServiceProcess(serviceProcessId); } if (process == null) { throw new NotFoundException("Cant find process"); } if (Validator.isNull(referenceUid) || referenceUid.trim().length() == 0) referenceUid = DossierNumberGenerator.generateReferenceUID(groupId); //Dossier checkDossier = dossierLocalService.getByRef(groupId, referenceUid); //if (checkDossier != null) { // return checkDossier; //} ServiceInfo service = serviceInfoLocalService.getByCode(groupId, input.getServiceCode()); String serviceName = StringPool.BLANK; if (service != null) { serviceName = service.getServiceName(); } String govAgencyName = getDictItemName(groupId, GOVERNMENT_AGENCY, input.getGovAgencyCode()); DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(ADMINISTRATIVE_REGION, groupId); String cityName = getDictItemName(groupId, dc, input.getCityCode()); String districtName = getDictItemName(groupId, dc, input.getDistrictCode()); String wardName = getDictItemName(groupId, dc, input.getWardCode()); // _log.info("Service code: " + input.getServiceCode()); _log.debug("===ADD DOSSIER CITY NAME:" + cityName); String password = StringPool.BLANK; if (Validator.isNotNull(input.getPassword())) { password = input.getPassword(); } else if (Validator.isNotNull(process.getGeneratePassword()) && process.getGeneratePassword()) { password = PwdGenerator.getPinNumber(); } String postalCityName = StringPool.BLANK; if (Validator.isNotNull(input.getPostalCityCode())) { postalCityName = getDictItemName(groupId, VNPOST_CITY_CODE, input.getPostalCityCode()); } Long sampleCount = (option != null ? option.getSampleCount() : 1l); // Process group dossier if (originality == 9) { _log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms"); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"); Date appIdDate = null; try { appIdDate = sdf.parse(input.getApplicantIdDate()); } catch (Exception e) { _log.debug(e); } Dossier dossier = dossierLocalService.initDossier(groupId, 0l, referenceUid, counter, input.getServiceCode(), serviceName, input.getGovAgencyCode(), govAgencyName, input.getApplicantName(), input.getApplicantIdType(), input.getApplicantIdNo(), appIdDate, input.getAddress(), input.getCityCode(), cityName, input.getDistrictCode(), districtName, input.getWardCode(), wardName, input.getContactName(), input.getContactTelNo(), input.getContactEmail(), input.getDossierTemplateNo(), password, viaPostal, input.getPostalAddress(), input.getPostalCityCode(), postalCityName, input.getPostalTelNo(), online, process.getDirectNotification(), input.getApplicantNote(), Integer.valueOf(input.getOriginality()), service, process, option, serviceContext); if (Validator.isNotNull(input.getDossierName())) { dossier.setDossierName(input.getDossierName()); } else { dossier.setDossierName(serviceName); } dossier.setSampleCount(sampleCount); if (Validator.isNotNull(input.getMetaData())) dossier.setMetaData(input.getMetaData()); updateDelegateApplicant(dossier, input); // Process update dossierNo // LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>(); // params.put(DossierTerm.GOV_AGENCY_CODE, dossier.getGovAgencyCode()); // params.put(DossierTerm.SERVICE_CODE, dossier.getServiceCode()); // params.put(DossierTerm.DOSSIER_TEMPLATE_NO, dossier.getDossierTemplateNo()); // params.put(DossierTerm.DOSSIER_STATUS, StringPool.BLANK); if (option != null) { //Process submition note dossier.setSubmissionNote(option.getSubmissionNote()); // String dossierRef = DossierNumberGenerator.generateDossierNumber(groupId, dossier.getCompanyId(), // dossier.getDossierId(), option.getProcessOptionId(), process.getDossierGroupPattern(), params); // dossier.setDossierNo(dossierRef.trim()); } dossier.setViaPostal(1); _log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms"); if (Validator.isNull(dossier)) { throw new NotFoundException("Can't add DOSSIER"); } _log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms"); //Create DossierMark _log.debug("originality: "+originality); String templateNo = dossier.getDossierTemplateNo(); _log.debug("templateNo: "+templateNo); if (Validator.isNotNull(input.getDossierMarkArr())) { JSONArray markArr = JSONFactoryUtil.createJSONArray(input.getDossierMarkArr()); if (markArr != null && markArr.length() > 0) { List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId()); Map<String, DossierMark> mapMarks = new HashMap<>(); for (DossierMark dm : lstMarks) { mapMarks.put(dm.getDossierPartNo(), dm); } for (int i = 0; i < markArr.length(); i++) { JSONObject jsonMark = markArr.getJSONObject(i); org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[markArr.length()]; org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel(); model.setDossierId(dossier.getDossierId()); model.setDossierPartNo(jsonMark.getString("partNo")); model.setFileCheck(0); model.setFileMark(jsonMark.getInt("fileMark")); model.setFileComment(StringPool.BLANK); model.setRecordCount(StringPool.BLANK); marks[i] = model; dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext); } } } else if (Validator.isNotNull(templateNo)) { List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo); // _log.info("partList: "+partList); if (partList != null && partList.size() > 0) { _log.debug("partList.size(): "+partList.size()); _log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms"); org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()]; int count = 0; List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId()); Map<String, DossierMark> mapMarks = new HashMap<>(); for (DossierMark dm : lstMarks) { mapMarks.put(dm.getDossierPartNo(), dm); } for (DossierPart dossierPart : partList) { int fileMark = dossierPart.getFileMark(); String dossierPartNo = dossierPart.getPartNo(); org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel(); model.setDossierId(dossier.getDossierId()); model.setDossierPartNo(dossierPartNo); model.setFileCheck(0); model.setFileMark(fileMark); model.setFileComment(StringPool.BLANK); model.setRecordCount(StringPool.BLANK); marks[count++] = model; } dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext); _log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms"); } } //Create dossier user List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId()); List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId()); if (lstDus.size() == 0) { DossierUserActions duActions = new DossierUserActionsImpl(); duActions.initDossierUser(groupId, dossier, process, lstProcessRoles); } // if (originality == DossierTerm.ORIGINALITY_DVCTT) { // dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true); // } _log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms"); //Add to dossier user based on service process role createDossierUsers(groupId, dossier, process, lstProcessRoles); if (Validator.isNotNull(input.getServerNo())) { dossier.setServerNo(input.getServerNo()); } _log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms"); return dossierLocalService.updateDossier(dossier); } else { List<Dossier> oldDossiers = dossierLocalService.getByU_G_GAC_SC_DTNO_DS_O( userId, groupId, input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo(), StringPool.BLANK, Integer.valueOf(input.getOriginality())); Dossier dossier = null; Dossier oldRefDossier = Validator.isNotNull(input.getReferenceUid()) ? dossierLocalService.getByRef(groupId, input.getReferenceUid()) : null; if (originality == DossierTerm.ORIGINALITY_DVCTT) { online = true; } boolean flagOldDossier = false; String registerBookCode = (option != null ? (Validator.isNotNull(option.getRegisterBookCode()) ? option.getRegisterBookCode() : StringPool.BLANK) : StringPool.BLANK); String registerBookName = (Validator.isNotNull(registerBookCode) ? getDictItemName(groupId, REGISTER_BOOK, registerBookCode) : StringPool.BLANK); _log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms"); if (oldRefDossier != null) { dossier = oldRefDossier; dossier.setSubmitDate(new Date()); ServiceProcess serviceProcess = process; double durationCount = 0; int durationUnit = 0; if (serviceProcess != null ) { durationCount = serviceProcess.getDurationCount(); durationUnit = serviceProcess.getDurationUnit(); dossier.setDurationCount(durationCount); dossier.setDurationUnit(durationUnit); } if (durationCount > 0) { Date dueDate = HolidayUtils.getDueDate(new Date(), durationCount, durationUnit, groupId); dossier.setDueDate(dueDate); } } else if (oldDossiers.size() > 0) { flagOldDossier = true; dossier = oldDossiers.get(0); dossier.setApplicantName(input.getApplicantName()); dossier.setApplicantNote(input.getApplicantNote()); dossier.setApplicantIdNo(input.getApplicantIdNo()); dossier.setAddress(input.getAddress()); dossier.setContactEmail(input.getContactEmail()); dossier.setContactName(input.getContactName()); dossier.setContactTelNo(input.getContactTelNo()); dossier.setDelegateName(input.getDelegateName()); dossier.setDelegateEmail(input.getDelegateEmail()); dossier.setDelegateAddress(input.getDelegateAddress()); dossier.setPostalAddress(input.getPostalAddress()); dossier.setPostalCityCode(input.getPostalCityCode()); dossier.setPostalCityName(postalCityName); dossier.setPostalTelNo(input.getPostalTelNo()); dossier.setPostalServiceCode(input.getPostalServiceCode()); dossier.setPostalServiceName(input.getPostalServiceName()); dossier.setPostalDistrictCode(input.getPostalDistrictCode()); dossier.setPostalDistrictName(input.getPostalDistrictName()); dossier.setPostalWardCode(input.getPostalWardCode()); dossier.setPostalWardName(input.getPostalWardName()); dossier.setPostalTelNo(input.getPostalTelNo()); dossier.setViaPostal(viaPostal); dossier.setOriginDossierNo(input.getOriginDossierNo()); dossier.setRegisterBookCode(registerBookCode); dossier.setRegisterBookName(registerBookName); dossier.setSampleCount(sampleCount); dossier.setServiceCode(input.getServiceCode()); dossier.setGovAgencyCode(input.getGovAgencyCode()); dossier.setDossierTemplateNo(input.getDossierTemplateNo()); updateDelegateApplicant(dossier, input); // dossier.setDossierNo(input.getDossierNo()); dossier.setSubmitDate(new Date()); // ServiceProcess serviceProcess = ServiceProcessLocalServiceUtil.fetchServiceProcess(serviceProcessId); ServiceProcess serviceProcess = process; double durationCount = 0; int durationUnit = 0; if (serviceProcess != null ) { durationCount = serviceProcess.getDurationCount(); durationUnit = serviceProcess.getDurationUnit(); dossier.setDurationCount(durationCount); dossier.setDurationUnit(durationUnit); } if (durationCount > 0) { Date dueDate = HolidayUtils.getDueDate(new Date(), durationCount, durationUnit, groupId); dossier.setDueDate(dueDate); } dossier.setOnline(online); if (Validator.isNotNull(input.getDossierName())) dossier.setDossierName(input.getDossierName()); if (serviceProcess != null) { dossier.setProcessNo(serviceProcess.getProcessNo()); } // dossier = DossierLocalServiceUtil.updateDossier(dossier); } else { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Date appIdDate = null; try { appIdDate = sdf.parse(input.getApplicantIdDate()); } catch (Exception e) { _log.debug(e); } dossier = dossierLocalService.initDossier(groupId, 0l, referenceUid, counter, input.getServiceCode(), serviceName, input.getGovAgencyCode(), govAgencyName, input.getApplicantName(), input.getApplicantIdType(), input.getApplicantIdNo(), appIdDate, input.getAddress(), input.getCityCode(), cityName, input.getDistrictCode(), districtName, input.getWardCode(), wardName, input.getContactName(), input.getContactTelNo(), input.getContactEmail(), input.getDossierTemplateNo(), password, viaPostal, input.getPostalAddress(), input.getPostalCityCode(), postalCityName, input.getPostalTelNo(), online, process.getDirectNotification(), input.getApplicantNote(), Integer.valueOf(input.getOriginality()), service, process, option, serviceContext); dossier.setDelegateName(input.getDelegateName()); dossier.setDelegateEmail(input.getDelegateEmail()); dossier.setDelegateAddress(input.getDelegateAddress()); if (Validator.isNotNull(input.getDossierName())) { dossier.setDossierName(input.getDossierName()); } else { dossier.setDossierName(serviceName); } dossier.setPostalCityName(postalCityName); dossier.setPostalTelNo(input.getPostalTelNo()); dossier.setPostalServiceCode(input.getPostalServiceCode()); dossier.setPostalServiceName(input.getPostalServiceName()); dossier.setPostalDistrictCode(input.getPostalDistrictCode()); dossier.setPostalDistrictName(input.getPostalDistrictName()); dossier.setPostalWardCode(input.getPostalWardCode()); dossier.setPostalWardName(input.getPostalWardName()); dossier.setOriginDossierNo(input.getOriginDossierNo()); dossier.setRegisterBookCode(registerBookCode); dossier.setRegisterBookName(registerBookName); dossier.setSampleCount(sampleCount); if (Validator.isNotNull(input.getMetaData())) dossier.setMetaData(input.getMetaData()); updateDelegateApplicant(dossier, input); if (process != null) { dossier.setProcessNo(process.getProcessNo()); } // dossier = DossierLocalServiceUtil.updateDossier(dossier); } _log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms"); if (originality != DossierTerm.ORIGINALITY_LIENTHONG) { Applicant applicant = ApplicantLocalServiceUtil.fetchByMappingID(serviceContext.getUserId()); if (applicant != null) { updateApplicantInfo(dossier, applicant.getApplicantIdDate(), applicant.getApplicantIdNo(), applicant.getApplicantIdType(), applicant.getApplicantName(), applicant.getAddress(), applicant.getCityCode(), applicant.getCityName(), applicant.getDistrictCode(), applicant.getDistrictName(), applicant.getWardCode(), applicant.getWardName(), applicant.getContactEmail(), applicant.getContactTelNo() ); } } if (Validator.isNull(dossier)) { throw new NotFoundException("Cant add DOSSIER"); } _log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms"); //Create DossierMark _log.debug("flagOldDossier: "+flagOldDossier); _log.debug("originality: "+originality); if ((originality == DossierTerm.ORIGINALITY_MOTCUA || originality == DossierTerm.ORIGINALITY_LIENTHONG) && !flagOldDossier) { String templateNo = dossier.getDossierTemplateNo(); _log.debug("templateNo: "+templateNo); if (Validator.isNotNull(templateNo)) { List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo); // _log.info("partList: "+partList); if (partList != null && partList.size() > 0) { _log.debug("partList.size(): "+partList.size()); _log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms"); org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()]; int count = 0; List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId()); Map<String, DossierMark> mapMarks = new HashMap<>(); for (DossierMark dm : lstMarks) { mapMarks.put(dm.getDossierPartNo(), dm); } for (DossierPart dossierPart : partList) { int fileMark = dossierPart.getFileMark(); String dossierPartNo = dossierPart.getPartNo(); org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel(); model.setDossierId(dossier.getDossierId()); model.setDossierPartNo(dossierPartNo); model.setFileCheck(0); model.setFileMark(fileMark); model.setFileComment(StringPool.BLANK); marks[count++] = model; // DossierMarkLocalServiceUtil.addDossierMark(groupId, dossier.getDossierId(), dossierPartNo, // fileMark, 0, StringPool.BLANK, serviceContext); } dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext); _log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms"); } } } //Create dossier user List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId()); List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId()); if (lstDus.size() == 0) { DossierUserActions duActions = new DossierUserActionsImpl(); // duActions.initDossierUser(groupId, dossier); duActions.initDossierUser(groupId, dossier, process, lstProcessRoles); } if (originality == DossierTerm.ORIGINALITY_DVCTT) { dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true); } _log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms"); // DossierLocalServiceUtil.updateDossier(dossier); if (dossier != null) { // long notificationQueueId = CounterLocalServiceUtil.increment(NotificationQueue.class.getName()); NotificationQueue queue = NotificationQueueLocalServiceUtil.createNotificationQueue(notificationQueueId); //Process add notification queue Date now = new Date(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) + 1); queue.setCreateDate(now); queue.setModifiedDate(now); queue.setGroupId(groupId); queue.setCompanyId(company.getCompanyId()); queue.setNotificationType(NotificationType.DOSSIER_01); queue.setClassName(Dossier.class.getName()); queue.setClassPK(String.valueOf(dossier.getPrimaryKey())); queue.setToUsername(dossier.getUserName()); queue.setToUserId(dossier.getUserId()); queue.setToEmail(dossier.getContactEmail()); queue.setToTelNo(dossier.getContactTelNo()); JSONObject payload = JSONFactoryUtil.createJSONObject(); try { // _log.info("START PAYLOAD: "); payload.put( "Dossier", JSONFactoryUtil.createJSONObject( JSONFactoryUtil.looseSerialize(dossier))); } catch (JSONException parse) { _log.error(parse); } // _log.info("payloadTest: "+payload.toJSONString()); queue.setPayload(payload.toJSONString()); queue.setExpireDate(cal.getTime()); NotificationQueueLocalServiceUtil.addNotificationQueue(queue); } _log.debug("CREATE DOSSIER 6: " + (System.currentTimeMillis() - start) + " ms"); //Add to dossier user based on service process role createDossierUsers(groupId, dossier, process, lstProcessRoles); if (Validator.isNotNull(input.getServerNo())) { dossier.setServerNo(input.getServerNo()); } _log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms"); dossierLocalService.updateDossier(dossier); _log.debug("CREATE DOSSIER 8: " + (System.currentTimeMillis() - start) + " ms"); return dossier; } } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = { SystemException.class, PortalException.class, Exception.class }) public Dossier addMultipleDossier(long groupId, Company company, User user, ServiceContext serviceContext, DossierMultipleInputModel input) throws UnauthenticationException, PortalException, Exception { BackendAuth auth = new BackendAuthImpl(); DossierPermission dossierPermission = new DossierPermission(); long start = System.currentTimeMillis(); if (!auth.isAuth(serviceContext)) { throw new UnauthenticationException(); } ProcessOption option = getProcessOption(input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo(), groupId); long serviceProcessId = 0; if (option != null) { serviceProcessId = option.getServiceProcessId(); } boolean flag = false; long userId = serviceContext.getUserId(); Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userId); if (employee != null) { long employeeId = employee.getEmployeeId(); if (employeeId > 0) { List<EmployeeJobPos> empJobList = EmployeeJobPosLocalServiceUtil.findByF_EmployeeId(employeeId); if (empJobList != null && empJobList.size() > 0) { for (EmployeeJobPos employeeJobPos : empJobList) { long jobPosId = employeeJobPos.getJobPostId(); if (jobPosId > 0) { JobPos job = JobPosLocalServiceUtil.fetchJobPos(jobPosId); if (job != null) { ServiceProcessRolePK pk = new ServiceProcessRolePK(serviceProcessId, job.getMappingRoleId()); ServiceProcessRole role = serviceProcessRoleLocalService .fetchServiceProcessRole(pk); if (role != null && role.getModerator()) { flag = true; break; } } } } } } } else { flag = true; } if (!flag) { throw new UnauthenticationException("No permission create dossier"); } _log.debug("CREATE DOSSIER 1: " + (System.currentTimeMillis() - start) + " ms"); dossierPermission.hasCreateDossier(groupId, user.getUserId(), input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo()); Dossier dossier = null; if (Validator.isNotNull(input.getDossiers())) { JSONObject jsonDossier = JSONFactoryUtil.createJSONObject(input.getDossiers()); //Get params input dossier String referenceUid = jsonDossier.getString(DossierTerm.REFERENCE_UID); if (Validator.isNull(referenceUid) || referenceUid.trim().length() == 0) referenceUid = DossierNumberGenerator.generateReferenceUID(groupId); int counter = 0; //boolean online = GetterUtil.getBoolean(input.getOnline()); boolean online = false; int originality = input.getOriginality(); int viaPostal = Validator.isNotNull(jsonDossier.getString(DossierTerm.VIA_POSTAL)) ? GetterUtil.getInteger(jsonDossier.getString(DossierTerm.VIA_POSTAL)): 0; ServiceConfig config = serviceConfigLocalService.getBySICodeAndGAC(groupId, input.getServiceCode(), input.getGovAgencyCode()); if (config != null && Validator.isNotNull(viaPostal)) { viaPostal = config.getPostService() ? (viaPostal == 0 ? 1 : viaPostal) : 0; } else if (config != null) { viaPostal = config.getPostService() ? 1 : 0; } //Get service process ServiceProcess process = null; if (option != null) { process = serviceProcessLocalService.getServiceProcess(serviceProcessId); if (process == null) { throw new NotFoundException("Cant find process"); } } ServiceInfo service = serviceInfoLocalService.getByCode(groupId, input.getServiceCode()); String serviceName = service != null ? service.getServiceName(): StringPool.BLANK; String govAgencyName = getDictItemName(groupId, GOVERNMENT_AGENCY, input.getGovAgencyCode()); //DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(ADMINISTRATIVE_REGION, groupId); //String cityName = getDictItemName(groupId, dc, input.getCityCode()); //String districtName = getDictItemName(groupId, dc, input.getDistrictCode()); //String wardName = getDictItemName(groupId, dc, input.getWardCode()); // _log.info("Service code: " + input.getServiceCode()); //_log.debug("===ADD DOSSIER CITY NAME:" + cityName); String password = StringPool.BLANK; if (Validator.isNotNull(jsonDossier.getString("password"))) { password = jsonDossier.getString("password"); } else if (Validator.isNotNull(process.getGeneratePassword()) && process.getGeneratePassword()) { password = PwdGenerator.getPinNumber(); } String postalCityName = StringPool.BLANK; if (Validator.isNotNull(jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE))) { postalCityName = getDictItemName(groupId, VNPOST_CITY_CODE, jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE)); } int sampleCount = (option != null ? (int) option.getSampleCount() : 1); String registerBookCode = (option != null ? (Validator.isNotNull(option.getRegisterBookCode()) ? option.getRegisterBookCode() : StringPool.BLANK) : StringPool.BLANK); String registerBookName = (Validator.isNotNull(registerBookCode) ? getDictItemName(groupId, REGISTER_BOOK, registerBookCode) : StringPool.BLANK); _log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms"); Long appIdDateLong = jsonDossier.getLong(DossierTerm.APPLICANT_ID_DATE); Date appIdDate = null; if (appIdDateLong > 0) { appIdDate = new Date(appIdDateLong); } // Params add dossier String applicantName = jsonDossier.getString(DossierTerm.APPLICANT_NAME); String applicantIdType = jsonDossier.getString(DossierTerm.APPLICANT_ID_TYPE); String applicantIdNo = jsonDossier.getString(DossierTerm.APPLICANT_ID_NO); String address = jsonDossier.getString(DossierTerm.ADDRESS); String contactName = jsonDossier.getString(DossierTerm.CONTACT_NAME); String contactTelNo = jsonDossier.getString(DossierTerm.CONTACT_TEL_NO); String contactEmail = jsonDossier.getString(DossierTerm.CONTACT_EMAIL); // String postalServiceCode = jsonDossier.getString(DossierTerm.POSTAL_SERVICE_CODE); String postalServiceName = jsonDossier.getString(DossierTerm.POSTAL_SERVICE_NAME); String postalAddress = jsonDossier.getString(DossierTerm.POSTAL_ADDRESS); String postalCityCode = jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE); String postalDistrictCode = jsonDossier.getString(DossierTerm.POSTAL_DISTRICT_CODE); String postalDistrictName = jsonDossier.getString(DossierTerm.POSTAL_DISTRICT_NAME); String postalWardCode = jsonDossier.getString(DossierTerm.POSTAL_WARD_CODE); String postalWardName = jsonDossier.getString(DossierTerm.POSTAL_WARD_NAME); String postalTelNo = jsonDossier.getString(DossierTerm.POSTAL_TEL_NO); String applicantNote = jsonDossier.getString(DossierTerm.APPLICANT_NOTE); String delegateIdNo = jsonDossier.getString(DossierTerm.DELEGATE_ID_NO); String delegateName = jsonDossier.getString(DossierTerm.DELEGATE_NAME); String delegateTelNo = jsonDossier.getString(DossierTerm.DELEGATE_TELNO); String delegateEmail = jsonDossier.getString(DossierTerm.DELEGATE_EMAIL); String delegateAddress = jsonDossier.getString(DossierTerm.DELEGATE_ADDRESS); //TODO String delegateCityCode = jsonDossier.getString(DossierTerm.DELEGATE_CITYCODE); String delegateCityName = StringPool.BLANK; if (Validator.isNotNull(delegateCityCode)) { delegateCityName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateCityCode); } String delegateDistrictCode = jsonDossier.getString(DossierTerm.DELEGATE_DISTRICTCODE); String delegateDistrictName = StringPool.BLANK; if (Validator.isNotNull(delegateDistrictCode)) { delegateDistrictName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateDistrictCode); } String delegateWardCode = jsonDossier.getString(DossierTerm.DELEGATE_WARDCODE); String delegateWardName = StringPool.BLANK; if (Validator.isNotNull(delegateWardCode)) { delegateWardName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateWardCode); } // String dossierName = Validator.isNotNull(jsonDossier.getString(DossierTerm.DOSSIER_NAME)) ? jsonDossier.getString(DossierTerm.DOSSIER_NAME) : serviceName; Long receiveDateTimeStamp = jsonDossier.getLong(DossierTerm.RECEIVE_DATE); Date receiveDate = null; if (receiveDateTimeStamp > 0) { receiveDate = new Date(receiveDateTimeStamp); } Long dueDateTimeStamp = jsonDossier.getLong(DossierTerm.DUE_DATE); Date dueDate = null; if (dueDateTimeStamp > 0) { dueDate = new Date(dueDateTimeStamp); } String metaData = jsonDossier.getString(DossierTerm.META_DATA); dossier = dossierLocalService.initMultipleDossier(groupId, 0l, referenceUid, counter, input.getServiceCode(), serviceName, input.getGovAgencyCode(), govAgencyName, applicantName, applicantIdType, applicantIdNo, appIdDate, address, contactName, contactTelNo, contactEmail, input.getDossierTemplateNo(), password, viaPostal, postalServiceCode, postalServiceName, postalAddress, postalCityCode, postalCityName, postalDistrictCode, postalDistrictName, postalWardCode, postalWardName, postalTelNo, online, process.getDirectNotification(), applicantNote, input.getOriginality(), delegateIdNo, delegateName, delegateTelNo, delegateEmail, delegateAddress, delegateCityCode, delegateCityName, delegateDistrictCode, delegateDistrictName, delegateWardCode, delegateWardName, registerBookCode, registerBookName, sampleCount, dossierName, service, process, option, serviceContext); if (receiveDate != null) dossier.setReceiveDate(receiveDate); if (dueDate != null) dossier.setDueDate(dueDate); if (Validator.isNotNull(metaData)) dossier.setMetaData(metaData); //TODO: Process then //updateDelegateApplicant(dossier, input); _log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms"); if (originality != DossierTerm.ORIGINALITY_LIENTHONG) { Applicant applicant = ApplicantLocalServiceUtil.fetchByMappingID(serviceContext.getUserId()); if (applicant != null) { updateApplicantInfo(dossier, applicant.getApplicantIdDate(), applicant.getApplicantIdNo(), applicant.getApplicantIdType(), applicant.getApplicantName(), applicant.getAddress(), applicant.getCityCode(), applicant.getCityName(), applicant.getDistrictCode(), applicant.getDistrictName(), applicant.getWardCode(), applicant.getWardName(), applicant.getContactEmail(), applicant.getContactTelNo() ); } } if (Validator.isNull(dossier)) { throw new NotFoundException("Cant add DOSSIER"); } _log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms"); //TODO /** Create DossierMark */ //_log.debug("flagOldDossier: "+flagOldDossier); _log.debug("originality: "+originality); String templateNo = dossier.getDossierTemplateNo(); _log.debug("templateNo: "+templateNo); long dossierId = dossier.getDossierId(); if (originality == DossierTerm.ORIGINALITY_MOTCUA || originality == DossierTerm.ORIGINALITY_LIENTHONG) { if (Validator.isNotNull(input.getDossierMarkArr())) { JSONArray markArr = JSONFactoryUtil.createJSONArray(input.getDossierMarkArr()); if (markArr != null && markArr.length() > 0) { List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossierId); Map<String, DossierMark> mapMarks = new HashMap<>(); for (DossierMark dm : lstMarks) { mapMarks.put(dm.getDossierPartNo(), dm); } org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[markArr.length()]; for (int i = 0; i < markArr.length(); i++) { JSONObject jsonMark = markArr.getJSONObject(i); //System.out.println("jsonMark: "+jsonMark); org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel(); model.setDossierId(dossier.getDossierId()); model.setDossierPartNo(jsonMark.getString("partNo")); model.setFileCheck(0); model.setFileMark(jsonMark.getInt("fileMark")); model.setFileComment(StringPool.BLANK); model.setRecordCount(StringPool.BLANK); marks[i] = model; } dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext); } } else if (Validator.isNotNull(templateNo)) { List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo); // _log.info("partList: "+partList); if (partList != null && partList.size() > 0) { _log.debug("partList.size(): "+partList.size()); _log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms"); org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()]; int count = 0; List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossierId); Map<String, DossierMark> mapMarks = new HashMap<>(); for (DossierMark dm : lstMarks) { mapMarks.put(dm.getDossierPartNo(), dm); } for (DossierPart dossierPart : partList) { int fileMark = dossierPart.getFileMark(); String dossierPartNo = dossierPart.getPartNo(); org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel(); model.setDossierId(dossier.getDossierId()); model.setDossierPartNo(dossierPartNo); model.setFileCheck(0); model.setFileMark(fileMark); model.setFileComment(StringPool.BLANK); model.setRecordCount(StringPool.BLANK); marks[count++] = model; } dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext); _log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms"); } } } /** * Add dossier file */ String strDossierFileId = input.getDossierFileArr(); if (Validator.isNotNull(strDossierFileId)) { String[] splitDossierFileId = strDossierFileId.split(StringPool.COMMA); if (splitDossierFileId != null && splitDossierFileId.length > 0) { for (String strFileId : splitDossierFileId) { processCloneDossierFile(Long.valueOf(strFileId), dossier.getDossierId(), userId); } } } /**Create dossier user */ List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId()); List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId()); if (lstDus.size() == 0) { DossierUserActions duActions = new DossierUserActionsImpl(); duActions.initDossierUser(groupId, dossier, process, lstProcessRoles); } if (originality == DossierTerm.ORIGINALITY_DVCTT) { dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true); } _log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms"); // if (dossier != null) { // // // long notificationQueueId = CounterLocalServiceUtil.increment(NotificationQueue.class.getName()); // // NotificationQueue queue = NotificationQueueLocalServiceUtil.createNotificationQueue(notificationQueueId); // //Process add notification queue // Date now = new Date(); // // Calendar cal = Calendar.getInstance(); // cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) + 1); // // queue.setCreateDate(now); // queue.setModifiedDate(now); // queue.setGroupId(groupId); // queue.setCompanyId(company.getCompanyId()); // // queue.setNotificationType(NotificationType.DOSSIER_01); // queue.setClassName(Dossier.class.getName()); // queue.setClassPK(String.valueOf(dossier.getPrimaryKey())); // queue.setToUsername(dossier.getUserName()); // queue.setToUserId(dossier.getUserId()); // queue.setToEmail(dossier.getContactEmail()); // queue.setToTelNo(dossier.getContactTelNo()); // // JSONObject payload = JSONFactoryUtil.createJSONObject(); // try { //// _log.info("START PAYLOAD: "); // payload.put( // "Dossier", JSONFactoryUtil.createJSONObject( // JSONFactoryUtil.looseSerialize(dossier))); // } // catch (JSONException parse) { // _log.error(parse); // } //// _log.info("payloadTest: "+payload.toJSONString()); // queue.setPayload(payload.toJSONString()); // queue.setExpireDate(cal.getTime()); // // NotificationQueueLocalServiceUtil.addNotificationQueue(queue); // } _log.debug("CREATE DOSSIER 6: " + (System.currentTimeMillis() - start) + " ms"); //Add to dossier user based on service process role createDossierUsers(groupId, dossier, process, lstProcessRoles); _log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms"); dossierLocalService.updateDossier(dossier); _log.debug("CREATE DOSSIER 8: " + (System.currentTimeMillis() - start) + " ms"); String payload = StringPool.BLANK; String actionCode = "1100"; if (dossier.getReceiveDate() == null) { JSONObject jsonDate = JSONFactoryUtil.createJSONObject(); jsonDate.put(DossierTerm.RECEIVE_DATE, (new Date()).getTime()); Double durationCount = process.getDurationCount(); if (Validator.isNotNull(String.valueOf(durationCount)) && durationCount > 0d) { Date dueDateCal = HolidayUtils.getDueDate(new Date(), process.getDurationCount(), process.getDurationUnit(), groupId); jsonDate.put(DossierTerm.DUE_DATE, dueDateCal != null ? dueDateCal.getTime() : 0); } if (Validator.isNotNull(jsonDate)) { payload = jsonDate.toJSONString(); } } // ProcessAction proAction = getProcessAction(groupId, dossier, actionCode, serviceProcessId); doAction(groupId, userId, dossier, option, proAction, actionCode, StringPool.BLANK, StringPool.BLANK, payload, StringPool.BLANK, input.getPayment(), 0, serviceContext); } return dossier; } private void processCloneDossierFile(Long dossierFileId, long dossierId, long userId) throws PortalException { DossierFile dossierFileParent = dossierFileLocalService.fetchDossierFile(dossierFileId); if (dossierFileParent != null) { long dossierFileChildrenId = counterLocalService.increment(DossierFile.class.getName()); DossierFile object = dossierFilePersistence.create(dossierFileChildrenId); _log.debug("****End uploadFile file at:" + new Date()); Date now = new Date(); User userAction = null; if (userId != 0) { userAction = userLocalService.getUser(userId); } // Add audit fields object.setCompanyId(dossierFileParent.getCompanyId()); object.setGroupId(dossierFileParent.getGroupId()); object.setCreateDate(now); object.setModifiedDate(now); object.setUserId(userAction != null ? userAction.getUserId() : 0l); object.setUserName(userAction != null ? userAction.getFullName() : StringPool.BLANK); // Add other fields object.setDossierId(dossierId); object.setReferenceUid(PortalUUIDUtil.generate()); object.setDossierTemplateNo(dossierFileParent.getDossierTemplateNo()); object.setFileEntryId(dossierFileParent.getFileEntryId()); object.setDossierPartNo(dossierFileParent.getDossierPartNo()); object.setFileTemplateNo(dossierFileParent.getFileTemplateNo()); object.setDossierPartType(dossierFileParent.getDossierPartType()); _log.debug("****Start autofill file at:" + new Date()); object.setDisplayName(dossierFileParent.getDisplayName()); object.setOriginal(false); object.setIsNew(true); object.setFormData(dossierFileParent.getFormData()); object.setEForm(dossierFileParent.getEForm()); object.setRemoved(false); object.setSignCheck(dossierFileParent.getSignCheck()); object.setFormScript(dossierFileParent.getFormScript()); object.setFormReport(dossierFileParent.getFormReport()); object.setFormSchema(dossierFileParent.getFormSchema()); dossierFilePersistence.update(object); } } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = { SystemException.class, PortalException.class, Exception.class }) public Dossier addFullDossier(long groupId, Company company, User user, ServiceContext serviceContext, DossierMultipleInputModel input) throws UnauthenticationException, PortalException, Exception { BackendAuth auth = new BackendAuthImpl(); DossierPermission dossierPermission = new DossierPermission(); long start = System.currentTimeMillis(); if (!auth.isAuth(serviceContext)) { throw new UnauthenticationException(); } ProcessOption option = getProcessOption(input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo(), groupId); long serviceProcessId = 0; if (option != null) { serviceProcessId = option.getServiceProcessId(); } boolean flag = false; long userId = serviceContext.getUserId(); Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userId); if (employee != null) { long employeeId = employee.getEmployeeId(); if (employeeId > 0) { List<EmployeeJobPos> empJobList = EmployeeJobPosLocalServiceUtil.findByF_EmployeeId(employeeId); if (empJobList != null && empJobList.size() > 0) { for (EmployeeJobPos employeeJobPos : empJobList) { long jobPosId = employeeJobPos.getJobPostId(); if (jobPosId > 0) { JobPos job = JobPosLocalServiceUtil.fetchJobPos(jobPosId); if (job != null) { ServiceProcessRolePK pk = new ServiceProcessRolePK(serviceProcessId, job.getMappingRoleId()); ServiceProcessRole role = serviceProcessRoleLocalService .fetchServiceProcessRole(pk); if (role != null && role.getModerator()) { flag = true; break; } } } } } } } else { flag = true; } if (!flag) { throw new UnauthenticationException("No permission create dossier"); } _log.debug("CREATE DOSSIER 1: " + (System.currentTimeMillis() - start) + " ms"); dossierPermission.hasCreateDossier(groupId, user.getUserId(), input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo()); Dossier dossier = null; if (Validator.isNotNull(input.getDossiers())) { JSONObject jsonDossier = JSONFactoryUtil.createJSONObject(input.getDossiers()); //Get params input dossier String referenceUid = jsonDossier.getString(DossierTerm.REFERENCE_UID); if (Validator.isNull(referenceUid) || referenceUid.trim().length() == 0) referenceUid = DossierNumberGenerator.generateReferenceUID(groupId); int counter = 0; //boolean online = GetterUtil.getBoolean(input.getOnline()); boolean online = false; int originality = input.getOriginality(); int viaPostal = Validator.isNotNull(jsonDossier.getString(DossierTerm.VIA_POSTAL)) ? GetterUtil.getInteger(jsonDossier.getString(DossierTerm.VIA_POSTAL)): 0; ServiceConfig config = serviceConfigLocalService.getBySICodeAndGAC(groupId, input.getServiceCode(), input.getGovAgencyCode()); if (config != null && Validator.isNotNull(viaPostal)) { viaPostal = config.getPostService() ? (viaPostal == 0 ? 1 : viaPostal) : 0; } else if (config != null) { viaPostal = config.getPostService() ? 1 : 0; } //Get service process ServiceProcess process = null; if (option != null) { process = serviceProcessLocalService.getServiceProcess(serviceProcessId); if (process == null) { throw new NotFoundException("Cant find process"); } } ServiceInfo service = serviceInfoLocalService.getByCode(groupId, input.getServiceCode()); String serviceName = service != null ? service.getServiceName(): StringPool.BLANK; String govAgencyName = getDictItemName(groupId, GOVERNMENT_AGENCY, input.getGovAgencyCode()); //DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(ADMINISTRATIVE_REGION, groupId); //String cityName = getDictItemName(groupId, dc, input.getCityCode()); //String districtName = getDictItemName(groupId, dc, input.getDistrictCode()); //String wardName = getDictItemName(groupId, dc, input.getWardCode()); // _log.info("Service code: " + input.getServiceCode()); //_log.debug("===ADD DOSSIER CITY NAME:" + cityName); String password = StringPool.BLANK; if (Validator.isNotNull(jsonDossier.getString("password"))) { password = jsonDossier.getString("password"); } else if (Validator.isNotNull(process.getGeneratePassword()) && process.getGeneratePassword()) { password = PwdGenerator.getPinNumber(); } String postalCityName = StringPool.BLANK; if (Validator.isNotNull(jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE))) { postalCityName = getDictItemName(groupId, VNPOST_CITY_CODE, jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE)); } int sampleCount = (option != null ? (int) option.getSampleCount() : 1); String registerBookCode = (option != null ? (Validator.isNotNull(option.getRegisterBookCode()) ? option.getRegisterBookCode() : StringPool.BLANK) : StringPool.BLANK); String registerBookName = (Validator.isNotNull(registerBookCode) ? getDictItemName(groupId, REGISTER_BOOK, registerBookCode) : StringPool.BLANK); _log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms"); Long appIdDateLong = jsonDossier.getLong(DossierTerm.APPLICANT_ID_DATE); Date appIdDate = null; if (appIdDateLong > 0) { appIdDate = new Date(appIdDateLong); } // Params add dossier String applicantName = jsonDossier.getString(DossierTerm.APPLICANT_NAME); String applicantIdType = jsonDossier.getString(DossierTerm.APPLICANT_ID_TYPE); String applicantIdNo = jsonDossier.getString(DossierTerm.APPLICANT_ID_NO); String address = jsonDossier.getString(DossierTerm.ADDRESS); String contactName = jsonDossier.getString(DossierTerm.CONTACT_NAME); String contactTelNo = jsonDossier.getString(DossierTerm.CONTACT_TEL_NO); String contactEmail = jsonDossier.getString(DossierTerm.CONTACT_EMAIL); // String postalServiceCode = jsonDossier.getString(DossierTerm.POSTAL_SERVICE_CODE); String postalServiceName = jsonDossier.getString(DossierTerm.POSTAL_SERVICE_NAME); String postalAddress = jsonDossier.getString(DossierTerm.POSTAL_ADDRESS); String postalCityCode = jsonDossier.getString(DossierTerm.POSTAL_CITY_CODE); String postalDistrictCode = jsonDossier.getString(DossierTerm.POSTAL_DISTRICT_CODE); String postalDistrictName = jsonDossier.getString(DossierTerm.POSTAL_DISTRICT_NAME); String postalWardCode = jsonDossier.getString(DossierTerm.POSTAL_WARD_CODE); String postalWardName = jsonDossier.getString(DossierTerm.POSTAL_WARD_NAME); String postalTelNo = jsonDossier.getString(DossierTerm.POSTAL_TEL_NO); String applicantNote = jsonDossier.getString(DossierTerm.APPLICANT_NOTE); String delegateIdNo = jsonDossier.getString(DossierTerm.DELEGATE_ID_NO); String delegateName = jsonDossier.getString(DossierTerm.DELEGATE_NAME); String delegateTelNo = jsonDossier.getString(DossierTerm.DELEGATE_TELNO); String delegateEmail = jsonDossier.getString(DossierTerm.DELEGATE_EMAIL); String delegateAddress = jsonDossier.getString(DossierTerm.DELEGATE_ADDRESS); //TODO String delegateCityCode = jsonDossier.getString(DossierTerm.DELEGATE_CITYCODE); String delegateCityName = StringPool.BLANK; if (Validator.isNotNull(delegateCityCode)) { delegateCityName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateCityCode); } String delegateDistrictCode = jsonDossier.getString(DossierTerm.DELEGATE_DISTRICTCODE); String delegateDistrictName = StringPool.BLANK; if (Validator.isNotNull(delegateDistrictCode)) { delegateDistrictName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateDistrictCode); } String delegateWardCode = jsonDossier.getString(DossierTerm.DELEGATE_WARDCODE); String delegateWardName = StringPool.BLANK; if (Validator.isNotNull(delegateWardCode)) { delegateWardName = getDictItemName(groupId, ADMINISTRATIVE_REGION, delegateWardCode); } // String dossierName = Validator.isNotNull(jsonDossier.getString(DossierTerm.DOSSIER_NAME)) ? jsonDossier.getString(DossierTerm.DOSSIER_NAME) : serviceName; Long receiveDateTimeStamp = jsonDossier.getLong(DossierTerm.RECEIVE_DATE); Date receiveDate = null; if (receiveDateTimeStamp > 0) { receiveDate = new Date(receiveDateTimeStamp); } Long dueDateTimeStamp = jsonDossier.getLong(DossierTerm.DUE_DATE); Date dueDate = null; if (dueDateTimeStamp > 0) { dueDate = new Date(dueDateTimeStamp); } String metaData = jsonDossier.getString(DossierTerm.META_DATA); dossier = dossierLocalService.initMultipleDossier(groupId, 0l, referenceUid, counter, input.getServiceCode(), serviceName, input.getGovAgencyCode(), govAgencyName, applicantName, applicantIdType, applicantIdNo, appIdDate, address, contactName, contactTelNo, contactEmail, input.getDossierTemplateNo(), password, viaPostal, postalServiceCode, postalServiceName, postalAddress, postalCityCode, postalCityName, postalDistrictCode, postalDistrictName, postalWardCode, postalWardName, postalTelNo, online, process.getDirectNotification(), applicantNote, input.getOriginality(), delegateIdNo, delegateName, delegateTelNo, delegateEmail, delegateAddress, delegateCityCode, delegateCityName, delegateDistrictCode, delegateDistrictName, delegateWardCode, delegateWardName, registerBookCode, registerBookName, sampleCount, dossierName, service, process, option, serviceContext); if (receiveDate != null) dossier.setReceiveDate(receiveDate); if (dueDate != null) dossier.setDueDate(dueDate); if (Validator.isNotNull(metaData)) dossier.setMetaData(metaData); //TODO: Process then //updateDelegateApplicant(dossier, input); _log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms"); if (originality != DossierTerm.ORIGINALITY_LIENTHONG) { Applicant applicant = ApplicantLocalServiceUtil.fetchByMappingID(serviceContext.getUserId()); if (applicant != null) { updateApplicantInfo(dossier, applicant.getApplicantIdDate(), applicant.getApplicantIdNo(), applicant.getApplicantIdType(), applicant.getApplicantName(), applicant.getAddress(), applicant.getCityCode(), applicant.getCityName(), applicant.getDistrictCode(), applicant.getDistrictName(), applicant.getWardCode(), applicant.getWardName(), applicant.getContactEmail(), applicant.getContactTelNo() ); } } if (Validator.isNull(dossier)) { throw new NotFoundException("Cant add DOSSIER"); } _log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms"); //TODO /** Create DossierMark */ //_log.debug("flagOldDossier: "+flagOldDossier); _log.debug("originality: "+originality); String templateNo = dossier.getDossierTemplateNo(); _log.debug("templateNo: "+templateNo); long dossierId = dossier.getDossierId(); if (originality == DossierTerm.ORIGINALITY_MOTCUA || originality == DossierTerm.ORIGINALITY_LIENTHONG) { if (Validator.isNotNull(input.getDossierMarkArr())) { JSONArray markArr = JSONFactoryUtil.createJSONArray(input.getDossierMarkArr()); if (markArr != null && markArr.length() > 0) { List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossierId); Map<String, DossierMark> mapMarks = new HashMap<>(); for (DossierMark dm : lstMarks) { mapMarks.put(dm.getDossierPartNo(), dm); } org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[markArr.length()]; for (int i = 0; i < markArr.length(); i++) { JSONObject jsonMark = markArr.getJSONObject(i); //System.out.println("jsonMark: "+jsonMark); org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel(); model.setDossierId(dossier.getDossierId()); model.setDossierPartNo(jsonMark.getString("partNo")); model.setFileCheck(0); model.setFileMark(jsonMark.getInt("fileMark")); model.setFileComment(StringPool.BLANK); model.setRecordCount(StringPool.BLANK); marks[i] = model; } dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext); } } else if (Validator.isNotNull(templateNo)) { List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo); // _log.info("partList: "+partList); if (partList != null && partList.size() > 0) { _log.debug("partList.size(): "+partList.size()); _log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms"); org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()]; int count = 0; List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossierId); Map<String, DossierMark> mapMarks = new HashMap<>(); for (DossierMark dm : lstMarks) { mapMarks.put(dm.getDossierPartNo(), dm); } for (DossierPart dossierPart : partList) { int fileMark = dossierPart.getFileMark(); String dossierPartNo = dossierPart.getPartNo(); org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel(); model.setDossierId(dossier.getDossierId()); model.setDossierPartNo(dossierPartNo); model.setFileCheck(0); model.setFileMark(fileMark); model.setFileComment(StringPool.BLANK); model.setRecordCount(StringPool.BLANK); marks[count++] = model; } dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext); _log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms"); } } } /** * Add dossier file */ if (Validator.isNotNull(input.getDossierFileArr())) { JSONArray dossierFileArr = JSONFactoryUtil.createJSONArray(input.getDossierFileArr()); if (dossierFileArr != null && dossierFileArr.length() > 0) { for (int j = 0; j < dossierFileArr.length(); j++) { JSONObject jsonFile = dossierFileArr.getJSONObject(j); System.out.println("jsonFile: "+jsonFile.getString("eform")); boolean eform = Boolean.valueOf(jsonFile.getString("eform")); System.out.println("eform"+eform); if (eform) { //EFORM _log.info("In dossier file create by eform"); try { // String referenceUidFile = UUID.randomUUID().toString(); String partNo = jsonFile.getString(DossierPartTerm.PART_NO); String formData = jsonFile.getString("formData"); DossierFile dossierFile = null; // DossierFileActions action = new DossierFileActionsImpl(); DossierPart dossierPart = dossierPartLocalService.fetchByTemplatePartNo(groupId, templateNo, partNo); //_log.info("__file:" + file); //DataHandler dataHandler = (file != null) ? file.getDataHandler() : null; dossierFile = DossierFileLocalServiceUtil.getByGID_DID_PART_EFORM(groupId, dossierId, partNo, true, false); if (dossierFile == null) { _log.info("dossierFile NULL"); dossierFile = dossierFileLocalService.addDossierFileEForm(groupId, dossierId, referenceUid, templateNo, partNo, dossierPart.getFileTemplateNo(), dossierPart.getPartName(), dossierPart.getPartName(), 0, null, StringPool.BLANK, "true", serviceContext); } if(Validator.isNotNull(formData)) { dossierFile.setFormData(formData); } if(Validator.isNotNull(eform)) { dossierFile.setEForm(eform); } _log.info("__Start update dossier file at:" + new Date()); DossierFileLocalServiceUtil.updateDossierFile(dossierFile); dossierFile = dossierFileLocalService.updateFormData(groupId, dossierId, dossierFile.getReferenceUid(), formData, serviceContext); _log.info("__End update dossier file at:" + new Date()); } catch (Exception e) { _log.debug(e); } } } } } /**Create dossier user */ List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId()); List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId()); if (lstDus.size() == 0) { DossierUserActions duActions = new DossierUserActionsImpl(); duActions.initDossierUser(groupId, dossier, process, lstProcessRoles); } if (originality == DossierTerm.ORIGINALITY_DVCTT) { dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true); } _log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms"); // if (dossier != null) { // // // long notificationQueueId = CounterLocalServiceUtil.increment(NotificationQueue.class.getName()); // // NotificationQueue queue = NotificationQueueLocalServiceUtil.createNotificationQueue(notificationQueueId); // //Process add notification queue // Date now = new Date(); // // Calendar cal = Calendar.getInstance(); // cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) + 1); // // queue.setCreateDate(now); // queue.setModifiedDate(now); // queue.setGroupId(groupId); // queue.setCompanyId(company.getCompanyId()); // // queue.setNotificationType(NotificationType.DOSSIER_01); // queue.setClassName(Dossier.class.getName()); // queue.setClassPK(String.valueOf(dossier.getPrimaryKey())); // queue.setToUsername(dossier.getUserName()); // queue.setToUserId(dossier.getUserId()); // queue.setToEmail(dossier.getContactEmail()); // queue.setToTelNo(dossier.getContactTelNo()); // // JSONObject payload = JSONFactoryUtil.createJSONObject(); // try { //// _log.info("START PAYLOAD: "); // payload.put( // "Dossier", JSONFactoryUtil.createJSONObject( // JSONFactoryUtil.looseSerialize(dossier))); // } // catch (JSONException parse) { // _log.error(parse); // } //// _log.info("payloadTest: "+payload.toJSONString()); // queue.setPayload(payload.toJSONString()); // queue.setExpireDate(cal.getTime()); // // NotificationQueueLocalServiceUtil.addNotificationQueue(queue); // } _log.debug("CREATE DOSSIER 6: " + (System.currentTimeMillis() - start) + " ms"); //Add to dossier user based on service process role createDossierUsers(groupId, dossier, process, lstProcessRoles); _log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms"); dossierLocalService.updateDossier(dossier); _log.debug("CREATE DOSSIER 8: " + (System.currentTimeMillis() - start) + " ms"); String payload = StringPool.BLANK; String actionCode = "1100"; if (dossier.getReceiveDate() == null) { JSONObject jsonDate = JSONFactoryUtil.createJSONObject(); jsonDate.put(DossierTerm.RECEIVE_DATE, (new Date()).getTime()); Double durationCount = process.getDurationCount(); if (Validator.isNotNull(String.valueOf(durationCount)) && durationCount > 0d) { Date dueDateCal = HolidayUtils.getDueDate(new Date(), process.getDurationCount(), process.getDurationUnit(), groupId); jsonDate.put(DossierTerm.DUE_DATE, dueDateCal != null ? dueDateCal.getTime() : 0); } if (Validator.isNotNull(jsonDate)) { payload = jsonDate.toJSONString(); } } // ProcessAction proAction = getProcessAction(groupId, dossier, actionCode, serviceProcessId); doAction(groupId, userId, dossier, option, proAction, actionCode, StringPool.BLANK, StringPool.BLANK, payload, StringPool.BLANK, input.getPayment(), 0, serviceContext); } return dossier; } private void createDossierUsers(long groupId, Dossier dossier, ServiceProcess process, List<ServiceProcessRole> lstProcessRoles) { List<DossierUser> lstDaus = dossierUserLocalService.findByDID(dossier.getDossierId()); int count = 0; long[] roleIds = new long[lstProcessRoles.size()]; for (ServiceProcessRole spr : lstProcessRoles) { long roleId = spr.getRoleId(); roleIds[count++] = roleId; } List<JobPos> lstJobPoses = JobPosLocalServiceUtil.findByF_mappingRoleIds(groupId, roleIds); Map<Long, JobPos> mapJobPoses = new HashMap<>(); long[] jobPosIds = new long[lstJobPoses.size()]; count = 0; for (JobPos jp : lstJobPoses) { mapJobPoses.put(jp.getJobPosId(), jp); jobPosIds[count++] = jp.getJobPosId(); } List<EmployeeJobPos> lstTemp = EmployeeJobPosLocalServiceUtil.findByF_G_jobPostIds(groupId, jobPosIds); Map<Long, List<EmployeeJobPos>> mapEJPS = new HashMap<>(); for (EmployeeJobPos ejp : lstTemp) { if (mapEJPS.get(ejp.getJobPostId()) != null) { mapEJPS.get(ejp.getJobPostId()).add(ejp); } else { List<EmployeeJobPos> lstEJPs = new ArrayList<>(); lstEJPs.add(ejp); mapEJPS.put(ejp.getJobPostId(), lstEJPs); } } for (ServiceProcessRole spr : lstProcessRoles) { long roleId = spr.getRoleId(); int moderator = spr.getModerator() ? 1 : 0; // JobPos jp = JobPosLocalServiceUtil.fetchByF_mappingRoleId(groupId, roleId); JobPos jp = mapJobPoses.get(roleId); if (jp != null) { // List<EmployeeJobPos> lstEJPs = EmployeeJobPosLocalServiceUtil.getByJobPostId(groupId, jp.getJobPosId()); List<EmployeeJobPos> lstEJPs = mapEJPS.get(jp.getJobPosId()); long[] employeeIds = new long[lstEJPs.size()]; int countEmp = 0; for (EmployeeJobPos ejp : lstEJPs) { employeeIds[countEmp++] = ejp.getEmployeeId(); } List<Employee> lstEmpls = EmployeeLocalServiceUtil.findByG_EMPID(groupId, employeeIds); HashMap<Long, Employee> mapEmpls = new HashMap<>(); for (Employee e : lstEmpls) { mapEmpls.put(e.getEmployeeId(), e); } List<Employee> lstEmployees = new ArrayList<>(); // for (EmployeeJobPos ejp : lstEJPs) { // Employee employee = EmployeeLocalServiceUtil.fetchEmployee(ejp.getEmployeeId()); // if (employee != null) { // lstEmployees.add(employee); // } // } for (EmployeeJobPos ejp : lstEJPs) { if (mapEmpls.get(ejp.getEmployeeId()) != null) { lstEmployees.add(mapEmpls.get(ejp.getEmployeeId())); } } HashMap<Long, DossierUser> mapDaus = new HashMap<>(); for (DossierUser du : lstDaus) { mapDaus.put(du.getUserId(), du); } for (Employee e : lstEmployees) { // DossierUserPK pk = new DossierUserPK(); // pk.setDossierId(dossier.getDossierId()); // pk.setUserId(e.getMappingUserId()); // DossierUser ds = DossierUserLocalServiceUtil.fetchDossierUser(pk); if (mapDaus.get(e.getMappingUserId()) == null) { // if (ds == null) { dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), e.getMappingUserId(), moderator, Boolean.FALSE); } else { DossierUser ds = mapDaus.get(e.getMappingUserId()); if (moderator == 1 && ds.getModerator() == 0) { ds.setModerator(1); dossierUserLocalService.updateDossierUser(ds); } } } } } } private void updateApplicantInfo(Dossier dossier, Date applicantIdDate, String applicantIdNo, String applicantIdType, String applicantName, String address, String cityCode, String cityName, String districtCode, String districtName, String wardCode, String wardName, String contactEmail, String contactTelNo) { dossier.setApplicantIdDate(applicantIdDate); dossier.setApplicantIdNo(applicantIdNo); dossier.setApplicantIdType(applicantIdType); dossier.setApplicantName(applicantName); dossier.setAddress(address); dossier.setCityCode(cityCode); dossier.setCityName(cityName); dossier.setDistrictCode(districtCode); dossier.setDistrictName(districtName); dossier.setWardCode(wardCode); dossier.setWardName(wardName); dossier.setContactEmail(contactEmail); dossier.setContactTelNo(contactTelNo); dossier.setDelegateAddress(address); dossier.setDelegateCityCode(cityCode); dossier.setDelegateCityName(cityName); dossier.setDelegateDistrictCode(districtCode); dossier.setDelegateDistrictName(districtName); dossier.setDelegateEmail(contactEmail); dossier.setDelegateIdNo(applicantIdNo); dossier.setDelegateName(applicantName); dossier.setDelegateTelNo(contactTelNo); dossier.setDelegateWardCode(wardCode); dossier.setDelegateWardName(wardName); } private void updateDelegateApplicant(Dossier dossier, DossierInputModel input) { if (Validator.isNotNull(input.getDelegateName())) { dossier.setDelegateName(input.getDelegateName()); } if (Validator.isNotNull(input.getDelegateIdNo())) { dossier.setDelegateIdNo(input.getDelegateIdNo()); } if (Validator.isNotNull(input.getDelegateTelNo())) { dossier.setDelegateTelNo(input.getDelegateTelNo()); } if (Validator.isNotNull(input.getDelegateEmail())) { dossier.setDelegateEmail(input.getDelegateEmail()); } if (Validator.isNotNull(input.getDelegateAddress())) { dossier.setDelegateAddress(input.getDelegateAddress()); } if (Validator.isNotNull(input.getDelegateCityCode())) { dossier.setDelegateCityCode(input.getDelegateCityCode()); } if (Validator.isNotNull(input.getDelegateCityName())) { dossier.setDelegateCityName(input.getDelegateCityName()); } if (Validator.isNotNull(input.getDelegateDistrictCode())) { dossier.setDelegateDistrictCode(input.getDelegateDistrictCode()); } if (Validator.isNotNull(input.getDelegateDistrictName())) { dossier.setDelegateDistrictName(input.getDelegateDistrictName()); } if (Validator.isNotNull(input.getDelegateWardCode())) { dossier.setDelegateWardCode(input.getDelegateWardCode()); } if (Validator.isNotNull(input.getDelegateWardName())) { dossier.setDelegateWardCode(input.getDelegateWardName()); } } private String getDictItemName(long groupId, DictCollection dc, String itemCode) { if (Validator.isNotNull(dc)) { DictItem it = DictItemLocalServiceUtil.fetchByF_dictItemCode(itemCode, dc.getPrimaryKey(), groupId); if(Validator.isNotNull(it)){ return it.getItemName(); }else{ return StringPool.BLANK; } } else { return StringPool.BLANK; } } @Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class }) public DossierFile addDossierFileByDossierId(long groupId, Company company, User user, ServiceContext serviceContext, Attachment file, String id, String referenceUid, String dossierTemplateNo, String dossierPartNo, String fileTemplateNo, String displayName, String fileType, String isSync, String formData, String removed, String eForm, Long modifiedDate) throws UnauthenticationException, PortalException, Exception { BackendAuth auth = new BackendAuthImpl(); if (!auth.isAuth(serviceContext)) { throw new UnauthenticationException(); } long dossierId = GetterUtil.getLong(id); Dossier dossier = null; if (dossierId != 0) { dossier = dossierLocalService.fetchDossier(dossierId); if (Validator.isNull(dossier)) { dossier = dossierLocalService.getByRef(groupId, id); } } else { dossier = dossierLocalService.getByRef(groupId, id); } DataHandler dataHandler = (file != null) ? file.getDataHandler() : null; long originDossierId = dossier.getOriginDossierId(); if (originDossierId != 0) { //HSLT Dossier hsltDossier = dossierLocalService.fetchDossier(dossier.getDossierId()); dossier = dossierLocalService.fetchDossier(dossier.getOriginDossierId()); ServiceConfig serviceConfig = serviceConfigLocalService.getBySICodeAndGAC(groupId, dossier.getServiceCode(), hsltDossier.getGovAgencyCode()); List<ProcessOption> lstOptions = processOptionLocalService.getByServiceProcessId(serviceConfig.getServiceConfigId()); if (serviceConfig != null) { if (lstOptions.size() > 0) { ProcessOption processOption = lstOptions.get(0); DossierTemplate dossierTemplate = dossierTemplateLocalService.fetchDossierTemplate(processOption.getDossierTemplateId()); List<DossierPart> lstParts = dossierPartLocalService.getByTemplateNo(groupId, dossierTemplate.getTemplateNo()); for (DossierPart dp : lstParts) { if (dp.getPartNo().equals(dossierPartNo) && dp.getFileTemplateNo().equals(fileTemplateNo)) { dossierTemplateNo = dp.getTemplateNo(); } } } } } else { List<DossierPart> lstParts = dossierPartLocalService.getByTemplateNo(groupId, dossier.getDossierTemplateNo()); for (DossierPart dp : lstParts) { if (dp.getPartNo().equals(dossierPartNo)) { fileTemplateNo = dp.getFileTemplateNo(); dossierTemplateNo = dossier.getDossierTemplateNo(); } } } if (originDossierId > 0) { _log.debug("__Start add file at:" + new Date()); DossierFile dossierFile = null; DossierFile oldDossierFile = null; if (Validator.isNotNull(referenceUid)) { oldDossierFile = dossierFileLocalService.getByDossierAndRef(dossier.getDossierId(), referenceUid); } if (oldDossierFile != null && modifiedDate != null) { if (oldDossierFile.getModifiedDate() != null && oldDossierFile.getModifiedDate().getTime() < modifiedDate) { if (dataHandler != null && dataHandler.getInputStream() != null) { dossierFile = dossierFileLocalService.updateDossierFile(groupId, dossier.getDossierId(), referenceUid, displayName, StringPool.BLANK, dataHandler.getInputStream(), serviceContext); } else { dossierFile = dossierFileLocalService.updateDossierFile(groupId, dossier.getDossierId(), referenceUid, displayName, StringPool.BLANK, null, serviceContext); } _log.debug("__End add file at:" + new Date()); if(Validator.isNotNull(formData)) { dossierFile.setFormData(formData); } _log.debug("REMOVED:" + removed); if(Validator.isNotNull(removed)) { dossierFile.setRemoved(Boolean.parseBoolean(removed)); } if(Validator.isNotNull(eForm)) { dossierFile.setEForm(Boolean.parseBoolean(eForm)); } _log.debug("__Start update dossier file at:" + new Date()); dossierFileLocalService.updateDossierFile(dossierFile); _log.debug("__End update dossier file at:" + new Date()); _log.debug("__End bind to dossierFile" + new Date()); return dossierFile; } else { throw new DataConflictException("Conflict dossier file"); } } else { _log.debug("__Start add file at:" + new Date()); if (dataHandler != null && dataHandler.getInputStream() != null) { dossierFile = dossierFileLocalService.addDossierFile(groupId, dossier.getDossierId(), referenceUid, dossierTemplateNo, dossierPartNo, fileTemplateNo, displayName, dataHandler.getName(), 0, dataHandler.getInputStream(), fileType, isSync, serviceContext); } else { dossierFile = dossierFileLocalService.addDossierFile(groupId, dossier.getDossierId(), referenceUid, dossierTemplateNo, dossierPartNo, fileTemplateNo, displayName, displayName, 0, null, fileType, isSync, serviceContext); } _log.debug("__End add file at:" + new Date()); if(Validator.isNotNull(formData)) { dossierFile.setFormData(formData); } if(Validator.isNotNull(removed)) { dossierFile.setRemoved(Boolean.parseBoolean(removed)); } if(Validator.isNotNull(eForm)) { dossierFile.setEForm(Boolean.parseBoolean(eForm)); } _log.debug("__Start update dossier file at:" + new Date()); dossierFileLocalService.updateDossierFile(dossierFile); _log.debug("__End update dossier file at:" + new Date()); _log.debug("__End bind to dossierFile" + new Date()); return dossierFile; } } else { // DossierFile lastDossierFile = DossierFileLocalServiceUtil.findLastDossierFile(dossier.getDossierId(), fileTemplateNo, dossierTemplateNo); //_log.info("lastDossierFile: "+lastDossierFile); DossierFile oldDossierFile = null; if (Validator.isNotNull(referenceUid)) { oldDossierFile = DossierFileLocalServiceUtil.getByDossierAndRef(dossier.getDossierId(), referenceUid); } if (oldDossierFile != null && modifiedDate != null) { if (oldDossierFile.getModifiedDate() != null && oldDossierFile.getModifiedDate().getTime() < modifiedDate) { _log.debug("__Start add file at:" + new Date()); DossierFile dossierFile = null; if (dataHandler != null && dataHandler.getInputStream() != null) { dossierFile = dossierFileLocalService.updateDossierFile(groupId, dossier.getDossierId(), referenceUid, displayName, StringPool.BLANK, dataHandler.getInputStream(), serviceContext); } else { dossierFile = dossierFileLocalService.updateDossierFile(groupId, dossier.getDossierId(), referenceUid, displayName, StringPool.BLANK, null, serviceContext); } _log.debug("__End add file at:" + new Date()); if(Validator.isNotNull(formData)) { dossierFile.setFormData(formData); } if(Validator.isNotNull(removed)) { dossierFile.setRemoved(Boolean.parseBoolean(removed)); } if(Validator.isNotNull(eForm)) { dossierFile.setEForm(Boolean.parseBoolean(eForm)); } _log.debug("__Start update dossier file at:" + new Date()); DossierFileLocalServiceUtil.updateDossierFile(dossierFile); _log.debug("__End update dossier file at:" + new Date()); _log.debug("__End bind to dossierFile" + new Date()); return dossierFile; } else { throw new DataConflictException("Conflict dossier file"); } } else { _log.debug("__Start add file at:" + new Date()); DossierFile dossierFile = null; if (dataHandler != null && dataHandler.getInputStream() != null) { dossierFile = dossierFileLocalService.addDossierFile(groupId, dossier.getDossierId(), referenceUid, dossierTemplateNo, dossierPartNo, fileTemplateNo, displayName, dataHandler.getName(), 0, dataHandler.getInputStream(), fileType, isSync, serviceContext); } else { dossierFile = dossierFileLocalService.addDossierFile(groupId, dossier.getDossierId(), referenceUid, dossierTemplateNo, dossierPartNo, fileTemplateNo, displayName, displayName, 0, null, fileType, isSync, serviceContext); } _log.debug("__End add file at:" + new Date()); if(Validator.isNotNull(formData)) { dossierFile.setFormData(formData); } if(Validator.isNotNull(removed)) { dossierFile.setRemoved(Boolean.parseBoolean(removed)); } if(Validator.isNotNull(eForm)) { dossierFile.setEForm(Boolean.parseBoolean(eForm)); } _log.debug("__Start update dossier file at:" + new Date()); dossierFileLocalService.updateDossierFile(dossierFile); _log.debug("__End update dossier file at:" + new Date()); _log.debug("__End bind to dossierFile" + new Date()); return dossierFile; } } } @Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class }) public DossierFile updateDossierFile(long groupId, Company company, ServiceContext serviceContext, long id, String referenceUid, Attachment file) throws UnauthenticationException, PortalException, Exception { BackendAuth auth = new BackendAuthImpl(); DataHandler dataHandle = file.getDataHandler(); if (!auth.isAuth(serviceContext)) { throw new UnauthenticationException(); } Dossier dossier = dossierLocalService.fetchDossier(id); if (dossier != null) { if (dossier.getOriginDossierId() != 0) { dossier = dossierLocalService.fetchDossier(dossier.getOriginDossierId()); id = dossier.getDossierId(); } } DossierFile dossierFile = dossierFileLocalService.updateDossierFile(groupId, id, referenceUid, dataHandle.getName(), StringPool.BLANK, dataHandle.getInputStream(), serviceContext); return dossierFile; } @Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class }) public DossierFile updateDossierFileFormData(long groupId, Company company, ServiceContext serviceContext, long id, String referenceUid, String formdata) throws UnauthenticationException, PortalException, Exception { BackendAuth auth = new BackendAuthImpl(); if (!auth.isAuth(serviceContext)) { throw new UnauthenticationException(); } Dossier dossier = dossierLocalService.fetchDossier(id); if (dossier != null) { if (dossier.getOriginDossierId() != 0) { dossier = dossierLocalService.fetchDossier(dossier.getOriginDossierId()); id = dossier.getOriginDossierId(); } } DossierFile dossierFile = dossierFileLocalService.updateFormData(groupId, id, referenceUid, formdata, serviceContext); return dossierFile; } @Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class }) public DossierFile resetformdataDossierFileFormData(long groupId, Company company, ServiceContext serviceContext, long id, String referenceUid, String formdata) throws UnauthenticationException, PortalException, Exception { BackendAuth auth = new BackendAuthImpl(); if (!auth.isAuth(serviceContext)) { throw new UnauthenticationException(); } Dossier dossier = dossierLocalService.fetchDossier(id); if (dossier != null) { if (dossier.getOriginDossierId() != 0) { dossier = dossierLocalService.fetchDossier(dossier.getOriginDossierId()); id = dossier.getOriginDossierId(); } } DossierFile dossierFile = dossierFileLocalService.getDossierFileByReferenceUid(dossier.getDossierId(), referenceUid); String defaultData = StringPool.BLANK; if (Validator.isNotNull(dossierFile)) { DossierPart part = dossierPartLocalService.getByFileTemplateNo(groupId, dossierFile.getFileTemplateNo()); defaultData = AutoFillFormData.sampleDataBinding(part.getSampleData(), dossier.getDossierId(), serviceContext); dossierFile = dossierFileLocalService.getByReferenceUid(referenceUid).get(0); JSONObject defaultDataObj = JSONFactoryUtil.createJSONObject(defaultData); defaultDataObj.put("LicenceNo", dossierFile.getDeliverableCode()); defaultData = defaultDataObj.toJSONString(); } dossierFile = dossierFileLocalService.updateFormData(groupId, dossier.getDossierId(), referenceUid, defaultData, serviceContext); String deliverableCode = dossierFile.getDeliverableCode(); if (Validator.isNotNull(deliverableCode)) { Deliverable deliverable = deliverableLocalService.getByCode(deliverableCode); deliverableLocalService.deleteDeliverable(deliverable); } return dossierFile; } @Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class }) public PaymentFile createPaymentFileByDossierId(long groupId, ServiceContext serviceContext, String id, PaymentFileInputModel input) throws UnauthenticationException, PortalException, Exception { long userId = serviceContext.getUserId(); BackendAuth auth = new BackendAuthImpl(); if (!auth.isAuth(serviceContext)) { throw new UnauthenticationException(); } Dossier dossier = getDossier(id, groupId); long dossierId = dossier.getPrimaryKey(); if (!auth.hasResource(serviceContext, PaymentFile.class.getName(), ActionKeys.ADD_ENTRY)) { throw new UnauthorizationException(); } PaymentFile oldPaymentFile = paymentFileLocalService.getByDossierId(groupId, dossier.getDossierId()); String referenceUid = input.getReferenceUid(); PaymentFile paymentFile = null; if (Validator.isNull(referenceUid)) { referenceUid = PortalUUIDUtil.generate(); } if (oldPaymentFile != null) { paymentFile = oldPaymentFile; } else { paymentFile = paymentFileLocalService.createPaymentFiles(userId, groupId, dossierId, referenceUid, input.getPaymentFee(), input.getAdvanceAmount(), input.getFeeAmount(), input.getServiceAmount(), input.getShipAmount(), input.getPaymentAmount(), input.getPaymentNote(), input.getEpaymentProfile(), input.getBankInfo(), 0, input.getPaymentMethod(), serviceContext); } paymentFile.setInvoiceTemplateNo(input.getInvoiceTemplateNo()); if(Validator.isNotNull(input.getConfirmFileEntryId())){ paymentFile.setConfirmFileEntryId(input.getConfirmFileEntryId()); } if(Validator.isNotNull(input.getPaymentStatus())){ paymentFile.setPaymentStatus(input.getPaymentStatus()); } if(Validator.isNotNull(input.getEinvoice())) { paymentFile.setEinvoice(input.getEinvoice()); } if(Validator.isNotNull(input.getPaymentAmount())) { paymentFile.setPaymentAmount(input.getPaymentAmount()); } if(Validator.isNotNull(input.getPaymentMethod())){ paymentFile.setPaymentMethod(input.getPaymentMethod()); } if(Validator.isNotNull(input.getServiceAmount())){ paymentFile.setServiceAmount(input.getServiceAmount()); } if(Validator.isNotNull(input.getShipAmount())){ paymentFile.setShipAmount(input.getShipAmount()); } if(Validator.isNotNull(input.getAdvanceAmount())){ paymentFile.setAdvanceAmount(input.getAdvanceAmount()); } paymentFile = paymentFileLocalService.updatePaymentFile(paymentFile); return paymentFile; } private Dossier getDossier(String id, long groupId) throws PortalException { long dossierId = GetterUtil.getLong(id); Dossier dossier = null; if (dossierId != 0) { dossier = dossierLocalService.fetchDossier(dossierId); } if (Validator.isNull(dossier)) { dossier = dossierLocalService.getByRef(groupId, id); } return dossier; } @Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class }) public Dossier addDossierPublish(long groupId, Company company, User user, ServiceContext serviceContext, org.opencps.dossiermgt.input.model.DossierPublishModel input) throws UnauthenticationException, PortalException, Exception { BackendAuth auth = new BackendAuthImpl(); DossierActions actions = new DossierActionsImpl(); if (!auth.isAuth(serviceContext)) { throw new UnauthenticationException(); } String referenceUid = input.getReferenceUid(); int counter = 0; String serviceCode = input.getServiceCode(); String serviceName = input.getServiceName(); String govAgencyCode = input.getGovAgencyCode(); String govAgencyName = input.getGovAgencyName(); String applicantName = input.getApplicantName(); String applicantType = input.getApplicantIdType(); String applicantIdNo = input.getApplicantIdNo(); String applicantIdDate = input.getApplicantIdDate(); String address = input.getAddress(); String cityCode = input.getCityCode(); String cityName = input.getCityName(); String districtCode = input.getDistrictCode(); String districtName = input.getDistrictName(); String wardCode = input.getWardCode(); String wardName = input.getWardName(); String contactName = input.getContactName(); String contactTelNo = input.getContactTelNo(); String contactEmail = input.getContactEmail(); String dossierTemplateNo = input.getDossierTemplateNo(); String password = input.getPassword(); String online = input.getOnline(); String applicantNote = input.getApplicantNote(); int originality = 0; long createDateLong = GetterUtil.getLong(input.getCreateDate()); long modifiedDateLong = GetterUtil.getLong(input.getModifiedDate()); long submitDateLong = GetterUtil.getLong(input.getSubmitDate()); long receiveDateLong = GetterUtil.getLong(input.getReceiveDate()); long dueDateLong = GetterUtil.getLong(input.getDueDate()); long releaseDateLong = GetterUtil.getLong(input.getReleaseDate()); long finishDateLong = GetterUtil.getLong(input.getFinishDate()); long cancellingDateLong = GetterUtil.getLong(input.getCancellingDate()); long correcttingDateLong = GetterUtil.getLong(input.getCorrecttingDate()); long endorsementDateLong = GetterUtil.getLong(input.getEndorsementDate()); long extendDateLong = GetterUtil.getLong(input.getExtendDate()); long processDateLong = GetterUtil.getLong(input.getProcessDate()); String submissionNote = input.getSubmissionNote(); String lockState = input.getLockState(); String dossierNo = input.getDossierNo(); Dossier oldDossier = null; if (Validator.isNotNull(input.getReferenceUid())) { oldDossier = getDossier(input.getReferenceUid(), groupId); } else { oldDossier = DossierLocalServiceUtil.getByDossierNo(groupId, dossierNo); referenceUid = DossierNumberGenerator.generateReferenceUID(groupId); } if (oldDossier == null || oldDossier.getOriginality() == 0) { Dossier dossier = actions.publishDossier(groupId, 0l, referenceUid, counter, serviceCode, serviceName, govAgencyCode, govAgencyName, applicantName, applicantType, applicantIdNo, applicantIdDate, address, cityCode, cityName, districtCode, districtName, wardCode, wardName, contactName, contactTelNo, contactEmail, dossierTemplateNo, password, 0, StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, Boolean.valueOf(online), false, applicantNote, originality, createDateLong != 0 ? new Date(createDateLong) : null, modifiedDateLong != 0 ? new Date(modifiedDateLong) : null, submitDateLong != 0 ? new Date(submitDateLong) : null, receiveDateLong != 0 ? new Date(receiveDateLong) : null, dueDateLong != 0 ? new Date(dueDateLong) : null, releaseDateLong != 0 ? new Date(releaseDateLong) : null, finishDateLong != 0 ? new Date(finishDateLong) : null, cancellingDateLong != 0 ? new Date(cancellingDateLong) : null, correcttingDateLong != 0 ? new Date(correcttingDateLong) : null, endorsementDateLong != 0 ? new Date(endorsementDateLong) : null, extendDateLong != 0 ? new Date(extendDateLong) : null, processDateLong != 0 ? new Date(processDateLong) : null, input.getDossierNo(), input.getDossierStatus(), input.getDossierStatusText(), input.getDossierSubStatus(), input.getDossierSubStatusText(), input.getDossierActionId() != null ? input.getDossierActionId() : 0, submissionNote, lockState, input.getDelegateName(), input.getDelegateIdNo(), input.getDelegateTelNo(), input.getDelegateEmail(), input.getDelegateAddress(), input.getDelegateCityCode(), input.getDelegateCityName(), input.getDelegateDistrictCode(), input.getDelegateDistrictName(), input.getDelegateWardCode(), input.getDelegateWardName(), input.getDurationCount(), input.getDurationUnit(), input.getDossierName(), input.getProcessNo(), input.getMetaData(), serviceContext); return dossier; } return oldDossier; } @Transactional(propagation=Propagation.REQUIRED, rollbackFor={SystemException.class, PortalException.class, Exception.class }) public Dossier addFullDossier(long groupId, Company company, User user, ServiceContext serviceContext, DossierInputModel input) throws UnauthenticationException, PortalException, Exception { BackendAuth auth = new BackendAuthImpl(); DossierPermission dossierPermission = new DossierPermission(); long start = System.currentTimeMillis(); if (!auth.isAuth(serviceContext)) { throw new UnauthenticationException(); } ProcessOption option = getProcessOption(input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo(), groupId); long serviceProcessId = 0; if (option != null) { serviceProcessId = option.getServiceProcessId(); } boolean flag = false; long userId = serviceContext.getUserId(); Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, userId); if (employee != null) { long employeeId = employee.getEmployeeId(); if (employeeId > 0) { List<EmployeeJobPos> empJobList = EmployeeJobPosLocalServiceUtil.findByF_EmployeeId(employeeId); if (empJobList != null && empJobList.size() > 0) { for (EmployeeJobPos employeeJobPos : empJobList) { long jobPosId = employeeJobPos.getJobPostId(); if (jobPosId > 0) { JobPos job = JobPosLocalServiceUtil.fetchJobPos(jobPosId); if (job != null) { ServiceProcessRolePK pk = new ServiceProcessRolePK(serviceProcessId, job.getMappingRoleId()); ServiceProcessRole role = serviceProcessRoleLocalService .fetchServiceProcessRole(pk); if (role != null && role.getModerator()) { flag = true; break; } } } } } } } else { flag = true; } if (!flag) { throw new UnauthenticationException("No permission create dossier"); } _log.debug("CREATE DOSSIER 1: " + (System.currentTimeMillis() - start) + " ms"); dossierPermission.hasCreateDossier(groupId, user.getUserId(), input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo()); //int counter = DossierNumberGenerator.counterDossier(user.getUserId(), groupId); String referenceUid = input.getReferenceUid(); int counter = 0; // Create dossierNote ServiceProcess process = null; boolean online = GetterUtil.getBoolean(input.getOnline()); int originality = GetterUtil.getInteger(input.getOriginality()); Integer viaPostal = input.getViaPostal(); ServiceConfig config = serviceConfigLocalService.getBySICodeAndGAC(groupId, input.getServiceCode(), input.getGovAgencyCode()); if (config != null && Validator.isNotNull(viaPostal)) { viaPostal = config.getPostService() ? (viaPostal == 0 ? 1 : viaPostal) : 0; } else if (config != null) { viaPostal = config.getPostService() ? 1 : 0; } if (option != null) { process = serviceProcessLocalService.getServiceProcess(serviceProcessId); } if (process == null) { throw new NotFoundException("Cant find process"); } if (Validator.isNull(referenceUid) || referenceUid.trim().length() == 0) referenceUid = DossierNumberGenerator.generateReferenceUID(groupId); //Dossier checkDossier = dossierLocalService.getByRef(groupId, referenceUid); //if (checkDossier != null) { // return checkDossier; //} ServiceInfo service = serviceInfoLocalService.getByCode(groupId, input.getServiceCode()); String serviceName = StringPool.BLANK; if (service != null) { serviceName = service.getServiceName(); } String govAgencyName = getDictItemName(groupId, GOVERNMENT_AGENCY, input.getGovAgencyCode()); DictCollection dc = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(ADMINISTRATIVE_REGION, groupId); String cityName = getDictItemName(groupId, dc, input.getCityCode()); String districtName = getDictItemName(groupId, dc, input.getDistrictCode()); String wardName = getDictItemName(groupId, dc, input.getWardCode()); // _log.info("Service code: " + input.getServiceCode()); _log.debug("===ADD DOSSIER CITY NAME:" + cityName); String password = StringPool.BLANK; if (Validator.isNotNull(input.getPassword())) { password = input.getPassword(); } else if (Validator.isNotNull(process.getGeneratePassword()) && process.getGeneratePassword()) { password = PwdGenerator.getPinNumber(); } String postalCityName = StringPool.BLANK; if (Validator.isNotNull(input.getPostalCityCode())) { postalCityName = getDictItemName(groupId, VNPOST_CITY_CODE, input.getPostalCityCode()); } Long sampleCount = (option != null ? option.getSampleCount() : 1l); // Process group dossier if (originality == DossierTerm.ORIGINALITY_HOSONHOM) { _log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms"); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"); Date appIdDate = null; try { appIdDate = sdf.parse(input.getApplicantIdDate()); } catch (Exception e) { _log.debug(e); } Dossier dossier = dossierLocalService.initDossier(groupId, 0l, referenceUid, counter, input.getServiceCode(), serviceName, input.getGovAgencyCode(), govAgencyName, input.getApplicantName(), input.getApplicantIdType(), input.getApplicantIdNo(), appIdDate, input.getAddress(), input.getCityCode(), cityName, input.getDistrictCode(), districtName, input.getWardCode(), wardName, input.getContactName(), input.getContactTelNo(), input.getContactEmail(), input.getDossierTemplateNo(), password, viaPostal, input.getPostalAddress(), input.getPostalCityCode(), postalCityName, input.getPostalTelNo(), online, process.getDirectNotification(), input.getApplicantNote(), Integer.valueOf(input.getOriginality()), service, process, option, serviceContext); if (Validator.isNotNull(input.getDossierName())) { dossier.setDossierName(input.getDossierName()); } else { dossier.setDossierName(serviceName); } dossier.setSampleCount(sampleCount); updateDelegateApplicant(dossier, input); // Process update dossierNo LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>(); params.put(DossierTerm.GOV_AGENCY_CODE, dossier.getGovAgencyCode()); params.put(DossierTerm.SERVICE_CODE, dossier.getServiceCode()); params.put(DossierTerm.DOSSIER_TEMPLATE_NO, dossier.getDossierTemplateNo()); params.put(DossierTerm.DOSSIER_STATUS, StringPool.BLANK); if (option != null) { //Process submition note dossier.setSubmissionNote(option.getSubmissionNote()); String dossierRef = DossierNumberGenerator.generateDossierNumber(groupId, dossier.getCompanyId(), dossier.getDossierId(), option.getProcessOptionId(), process.getDossierGroupPattern(), params); dossier.setDossierNo(dossierRef.trim()); } dossier.setViaPostal(1); _log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms"); if (Validator.isNull(dossier)) { throw new NotFoundException("Can't add DOSSIER"); } _log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms"); //Create DossierMark _log.debug("originality: "+originality); String templateNo = dossier.getDossierTemplateNo(); _log.debug("templateNo: "+templateNo); if (Validator.isNotNull(input.getDossierMarkArr())) { JSONArray markArr = JSONFactoryUtil.createJSONArray(input.getDossierMarkArr()); if (markArr != null && markArr.length() > 0) { List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId()); Map<String, DossierMark> mapMarks = new HashMap<>(); for (DossierMark dm : lstMarks) { mapMarks.put(dm.getDossierPartNo(), dm); } for (int i = 0; i < markArr.length(); i++) { JSONObject jsonMark = markArr.getJSONObject(i); org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[markArr.length()]; org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel(); model.setDossierId(dossier.getDossierId()); model.setDossierPartNo(jsonMark.getString("partNo")); model.setFileCheck(0); model.setFileMark(jsonMark.getInt("fileMark")); model.setFileComment(StringPool.BLANK); model.setRecordCount(StringPool.BLANK); marks[i] = model; dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext); } } } else if (Validator.isNotNull(templateNo)) { List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo); // _log.info("partList: "+partList); if (partList != null && partList.size() > 0) { _log.debug("partList.size(): "+partList.size()); _log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms"); org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()]; int count = 0; List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId()); Map<String, DossierMark> mapMarks = new HashMap<>(); for (DossierMark dm : lstMarks) { mapMarks.put(dm.getDossierPartNo(), dm); } for (DossierPart dossierPart : partList) { int fileMark = dossierPart.getFileMark(); String dossierPartNo = dossierPart.getPartNo(); org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel(); model.setDossierId(dossier.getDossierId()); model.setDossierPartNo(dossierPartNo); model.setFileCheck(0); model.setFileMark(fileMark); model.setFileComment(StringPool.BLANK); model.setRecordCount(StringPool.BLANK); marks[count++] = model; } dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext); _log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms"); } } //Create dossier user List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId()); List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId()); if (lstDus.size() == 0) { DossierUserActions duActions = new DossierUserActionsImpl(); duActions.initDossierUser(groupId, dossier, process, lstProcessRoles); } // if (originality == DossierTerm.ORIGINALITY_DVCTT) { // dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true); // } _log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms"); //Add to dossier user based on service process role createDossierUsers(groupId, dossier, process, lstProcessRoles); _log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms"); return dossierLocalService.updateDossier(dossier); } else { List<Dossier> oldDossiers = dossierLocalService.getByU_G_GAC_SC_DTNO_DS_O( userId, groupId, input.getServiceCode(), input.getGovAgencyCode(), input.getDossierTemplateNo(), StringPool.BLANK, Integer.valueOf(input.getOriginality())); Dossier dossier = null; Dossier oldRefDossier = Validator.isNotNull(input.getReferenceUid()) ? dossierLocalService.getByRef(groupId, input.getReferenceUid()) : null; if (originality == DossierTerm.ORIGINALITY_DVCTT) { online = true; } boolean flagOldDossier = false; String registerBookCode = (option != null ? (Validator.isNotNull(option.getRegisterBookCode()) ? option.getRegisterBookCode() : StringPool.BLANK) : StringPool.BLANK); String registerBookName = (Validator.isNotNull(registerBookCode) ? getDictItemName(groupId, REGISTER_BOOK, registerBookCode) : StringPool.BLANK); _log.debug("CREATE DOSSIER 2: " + (System.currentTimeMillis() - start) + " ms"); if (oldRefDossier != null) { dossier = oldRefDossier; dossier.setSubmitDate(new Date()); ServiceProcess serviceProcess = process; double durationCount = 0; int durationUnit = 0; if (serviceProcess != null ) { durationCount = serviceProcess.getDurationCount(); durationUnit = serviceProcess.getDurationUnit(); dossier.setDurationCount(durationCount); dossier.setDurationUnit(durationUnit); } if (durationCount > 0) { Date dueDate = HolidayUtils.getDueDate(new Date(), durationCount, durationUnit, groupId); dossier.setDueDate(dueDate); } } else if (oldDossiers.size() > 0) { flagOldDossier = true; dossier = oldDossiers.get(0); dossier.setApplicantName(input.getApplicantName()); dossier.setApplicantNote(input.getApplicantNote()); dossier.setApplicantIdNo(input.getApplicantIdNo()); dossier.setAddress(input.getAddress()); dossier.setContactEmail(input.getContactEmail()); dossier.setContactName(input.getContactName()); dossier.setContactTelNo(input.getContactTelNo()); dossier.setDelegateName(input.getDelegateName()); dossier.setDelegateEmail(input.getDelegateEmail()); dossier.setDelegateAddress(input.getDelegateAddress()); dossier.setPostalAddress(input.getPostalAddress()); dossier.setPostalCityCode(input.getPostalCityCode()); dossier.setPostalCityName(postalCityName); dossier.setPostalTelNo(input.getPostalTelNo()); dossier.setPostalServiceCode(input.getPostalServiceCode()); dossier.setPostalServiceName(input.getPostalServiceName()); dossier.setPostalDistrictCode(input.getPostalDistrictCode()); dossier.setPostalDistrictName(input.getPostalDistrictName()); dossier.setPostalWardCode(input.getPostalWardCode()); dossier.setPostalWardName(input.getPostalWardName()); dossier.setPostalTelNo(input.getPostalTelNo()); dossier.setViaPostal(viaPostal); dossier.setOriginDossierNo(input.getOriginDossierNo()); dossier.setRegisterBookCode(registerBookCode); dossier.setRegisterBookName(registerBookName); dossier.setSampleCount(sampleCount); dossier.setServiceCode(input.getServiceCode()); dossier.setGovAgencyCode(input.getGovAgencyCode()); dossier.setDossierTemplateNo(input.getDossierTemplateNo()); updateDelegateApplicant(dossier, input); // dossier.setDossierNo(input.getDossierNo()); dossier.setSubmitDate(new Date()); // ServiceProcess serviceProcess = ServiceProcessLocalServiceUtil.fetchServiceProcess(serviceProcessId); ServiceProcess serviceProcess = process; double durationCount = 0; int durationUnit = 0; if (serviceProcess != null ) { durationCount = serviceProcess.getDurationCount(); durationUnit = serviceProcess.getDurationUnit(); dossier.setDurationCount(durationCount); dossier.setDurationUnit(durationUnit); } if (durationCount > 0) { Date dueDate = HolidayUtils.getDueDate(new Date(), durationCount, durationUnit, groupId); dossier.setDueDate(dueDate); } dossier.setOnline(online); if (Validator.isNotNull(input.getDossierName())) dossier.setDossierName(input.getDossierName()); if (serviceProcess != null) { dossier.setProcessNo(serviceProcess.getProcessNo()); } // dossier = DossierLocalServiceUtil.updateDossier(dossier); } else { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"); Date appIdDate = null; try { appIdDate = sdf.parse(input.getApplicantIdDate()); } catch (Exception e) { _log.debug(e); } dossier = dossierLocalService.initDossier(groupId, 0l, referenceUid, counter, input.getServiceCode(), serviceName, input.getGovAgencyCode(), govAgencyName, input.getApplicantName(), input.getApplicantIdType(), input.getApplicantIdNo(), appIdDate, input.getAddress(), input.getCityCode(), cityName, input.getDistrictCode(), districtName, input.getWardCode(), wardName, input.getContactName(), input.getContactTelNo(), input.getContactEmail(), input.getDossierTemplateNo(), password, viaPostal, input.getPostalAddress(), input.getPostalCityCode(), postalCityName, input.getPostalTelNo(), online, process.getDirectNotification(), input.getApplicantNote(), Integer.valueOf(input.getOriginality()), service, process, option, serviceContext); dossier.setDelegateName(input.getDelegateName()); dossier.setDelegateEmail(input.getDelegateEmail()); dossier.setDelegateAddress(input.getDelegateAddress()); if (Validator.isNotNull(input.getDossierName())) { dossier.setDossierName(input.getDossierName()); } else { dossier.setDossierName(serviceName); } dossier.setPostalCityName(postalCityName); dossier.setPostalTelNo(input.getPostalTelNo()); dossier.setPostalServiceCode(input.getPostalServiceCode()); dossier.setPostalServiceName(input.getPostalServiceName()); dossier.setPostalDistrictCode(input.getPostalDistrictCode()); dossier.setPostalDistrictName(input.getPostalDistrictName()); dossier.setPostalWardCode(input.getPostalWardCode()); dossier.setPostalWardName(input.getPostalWardName()); dossier.setOriginDossierNo(input.getOriginDossierNo()); dossier.setRegisterBookCode(registerBookCode); dossier.setRegisterBookName(registerBookName); dossier.setSampleCount(sampleCount); updateDelegateApplicant(dossier, input); if (process != null) { dossier.setProcessNo(process.getProcessNo()); } // dossier = DossierLocalServiceUtil.updateDossier(dossier); } _log.debug("CREATE DOSSIER 3: " + (System.currentTimeMillis() - start) + " ms"); if (originality != DossierTerm.ORIGINALITY_LIENTHONG) { Applicant applicant = ApplicantLocalServiceUtil.fetchByMappingID(serviceContext.getUserId()); if (applicant != null) { updateApplicantInfo(dossier, applicant.getApplicantIdDate(), applicant.getApplicantIdNo(), applicant.getApplicantIdType(), applicant.getApplicantName(), applicant.getAddress(), applicant.getCityCode(), applicant.getCityName(), applicant.getDistrictCode(), applicant.getDistrictName(), applicant.getWardCode(), applicant.getWardName(), applicant.getContactEmail(), applicant.getContactTelNo() ); } } if (Validator.isNull(dossier)) { throw new NotFoundException("Cant add DOSSIER"); } _log.debug("CREATE DOSSIER 4: " + (System.currentTimeMillis() - start) + " ms"); //Create DossierMark _log.debug("flagOldDossier: "+flagOldDossier); _log.debug("originality: "+originality); if ((originality == DossierTerm.ORIGINALITY_MOTCUA || originality == DossierTerm.ORIGINALITY_LIENTHONG) && !flagOldDossier) { String templateNo = dossier.getDossierTemplateNo(); _log.debug("templateNo: "+templateNo); if (Validator.isNotNull(templateNo)) { List<DossierPart> partList = dossierPartLocalService.getByTemplateNo(groupId, templateNo); // _log.info("partList: "+partList); if (partList != null && partList.size() > 0) { _log.debug("partList.size(): "+partList.size()); _log.debug("CREATE DOSSIER 4.1: " + (System.currentTimeMillis() - start) + " ms"); org.opencps.dossiermgt.input.model.DossierMarkBatchModel[] marks = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel[partList.size()]; int count = 0; List<DossierMark> lstMarks = dossierMarkLocalService.getDossierMarks(groupId, dossier.getDossierId()); Map<String, DossierMark> mapMarks = new HashMap<>(); for (DossierMark dm : lstMarks) { mapMarks.put(dm.getDossierPartNo(), dm); } for (DossierPart dossierPart : partList) { int fileMark = dossierPart.getFileMark(); String dossierPartNo = dossierPart.getPartNo(); org.opencps.dossiermgt.input.model.DossierMarkBatchModel model = new org.opencps.dossiermgt.input.model.DossierMarkBatchModel(); model.setDossierId(dossier.getDossierId()); model.setDossierPartNo(dossierPartNo); model.setFileCheck(0); model.setFileMark(fileMark); model.setFileComment(StringPool.BLANK); marks[count++] = model; // DossierMarkLocalServiceUtil.addDossierMark(groupId, dossier.getDossierId(), dossierPartNo, // fileMark, 0, StringPool.BLANK, serviceContext); } dossierMarkLocalService.addBatchDossierMark(groupId, marks, mapMarks, serviceContext); _log.debug("CREATE DOSSIER 4.2: " + (System.currentTimeMillis() - start) + " ms"); } } } //Create dossier user List<DossierUser> lstDus = dossierUserLocalService.findByDID(dossier.getDossierId()); List<ServiceProcessRole> lstProcessRoles = serviceProcessRoleLocalService.findByS_P_ID(process.getServiceProcessId()); if (lstDus.size() == 0) { DossierUserActions duActions = new DossierUserActionsImpl(); // duActions.initDossierUser(groupId, dossier); duActions.initDossierUser(groupId, dossier, process, lstProcessRoles); } if (originality == DossierTerm.ORIGINALITY_DVCTT) { dossierUserLocalService.addDossierUser(groupId, dossier.getDossierId(), userId, 1, true); } _log.debug("CREATE DOSSIER 5: " + (System.currentTimeMillis() - start) + " ms"); // DossierLocalServiceUtil.updateDossier(dossier); if (dossier != null) { // long notificationQueueId = CounterLocalServiceUtil.increment(NotificationQueue.class.getName()); NotificationQueue queue = NotificationQueueLocalServiceUtil.createNotificationQueue(notificationQueueId); //Process add notification queue Date now = new Date(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) + 1); queue.setCreateDate(now); queue.setModifiedDate(now); queue.setGroupId(groupId); queue.setCompanyId(company.getCompanyId()); queue.setNotificationType(NotificationType.DOSSIER_01); queue.setClassName(Dossier.class.getName()); queue.setClassPK(String.valueOf(dossier.getPrimaryKey())); queue.setToUsername(dossier.getUserName()); queue.setToUserId(dossier.getUserId()); queue.setToEmail(dossier.getContactEmail()); queue.setToTelNo(dossier.getContactTelNo()); JSONObject payload = JSONFactoryUtil.createJSONObject(); try { // _log.info("START PAYLOAD: "); payload.put( "Dossier", JSONFactoryUtil.createJSONObject( JSONFactoryUtil.looseSerialize(dossier))); } catch (JSONException parse) { _log.error(parse); } // _log.info("payloadTest: "+payload.toJSONString()); queue.setPayload(payload.toJSONString()); queue.setExpireDate(cal.getTime()); NotificationQueueLocalServiceUtil.addNotificationQueue(queue); } _log.debug("CREATE DOSSIER 6: " + (System.currentTimeMillis() - start) + " ms"); //Add to dossier user based on service process role createDossierUsers(groupId, dossier, process, lstProcessRoles); _log.debug("CREATE DOSSIER 7: " + (System.currentTimeMillis() - start) + " ms"); dossierLocalService.updateDossier(dossier); _log.debug("CREATE DOSSIER 8: " + (System.currentTimeMillis() - start) + " ms"); return dossier; } } public static final String GOVERNMENT_AGENCY = "GOVERNMENT_AGENCY"; public static final String ADMINISTRATIVE_REGION = "ADMINISTRATIVE_REGION"; public static final String VNPOST_CITY_CODE = "VNPOST_CITY_CODE"; public static final String REGISTER_BOOK = "REGISTER_BOOK"; private static final long VALUE_CONVERT_DATE_TIMESTAMP = 1000 * 60 * 60 * 24; private static final long VALUE_CONVERT_HOUR_TIMESTAMP = 1000 * 60 * 60; private static ProcessAction getProcessAction(long groupId, Dossier dossier, String actionCode, long serviceProcessId) throws PortalException { //_log.debug("GET PROCESS ACTION____"); ProcessAction action = null; DossierAction dossierAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId()); try { List<ProcessAction> actions = ProcessActionLocalServiceUtil.getByActionCode(groupId, actionCode, serviceProcessId); //_log.debug("GET PROCESS ACTION____" + groupId + "," + actionCode + "," + serviceProcessId); String dossierStatus = dossier.getDossierStatus(); String dossierSubStatus = dossier.getDossierSubStatus(); String preStepCode; for (ProcessAction act : actions) { preStepCode = act.getPreStepCode(); //_log.debug("LamTV_preStepCode: "+preStepCode); ProcessStep step = ProcessStepLocalServiceUtil.fetchBySC_GID(preStepCode, groupId, serviceProcessId); // _log.info("LamTV_ProcessStep: "+step); if (Validator.isNull(step) && dossierAction == null) { action = act; break; } else { String stepStatus = step != null ? step.getDossierStatus() : StringPool.BLANK; String stepSubStatus = step != null ? step.getDossierSubStatus() : StringPool.BLANK; boolean flagCheck = false; if (dossierAction != null) { if (act.getPreStepCode().equals(dossierAction.getStepCode())) { flagCheck = true; } } else { flagCheck = true; } //_log.debug("LamTV_preStepCode: "+stepStatus + "," + stepSubStatus + "," + dossierStatus + "," + dossierSubStatus + "," + act.getPreCondition() + "," + flagCheck); if (stepStatus.contentEquals(dossierStatus) && StringUtil.containsIgnoreCase(stepSubStatus, dossierSubStatus) && flagCheck) { if (Validator.isNotNull(act.getPreCondition()) && DossierMgtUtils.checkPreCondition(act.getPreCondition().split(StringPool.COMMA), dossier)) { action = act; break; } else if (Validator.isNull(act.getPreCondition())) { action = act; break; } } } } } catch (Exception e) { //_log.debug("NOT PROCESS ACTION"); //_log.debug(e); } return action; } private Log _log = LogFactoryUtil.getLog(CPSDossierBusinessLocalServiceImpl.class); }
update working status
modules/backend-dossiermgt/backend-dossiermgt-service/src/main/java/org/opencps/dossiermgt/service/impl/CPSDossierBusinessLocalServiceImpl.java
update working status
<ide><path>odules/backend-dossiermgt/backend-dossiermgt-service/src/main/java/org/opencps/dossiermgt/service/impl/CPSDossierBusinessLocalServiceImpl.java <ide> // Get list user <ide> List<User> users = UserLocalServiceUtil.getRoleUsers(roleId); <ide> for (User user : users) { <del> Employee employee = EmployeeLocalServiceUtil.fetchByFB_MUID(userId); <add> Employee employee = EmployeeLocalServiceUtil.fetchByFB_MUID(user.getUserId()); <ide> //_log.debug("Employee : " + employee); <ide> if (employee != null && employee.getWorkingStatus() == 1) { <ide> List<DossierAction> lstDoneActions = dossierActionLocalService
JavaScript
mit
dcac0bce042ec6829b2734c832ed4b1a48227014
0
baiyanghese/processing-js,corbanbrook/processing-js,annasob/processing-js,jaredly/processing-js,jeresig/processing-js,baiyanghese/processing-js,corbanbrook/processing-js,corbanbrook/processing-js,jeresig/processing-js,guazipi/processing-js,kevinb7/processing-js,annasob/processing-js,guazipi/processing-js,annasob/processing-js,kevinb7/processing-js,jaredly/processing-js
/* P R O C E S S I N G . J S - @VERSION@ a port of the Processing visualization language License : MIT Developer : John Resig: http://ejohn.org Web Site : http://processingjs.org Java Version : http://processing.org Github Repo. : http://github.com/jeresig/processing-js Bug Tracking : http://processing-js.lighthouseapp.com Mozilla POW! : http://wiki.Mozilla.org/Education/Projects/ProcessingForTheWeb Maintained by : Seneca: http://zenit.senecac.on.ca/wiki/index.php/Processing.js Hyper-Metrix: http://hyper-metrix.com/#Processing BuildingSky: http://weare.buildingsky.net/pages/processing-js */ (function() { var Processing = this.Processing = function Processing(curElement, aCode) { var p = this; p.pjs = { imageCache: { pending: 0 } }; // by default we have an empty imageCache, no more. p.name = 'Processing.js Instance'; // Set Processing defaults / environment variables p.use3DContext = false; // default '2d' canvas context p.canvas = curElement; // Glyph path storage for textFonts p.glyphTable = {}; // Global vars for tracking mouse position p.pmouseX = 0; p.pmouseY = 0; p.mouseX = 0; p.mouseY = 0; p.mouseButton = 0; p.mouseDown = false; p.mouseScroll = 0; // Undefined event handlers to be replaced by user when needed p.mouseClicked = undefined; p.mouseDragged = undefined; p.mouseMoved = undefined; p.mousePressed = undefined; p.mouseReleased = undefined; p.mouseScrolled = undefined; p.key = undefined; p.keyPressed = undefined; p.keyReleased = undefined; p.keyTyped = undefined; p.draw = undefined; p.setup = undefined; // The height/width of the canvas p.width = curElement.width - 0; p.height = curElement.height - 0; // The current animation frame p.frameCount = 0; // Color modes p.RGB = 1; p.ARGB = 2; p.HSB = 3; p.ALPHA = 4; p.CMYK = 5; // Renderers p.P2D = 1; p.JAVA2D = 1; p.WEBGL = 2; p.P3D = 2; p.OPENGL = 2; p.EPSILON = 0.0001; p.MAX_FLOAT = 3.4028235e+38; p.MIN_FLOAT = -3.4028235e+38; p.MAX_INT = 2147483647; p.MIN_INT = -2147483648; p.PI = Math.PI; p.TWO_PI = 2 * p.PI; p.HALF_PI = p.PI / 2; p.THIRD_PI = p.PI / 3; p.QUARTER_PI = p.PI / 4; p.DEG_TO_RAD = p.PI / 180; p.RAD_TO_DEG = 180 / p.PI; p.WHITESPACE = " \t\n\r\f\u00A0"; // Filter/convert types p.BLUR = 11; p.GRAY = 12; p.INVERT = 13; p.OPAQUE = 14; p.POSTERIZE = 15; p.THRESHOLD = 16; p.ERODE = 17; p.DILATE = 18; // Blend modes p.REPLACE = 0; p.BLEND = 1 << 0; p.ADD = 1 << 1; p.SUBTRACT = 1 << 2; p.LIGHTEST = 1 << 3; p.DARKEST = 1 << 4; p.DIFFERENCE = 1 << 5; p.EXCLUSION = 1 << 6; p.MULTIPLY = 1 << 7; p.SCREEN = 1 << 8; p.OVERLAY = 1 << 9; p.HARD_LIGHT = 1 << 10; p.SOFT_LIGHT = 1 << 11; p.DODGE = 1 << 12; p.BURN = 1 << 13; // Color component bit masks p.ALPHA_MASK = 0xff000000; p.RED_MASK = 0x00ff0000; p.GREEN_MASK = 0x0000ff00; p.BLUE_MASK = 0x000000ff; // Projection matrices p.CUSTOM = 0; p.ORTHOGRAPHIC = 2; p.PERSPECTIVE = 3; // Shapes p.POINT = 2; p.POINTS = 2; p.LINE = 4; p.LINES = 4; p.TRIANGLE = 8; p.TRIANGLES = 9; p.TRIANGLE_STRIP = 10; p.TRIANGLE_FAN = 11; p.QUAD = 16; p.QUADS = 16; p.QUAD_STRIP = 17; p.POLYGON = 20; p.PATH = 21; p.RECT = 30; p.ELLIPSE = 31; p.ARC = 32; p.SPHERE = 40; p.BOX = 41; // Shape closing modes p.OPEN = 1; p.CLOSE = 2; // Shape drawing modes p.CORNER = 0; // Draw mode convention to use (x, y) to (width, height) p.CORNERS = 1; // Draw mode convention to use (x1, y1) to (x2, y2) coordinates p.RADIUS = 2; // Draw mode from the center, and using the radius p.CENTER_RADIUS = 2; // Deprecated! Use RADIUS instead p.CENTER = 3; // Draw from the center, using second pair of values as the diameter p.DIAMETER = 3; // Synonym for the CENTER constant. Draw from the center p.CENTER_DIAMETER = 3; // Deprecated! Use DIAMETER instead // Text vertical alignment modes p.BASELINE = 0; // Default vertical alignment for text placement p.TOP = 101; // Align text to the top p.BOTTOM = 102; // Align text from the bottom, using the baseline // UV Texture coordinate modes p.NORMAL = 1; p.NORMALIZE = 1; p.IMAGE = 2; // Text placement modes p.MODEL = 4; p.SHAPE = 5; // Stroke modes p.SQUARE = 'butt'; p.ROUND = 'round'; p.PROJECT = 'square'; p.MITER = 'miter'; p.BEVEL = 'bevel'; // Lighting modes p.AMBIENT = 0; p.DIRECTIONAL = 1; //POINT = 2; Shared with Shape constant p.SPOT = 3; // Key constants // Both key and keyCode will be equal to these values p.BACKSPACE = 8; p.TAB = 9; p.ENTER = 10; p.RETURN = 13; p.ESC = 27; p.DELETE = 127; p.CODED = 0xffff; // p.key will be CODED and p.keyCode will be this value p.SHIFT = 16; p.CONTROL = 17; p.ALT = 18; p.UP = 38; p.RIGHT = 39; p.DOWN = 40; p.LEFT = 37; var codedKeys = [p.SHIFT, p.CONTROL, p.ALT, p.UP, p.RIGHT, p.DOWN, p.LEFT]; // Cursor types p.ARROW = 'default'; p.CROSS = 'crosshair'; p.HAND = 'pointer'; p.MOVE = 'move'; p.TEXT = 'text'; p.WAIT = 'wait'; p.NOCURSOR = "url('data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='), auto"; // Hints p.DISABLE_OPENGL_2X_SMOOTH = 1; p.ENABLE_OPENGL_2X_SMOOTH = -1; p.ENABLE_OPENGL_4X_SMOOTH = 2; p.ENABLE_NATIVE_FONTS = 3; p.DISABLE_DEPTH_TEST = 4; p.ENABLE_DEPTH_TEST = -4; p.ENABLE_DEPTH_SORT = 5; p.DISABLE_DEPTH_SORT = -5; p.DISABLE_OPENGL_ERROR_REPORT = 6; p.ENABLE_OPENGL_ERROR_REPORT = -6; p.ENABLE_ACCURATE_TEXTURES = 7; p.DISABLE_ACCURATE_TEXTURES = -7; p.HINT_COUNT = 10; // PJS defined constants p.SINCOS_LENGTH = parseInt(360 / 0.5, 10); p.FRAME_RATE = 0; p.focused = true; p.PRECISIONB = 15; // fixed point precision is limited to 15 bits!! p.PRECISIONF = 1 << p.PRECISIONB; p.PREC_MAXVAL = p.PRECISIONF - 1; p.PREC_ALPHA_SHIFT = 24 - p.PRECISIONB; p.PREC_RED_SHIFT = 16 - p.PRECISIONB; p.NORMAL_MODE_AUTO = 0; p.NORMAL_MODE_SHAPE = 1; p.NORMAL_MODE_VERTEX = 2; p.MAX_LIGHTS = 8; // "Private" variables used to maintain state var curContext, online = true, doFill = true, fillStyle = "rgba( 255, 255, 255, 1 )", doStroke = true, strokeStyle = "rgba( 204, 204, 204, 1 )", lineWidth = 1, loopStarted = false, refreshBackground = function() {}, doLoop = true, looping = 0, curRectMode = p.CORNER, curEllipseMode = p.CENTER, normalX = 0, normalY = 0, normalZ = 0, normalMode = p.NORMAL_MODE_AUTO, inDraw = false, curBackground = "rgba( 204, 204, 204, 1 )", curFrameRate = 60, curCursor = p.ARROW, oldCursor = curElement.style.cursor, curMsPerFrame = 1, curShape = p.POLYGON, curShapeCount = 0, curvePoints = [], curTightness = 0, curveDetail = 20, curveInited = false, colorModeA = 255, colorModeX = 255, colorModeY = 255, colorModeZ = 255, pathOpen = false, mousePressed = false, mouseDragging = false, keyPressed = false, curColorMode = p.RGB, curTint = function() {}, curTextSize = 12, curTextFont = "Arial", getLoaded = false, start = new Date().getTime(), timeSinceLastFPS = start, framesSinceLastFPS = 0, lastTextPos = [0, 0, 0], curveBasisMatrix, curveToBezierMatrix, curveDrawMatrix, bezierBasisInverse, bezierBasisMatrix, programObject3D, programObject2D, boxBuffer, boxNormBuffer, boxOutlineBuffer, sphereBuffer, lineBuffer, fillBuffer, pointBuffer; // User can only have MAX_LIGHTS lights var lightCount = 0; //sphere stuff var sphereDetailV = 0, sphereDetailU = 0, sphereX = [], sphereY = [], sphereZ = [], sinLUT = new Array(p.SINCOS_LENGTH), cosLUT = new Array(p.SINCOS_LENGTH), sphereVerts, sphereNorms; // Camera defaults and settings var cam, cameraInv, forwardTransform, reverseTransform, modelView, modelViewInv, userMatrixStack, inverseCopy, projection, manipulatingCamera = false, frustumMode = false, cameraFOV = 60 * (Math.PI / 180), cameraX = curElement.width / 2, cameraY = curElement.height / 2, cameraZ = cameraY / Math.tan(cameraFOV / 2), cameraNear = cameraZ / 10, cameraFar = cameraZ * 10, cameraAspect = curElement.width / curElement.height; var vertArray = [], isCurve = false, isBezier = false, firstVert = true; // Stores states for pushStyle() and popStyle(). var styleArray = new Array(0); // Vertices are specified in a counter-clockwise order // triangles are in this order: back, front, right, bottom, left, top var boxVerts = [0.5, 0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5]; var boxNorms = [0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0]; var boxOutlineVerts = [0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, -0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5]; // Vertex shader for points and lines var vertexShaderSource2D = "attribute vec3 Vertex;" + "uniform vec4 color;" + "uniform mat4 model;" + "uniform mat4 view;" + "uniform mat4 projection;" + "void main(void) {" + " gl_FrontColor = color;" + " gl_Position = projection * view * model * vec4(Vertex, 1.0);" + "}"; var fragmentShaderSource2D = "void main(void){" + " gl_FragColor = gl_Color;" + "}"; // Vertex shader for boxes and spheres var vertexShaderSource3D = "attribute vec3 Vertex;" + "attribute vec3 Normal;" + "uniform vec4 color;" + "uniform bool usingMat;" + "uniform vec3 specular;" + "uniform vec3 mat_emissive;" + "uniform vec3 mat_ambient;" + "uniform vec3 mat_specular;" + "uniform float shininess;" + "uniform mat4 model;" + "uniform mat4 view;" + "uniform mat4 projection;" + "uniform mat4 normalTransform;" + "uniform int lightCount;" + "uniform vec3 falloff;" + "struct Light {" + " bool dummy;" + " int type;" + " vec3 color;" + " vec3 position;" + " vec3 direction;" + " float angle;" + " vec3 halfVector;" + " float concentration;" + "};" + "uniform Light lights[8];" + "void AmbientLight( inout vec3 totalAmbient, in vec3 ecPos, in Light light ) {" + // Get the vector from the light to the vertex // Get the distance from the current vector to the light position " float d = length( light.position - ecPos );" + " float attenuation = 1.0 / ( falloff[0] + ( falloff[1] * d ) + ( falloff[2] * d * d ));" + " totalAmbient += light.color * attenuation;" + "}" + "void DirectionalLight( inout vec3 col, in vec3 ecPos, inout vec3 spec, in vec3 vertNormal, in Light light ) {" + " float powerfactor = 0.0;" + " float nDotVP = max(0.0, dot( vertNormal, light.position ));" + " float nDotVH = max(0.0, dot( vertNormal, normalize( light.position-ecPos )));" + " if( nDotVP != 0.0 ){" + " powerfactor = pow( nDotVH, shininess );" + " }" + " col += light.color * nDotVP;" + " spec += specular * powerfactor;" + "}" + "void PointLight( inout vec3 col, inout vec3 spec, in vec3 vertNormal, in vec3 ecPos, in vec3 eye, in Light light ) {" + " float powerfactor;" + // Get the vector from the light to the vertex " vec3 VP = light.position - ecPos;" + // Get the distance from the current vector to the light position " float d = length( VP ); " + // Normalize the light ray so it can be used in the dot product operation. " VP = normalize( VP );" + " float attenuation = 1.0 / ( falloff[0] + ( falloff[1] * d ) + ( falloff[2] * d * d ));" + " float nDotVP = max( 0.0, dot( vertNormal, VP ));" + " vec3 halfVector = normalize( VP + eye );" + " float nDotHV = max( 0.0, dot( vertNormal, halfVector ));" + " if( nDotVP == 0.0) {" + " powerfactor = 0.0;" + " }" + " else{" + " powerfactor = pow( nDotHV, shininess );" + " }" + " spec += specular * powerfactor * attenuation;" + " col += light.color * nDotVP * attenuation;" + "}" + /* */ "void SpotLight( inout vec3 col, inout vec3 spec, in vec3 vertNormal, in vec3 ecPos, in vec3 eye, in Light light ) {" + " float spotAttenuation;" + " float powerfactor;" + // calculate the vector from the current vertex to the light. " vec3 VP = light.position - ecPos; " + " vec3 ldir = normalize( light.direction );" + // get the distance from the spotlight and the vertex " float d = length( VP );" + " VP = normalize( VP );" + " float attenuation = 1.0 / ( falloff[0] + ( falloff[1] * d ) + ( falloff[2] * d * d ) );" + // dot product of the vector from vertex to light and light direction. " float spotDot = dot( VP, ldir );" + // if the vertex falls inside the cone " if( spotDot < cos( light.angle ) ) {" + " spotAttenuation = pow( spotDot, light.concentration );" + " }" + " else{" + " spotAttenuation = 1.0;" + " }" + " attenuation *= spotAttenuation;" + " float nDotVP = max( 0.0, dot( vertNormal, VP ));" + " vec3 halfVector = normalize( VP + eye );" + " float nDotHV = max( 0.0, dot( vertNormal, halfVector ));" + " if( nDotVP == 0.0 ) {" + " powerfactor = 0.0;" + " }" + " else {" + " powerfactor = pow( nDotHV, shininess );" + " }" + " spec += specular * powerfactor * attenuation;" + " col += light.color * nDotVP * attenuation;" + "}" + "void main(void) {" + " vec3 finalAmbient = vec3( 0.0, 0.0, 0.0 );" + " vec3 finalDiffuse = vec3( 0.0, 0.0, 0.0 );" + " vec3 finalSpecular = vec3( 0.0, 0.0, 0.0 );" + " vec3 norm = vec3( normalTransform * vec4( Normal, 0.0 ) );" + " vec4 ecPos4 = view * model * vec4(Vertex,1.0);" + " vec3 ecPos = (vec3(ecPos4))/ecPos4.w;" + " vec3 eye = vec3( 0.0, 0.0, 1.0 );" + // If there were no lights this draw call, just use the // assigned fill color of the shape and the specular value " if( lightCount == 0 ) {" + " gl_FrontColor = color + vec4(mat_specular,1.0);" + " }" + " else {" + " for( int i = 0; i < lightCount; i++ ) {" + " if( lights[i].type == 0 ) {" + " AmbientLight( finalAmbient, ecPos, lights[i] );" + " }" + " else if( lights[i].type == 1 ) {" + " DirectionalLight( finalDiffuse,ecPos, finalSpecular, norm, lights[i] );" + " }" + " else if( lights[i].type == 2 ) {" + " PointLight( finalDiffuse, finalSpecular, norm, ecPos, eye, lights[i] );" + " }" + " else if( lights[i].type == 3 ) {" + " SpotLight( finalDiffuse, finalSpecular, norm, ecPos, eye, lights[i] );" + " }" + " }" + " if( usingMat == false ) {" + " gl_FrontColor = vec4( " + " vec3(color) * finalAmbient +" + " vec3(color) * finalDiffuse +" + " vec3(color) * finalSpecular," + " color[3] );" + " }" + " else{" + " gl_FrontColor = vec4( " + " mat_emissive + " + " (vec3(color) * mat_ambient * finalAmbient) + " + " (vec3(color) * finalDiffuse) + " + " (mat_specular * finalSpecular), " + " color[3] );" + " }" + " }" + " gl_Position = projection * view * model * vec4( Vertex, 1.0 );" + "}"; var fragmentShaderSource3D = "void main(void){" + " gl_FragColor = gl_Color;" + "}"; // Wrapper to easily deal with array names changes. var newWebGLArray = function(data) { return new WebGLFloatArray(data); }; var imageModeCorner = function imageModeCorner(x, y, w, h, whAreSizes) { return { x: x, y: y, w: w, h: h }; }; var imageModeConvert = imageModeCorner; var imageModeCorners = function imageModeCorners(x, y, w, h, whAreSizes) { return { x: x, y: y, w: whAreSizes ? w : w - x, h: whAreSizes ? h : h - y }; }; var imageModeCenter = function imageModeCenter(x, y, w, h, whAreSizes) { return { x: x - w / 2, y: y - h / 2, w: w, h: h }; }; var createProgramObject = function(curContext, vetexShaderSource, fragmentShaderSource) { var vertexShaderObject = curContext.createShader(curContext.VERTEX_SHADER); curContext.shaderSource(vertexShaderObject, vetexShaderSource); curContext.compileShader(vertexShaderObject); if (!curContext.getShaderParameter(vertexShaderObject, curContext.COMPILE_STATUS)) { throw curContext.getShaderInfoLog(vertexShaderObject); } var fragmentShaderObject = curContext.createShader(curContext.FRAGMENT_SHADER); curContext.shaderSource(fragmentShaderObject, fragmentShaderSource); curContext.compileShader(fragmentShaderObject); if (!curContext.getShaderParameter(fragmentShaderObject, curContext.COMPILE_STATUS)) { throw curContext.getShaderInfoLog(fragmentShaderObject); } var programObject = curContext.createProgram(); curContext.attachShader(programObject, vertexShaderObject); curContext.attachShader(programObject, fragmentShaderObject); curContext.linkProgram(programObject); if (!curContext.getProgramParameter(programObject, curContext.LINK_STATUS)) { throw "Error linking shaders."; } return programObject; }; //////////////////////////////////////////////////////////////////////////// // Char handling //////////////////////////////////////////////////////////////////////////// var charMap = {}; var Char = function Char(chr) { if (typeof chr === 'string' && chr.length === 1) { this.code = chr.charCodeAt(0); } else { this.code = NaN; } return (typeof charMap[this.code] === 'undefined') ? charMap[this.code] = this : charMap[this.code]; }; Char.prototype.toString = function() { return String.fromCharCode(this.code); }; Char.prototype.valueOf = function() { return this.code; }; //////////////////////////////////////////////////////////////////////////// // PVector //////////////////////////////////////////////////////////////////////////// var PVector = function(x, y, z) { this.x = x || 0; this.y = y || 0; this.z = z || 0; }, createPVectorMethod = function(method) { return function(v1, v2) { var v = v1.get(); v[method](v2); return v; }; }, createSimplePVectorMethod = function(method) { return function(v1, v2) { return v1[method](v2); }; }, simplePVMethods = "dist dot cross".split(" "), method = simplePVMethods.length; PVector.angleBetween = function(v1, v2) { return Math.acos(v1.dot(v2) / (v1.mag() * v2.mag())); }; // Common vector operations for PVector PVector.prototype = { set: function(v, y, z) { if (arguments.length === 1) { this.set(v.x || v[0], v.y || v[1], v.z || v[2]); } else { this.x = v; this.y = y; this.z = z; } }, get: function() { return new PVector(this.x, this.y, this.z); }, mag: function() { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); }, add: function(v, y, z) { if (arguments.length === 3) { this.x += v; this.y += y; this.z += z; } else if (arguments.length === 1) { this.x += v.x; this.y += v.y; this.z += v.z; } }, sub: function(v, y, z) { if (arguments.length === 3) { this.x -= v; this.y -= y; this.z -= z; } else if (arguments.length === 1) { this.x -= v.x; this.y -= v.y; this.z -= v.z; } }, mult: function(v) { if (typeof v === 'number') { this.x *= v; this.y *= v; this.z *= v; } else if (typeof v === 'object') { this.x *= v.x; this.y *= v.y; this.z *= v.z; } }, div: function(v) { if (typeof v === 'number') { this.x /= v; this.y /= v; this.z /= v; } else if (typeof v === 'object') { this.x /= v.x; this.y /= v.y; this.z /= v.z; } }, dist: function(v) { var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; return Math.sqrt(dx * dx + dy * dy + dz * dz); }, dot: function(v, y, z) { var num; if (arguments.length === 3) { num = this.x * v + this.y * y + this.z * z; } else if (arguments.length === 1) { num = this.x * v.x + this.y * v.y + this.z * v.z; } return num; }, cross: function(v) { var crossX = this.y * v.z - v.y * this.z, crossY = this.z * v.x - v.z * this.x, crossZ = this.x * v.y - v.x * this.y; return new PVector(crossX, crossY, crossZ); }, normalize: function() { var m = this.mag(); if (m > 0) { this.div(m); } }, limit: function(high) { if (this.mag() > high) { this.normalize(); this.mult(high); } }, heading2D: function() { var angle = Math.atan2(-this.y, this.x); return -angle; }, toString: function() { return "[" + this.x + ", " + this.y + ", " + this.z + "]"; }, array: function() { return [this.x, this.y, this.z]; } }; while (method--) { PVector[simplePVMethods[method]] = createSimplePVectorMethod(simplePVMethods[method]); } for (method in PVector.prototype) { if (PVector.prototype.hasOwnProperty(method) && !PVector.hasOwnProperty(method)) { PVector[method] = createPVectorMethod(method); } } p.PVector = PVector; //////////////////////////////////////////////////////////////////////////// // 2D Matrix //////////////////////////////////////////////////////////////////////////// /* Helper function for printMatrix(). Finds the largest scalar in the matrix, then number of digits left of the decimal. Call from PMatrix2D and PMatrix3D's print() function. */ var printMatrixHelper = function printMatrixHelper(elements) { var big = 0; for (var i = 0; i < elements.length; i++) { if (i !== 0) { big = Math.max(big, Math.abs(elements[i])); } else { big = Math.abs(elements[i]); } } var digits = (big + "").indexOf("."); if (digits === 0) { digits = 1; } else if (digits === -1) { digits = (big + "").length; } return digits; }; var PMatrix2D = function() { if (arguments.length === 0) { this.reset(); } else if (arguments.length === 1 && arguments[0] instanceof PMatrix2D) { this.set(arguments[0].array()); } else if (arguments.length === 6) { this.set(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]); } }; PMatrix2D.prototype = { set: function() { if (arguments.length === 6) { var a = arguments; this.set([a[0], a[1], a[2], a[3], a[4], a[5]]); } else if (arguments.length === 1 && arguments[0] instanceof PMatrix2D) { this.elements = arguments[0].array(); } else if (arguments.length === 1 && arguments[0] instanceof Array) { this.elements = arguments[0].slice(); } }, get: function() { var outgoing = new PMatrix2D(); outgoing.set(this.elements); return outgoing; }, reset: function() { this.set([1, 0, 0, 0, 1, 0]); }, // Returns a copy of the element values. array: function array() { return this.elements.slice(); }, translate: function(tx, ty) { this.elements[2] = tx * this.elements[0] + ty * this.elements[1] + this.elements[2]; this.elements[5] = tx * this.elements[3] + ty * this.elements[4] + this.elements[5]; }, // Does nothing in Processing. transpose: function() { }, mult: function(source, target) { var x, y; if (source instanceof PVector) { x = source.x; y = source.y; if (!target) { target = new PVector(); } } else if (source instanceof Array) { x = source[0]; y = source[1]; if (!target) { target = []; } } if (target instanceof Array) { target[0] = this.elements[0] * x + this.elements[1] * y + this.elements[2]; target[1] = this.elements[3] * x + this.elements[4] * y + this.elements[5]; } else if (target instanceof PVector) { target.x = this.elements[0] * x + this.elements[1] * y + this.elements[2]; target.y = this.elements[3] * x + this.elements[4] * y + this.elements[5]; target.z = 0; } return target; }, multX: function(x, y) { return x * this.elements[0] + y * this.elements[1] + this.elements[2]; }, multY: function(x, y) { return x * this.elements[3] + y * this.elements[4] + this.elements[5]; }, skewX: function(angle) { this.apply(1, 0, 1, angle, 0, 0); }, skewY: function(angle) { this.apply(1, 0, 1, 0, angle, 0); }, determinant: function() { return this.elements[0] * this.elements[4] - this.elements[1] * this.elements[3]; }, invert: function() { var d = this.determinant(); if ( Math.abs( d ) > p.FLOAT_MIN ) { var old00 = this.elements[0]; var old01 = this.elements[1]; var old02 = this.elements[2]; var old10 = this.elements[3]; var old11 = this.elements[4]; var old12 = this.elements[5]; this.elements[0] = old11 / d; this.elements[3] = -old10 / d; this.elements[1] = -old01 / d; this.elements[1] = old00 / d; this.elements[2] = (old01 * old12 - old11 * old02) / d; this.elements[5] = (old10 * old02 - old00 * old12) / d; return true; } return false; }, scale: function(sx, sy) { if (sx && !sy) { sy = sx; } if (sx && sy) { this.elements[0] *= sx; this.elements[1] *= sy; this.elements[3] *= sx; this.elements[4] *= sy; } }, apply: function() { if (arguments.length === 1 && arguments[0] instanceof PMatrix2D) { this.apply(arguments[0].array()); } else if (arguments.length === 6) { var a = arguments; this.apply([a[0], a[1], a[2], a[3], a[4], a[5]]); } else if (arguments.length === 1 && arguments[0] instanceof Array) { var source = arguments[0]; var result = [0, 0, this.elements[2], 0, 0, this.elements[5]]; var e = 0; for (var row = 0; row < 2; row++) { for (var col = 0; col < 3; col++, e++) { result[e] += this.elements[row * 3 + 0] * source[col + 0] + this.elements[row * 3 + 1] * source[col + 3]; } } this.elements = result.slice(); } }, preApply: function() { if (arguments.length === 1 && arguments[0] instanceof PMatrix2D) { this.preApply(arguments[0].array()); } else if (arguments.length === 6) { var a = arguments; this.preApply([a[0], a[1], a[2], a[3], a[4], a[5]]); } else if (arguments.length === 1 && arguments[0] instanceof Array) { var source = arguments[0]; var result = [0, 0, source[2], 0, 0, source[5]]; result[2]= source[2] + this.elements[2] * source[0] + this.elements[5] * source[1]; result[5]= source[5] + this.elements[2] * source[3] + this.elements[5] * source[4]; result[0] = this.elements[0] * source[0] + this.elements[3] * source[1]; result[3] = this.elements[0] * source[3] + this.elements[3] * source[4]; result[1] = this.elements[1] * source[0] + this.elements[4] * source[1]; result[4] = this.elements[1] * source[3] + this.elements[4] * source[4]; this.elements = result.slice(); } }, rotate: function(angle) { var c = Math.cos(angle); var s = Math.sin(angle); var temp1 = this.elements[0]; var temp2 = this.elements[1]; this.elements[0] = c * temp1 + s * temp2; this.elements[1] = -s * temp1 + c * temp2; temp1 = this.elements[3]; temp2 = this.elements[4]; this.elements[3] = c * temp1 + s * temp2; this.elements[4] = -s * temp1 + c * temp2; }, rotateZ: function(angle) { this.rotate(angle); }, print: function() { var digits = printMatrixHelper(this.elements); var output = ""; output += p.nfs(this.elements[0], digits, 4) + " " + p.nfs(this.elements[1], digits, 4) + " " + p.nfs(this.elements[2], digits, 4) + "\n"; output += p.nfs(this.elements[3], digits, 4) + " " + p.nfs(this.elements[4], digits, 4) + " " + p.nfs(this.elements[5], digits, 4) + "\n\n"; p.println(output); } }; //////////////////////////////////////////////////////////////////////////// // PMatrix3D //////////////////////////////////////////////////////////////////////////// var PMatrix3D = function PMatrix3D() { //When a matrix is created, it is set to an identity matrix this.reset(); }; PMatrix3D.prototype = { set: function() { if (arguments.length === 16) { var a = arguments; this.set([a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]]); } else if (arguments.length === 1 && arguments[0] instanceof PMatrix3D) { this.elements = arguments[0].array(); } else if (arguments.length === 1 && arguments[0] instanceof Array) { this.elements = arguments[0].slice(); } }, get: function() { var outgoing = new PMatrix3D(); outgoing.set(this.elements); return outgoing; }, reset: function() { this.set([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); }, // Returns a copy of the element values. array: function array() { return this.elements.slice(); }, translate: function(tx, ty, tz) { if (typeof tz === 'undefined') { tx = 0; } this.elements[3] += tx * this.elements[0] + ty * this.elements[1] + tz * this.elements[2]; this.elements[7] += tx * this.elements[4] + ty * this.elements[5] + tz * this.elements[6]; this.elements[11] += tx * this.elements[8] + ty * this.elements[9] + tz * this.elements[10]; this.elements[15] += tx * this.elements[12] + ty * this.elements[13] + tz * this.elements[14]; }, transpose: function() { var temp = this.elements.slice(); this.elements[0] = temp[0]; this.elements[1] = temp[4]; this.elements[2] = temp[8]; this.elements[3] = temp[12]; this.elements[4] = temp[1]; this.elements[5] = temp[5]; this.elements[6] = temp[9]; this.elements[7] = temp[13]; this.elements[8] = temp[2]; this.elements[9] = temp[6]; this.elements[10] = temp[10]; this.elements[11] = temp[14]; this.elements[12] = temp[3]; this.elements[13] = temp[7]; this.elements[14] = temp[11]; this.elements[15] = temp[15]; }, /* You must either pass in two PVectors or two arrays, don't mix between types. You may also omit a second argument and simply read the result from the return. */ mult: function(source, target) { var x, y, z, w; if (source instanceof PVector) { x = source.x; y = source.y; z = source.z; w = 1; if (!target) { target = new PVector(); } } else if (source instanceof Array) { x = source[0]; y = source[1]; z = source[2]; w = source[3] || 1; if (!target || target.length !== 3 && target.length !== 4) { target = [0, 0, 0]; } } if (target instanceof Array) { if (target.length === 3) { target[0] = this.elements[0] * x + this.elements[1] * y + this.elements[2] * z + this.elements[3]; target[1] = this.elements[4] * x + this.elements[5] * y + this.elements[6] * z + this.elements[7]; target[2] = this.elements[8] * x + this.elements[9] * y + this.elements[10] * z + this.elements[11]; } else if (target.length === 4) { target[0] = this.elements[0] * x + this.elements[1] * y + this.elements[2] * z + this.elements[3] * w; target[1] = this.elements[4] * x + this.elements[5] * y + this.elements[6] * z + this.elements[7] * w; target[2] = this.elements[8] * x + this.elements[9] * y + this.elements[10] * z + this.elements[11] * w; target[3] = this.elements[12] * x + this.elements[13] * y + this.elements[14] * z + this.elements[15] * w; } } if (target instanceof PVector) { target.x = this.elements[0] * x + this.elements[1] * y + this.elements[2] * z + this.elements[3]; target.y = this.elements[4] * x + this.elements[5] * y + this.elements[6] * z + this.elements[7]; target.z = this.elements[8] * x + this.elements[9] * y + this.elements[10] * z + this.elements[11]; } return target; }, preApply: function() { if (arguments.length === 1 && arguments[0] instanceof PMatrix3D) { this.preApply(arguments[0].array()); } else if (arguments.length === 16) { var a = arguments; this.preApply([a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]]); } else if (arguments.length === 1 && arguments[0] instanceof Array) { var source = arguments[0]; var result = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; var e = 0; for (var row = 0; row < 4; row++) { for (var col = 0; col < 4; col++, e++) { result[e] += this.elements[col + 0] * source[row * 4 + 0] + this.elements[col + 4] * source[row * 4 + 1] + this.elements[col + 8] * source[row * 4 + 2] + this.elements[col + 12] * source[row * 4 + 3]; } } this.elements = result.slice(); } }, apply: function() { if (arguments.length === 1 && arguments[0] instanceof PMatrix3D) { this.apply(arguments[0].array()); } else if (arguments.length === 16) { var a = arguments; this.apply([a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]]); } else if (arguments.length === 1 && arguments[0] instanceof Array) { var source = arguments[0]; var result = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; var e = 0; for (var row = 0; row < 4; row++) { for (var col = 0; col < 4; col++, e++) { result[e] += this.elements[row * 4 + 0] * source[col + 0] + this.elements[row * 4 + 1] * source[col + 4] + this.elements[row * 4 + 2] * source[col + 8] + this.elements[row * 4 + 3] * source[col + 12]; } } this.elements = result.slice(); } }, rotate: function(angle, v0, v1, v2) { if (!v1) { this.rotateZ(angle); } else { // TODO should make sure this vector is normalized var c = p.cos(angle); var s = p.sin(angle); var t = 1.0 - c; this.apply((t * v0 * v0) + c, (t * v0 * v1) - (s * v2), (t * v0 * v2) + (s * v1), 0, (t * v0 * v1) + (s * v2), (t * v1 * v1) + c, (t * v1 * v2) - (s * v0), 0, (t * v0 * v2) - (s * v1), (t * v1 * v2) + (s * v0), (t * v2 * v2) + c, 0, 0, 0, 0, 1); } }, invApply: function() { if (typeof inverseCopy === "undefined") { inverseCopy = new PMatrix3D(); } var a = arguments; inverseCopy.set(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]); if (!inverseCopy.invert()) { return false; } this.preApply(inverseCopy); return true; }, rotateX: function(angle) { var c = p.cos(angle); var s = p.sin(angle); this.apply([1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1]); }, rotateY: function(angle) { var c = p.cos(angle); var s = p.sin(angle); this.apply([c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1]); }, rotateZ: function(angle) { var c = Math.cos(angle); var s = Math.sin(angle); this.apply([c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); }, // Uniform scaling if only one value passed in scale: function(sx, sy, sz) { if (sx && !sy && !sz) { sy = sz = sx; } else if (sx && sy && !sz) { sz = 1; } if (sx && sy && sz) { this.elements[0] *= sx; this.elements[1] *= sy; this.elements[2] *= sz; this.elements[4] *= sx; this.elements[5] *= sy; this.elements[6] *= sz; this.elements[8] *= sx; this.elements[9] *= sy; this.elements[10] *= sz; this.elements[12] *= sx; this.elements[13] *= sy; this.elements[14] *= sz; } }, skewX: function(angle) { var t = p.tan(angle); this.apply(1, t, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); }, skewY: function(angle) { var t = Math.tan(angle); this.apply(1, 0, 0, 0, t, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); }, multX: function(x, y, z, w) { if (!z) { return this.elements[0] * x + this.elements[1] * y + this.elements[3]; } else if (!w) { return this.elements[0] * x + this.elements[1] * y + this.elements[2] * z + this.elements[3]; } else { return this.elements[0] * x + this.elements[1] * y + this.elements[2] * z + this.elements[3] * w; } }, multY: function(x, y, z, w) { if (!z) { return this.elements[4] * x + this.elements[5] * y + this.elements[7]; } else if (!w) { return this.elements[4] * x + this.elements[5] * y + this.elements[6] * z + this.elements[7]; } else { return this.elements[4] * x + this.elements[5] * y + this.elements[6] * z + this.elements[7] * w; } }, multZ: function(x, y, z, w) { if (!w) { return this.elements[8] * x + this.elements[9] * y + this.elements[10] * z + this.elements[11]; } else { return this.elements[8] * x + this.elements[9] * y + this.elements[10] * z + this.elements[11] * w; } }, multW: function(x, y, z, w) { if (!w) { return this.elements[12] * x + this.elements[13] * y + this.elements[14] * z + this.elements[15]; } else { return this.elements[12] * x + this.elements[13] * y + this.elements[14] * z + this.elements[15] * w; } }, invert: function() { var kInv = []; var fA0 = this.elements[0] * this.elements[5] - this.elements[1] * this.elements[4]; var fA1 = this.elements[0] * this.elements[6] - this.elements[2] * this.elements[4]; var fA2 = this.elements[0] * this.elements[7] - this.elements[3] * this.elements[4]; var fA3 = this.elements[1] * this.elements[6] - this.elements[2] * this.elements[5]; var fA4 = this.elements[1] * this.elements[7] - this.elements[3] * this.elements[5]; var fA5 = this.elements[2] * this.elements[7] - this.elements[3] * this.elements[6]; var fB0 = this.elements[8] * this.elements[13] - this.elements[9] * this.elements[12]; var fB1 = this.elements[8] * this.elements[14] - this.elements[10] * this.elements[12]; var fB2 = this.elements[8] * this.elements[15] - this.elements[11] * this.elements[12]; var fB3 = this.elements[9] * this.elements[14] - this.elements[10] * this.elements[13]; var fB4 = this.elements[9] * this.elements[15] - this.elements[11] * this.elements[13]; var fB5 = this.elements[10] * this.elements[15] - this.elements[11] * this.elements[14]; // Determinant var fDet = fA0 * fB5 - fA1 * fB4 + fA2 * fB3 + fA3 * fB2 - fA4 * fB1 + fA5 * fB0; // Account for a very small value // return false if not successful. if (Math.abs(fDet) <= 1e-9) { return false; } kInv[0] = +this.elements[5] * fB5 - this.elements[6] * fB4 + this.elements[7] * fB3; kInv[4] = -this.elements[4] * fB5 + this.elements[6] * fB2 - this.elements[7] * fB1; kInv[8] = +this.elements[4] * fB4 - this.elements[5] * fB2 + this.elements[7] * fB0; kInv[12] = -this.elements[4] * fB3 + this.elements[5] * fB1 - this.elements[6] * fB0; kInv[1] = -this.elements[1] * fB5 + this.elements[2] * fB4 - this.elements[3] * fB3; kInv[5] = +this.elements[0] * fB5 - this.elements[2] * fB2 + this.elements[3] * fB1; kInv[9] = -this.elements[0] * fB4 + this.elements[1] * fB2 - this.elements[3] * fB0; kInv[13] = +this.elements[0] * fB3 - this.elements[1] * fB1 + this.elements[2] * fB0; kInv[2] = +this.elements[13] * fA5 - this.elements[14] * fA4 + this.elements[15] * fA3; kInv[6] = -this.elements[12] * fA5 + this.elements[14] * fA2 - this.elements[15] * fA1; kInv[10] = +this.elements[12] * fA4 - this.elements[13] * fA2 + this.elements[15] * fA0; kInv[14] = -this.elements[12] * fA3 + this.elements[13] * fA1 - this.elements[14] * fA0; kInv[3] = -this.elements[9] * fA5 + this.elements[10] * fA4 - this.elements[11] * fA3; kInv[7] = +this.elements[8] * fA5 - this.elements[10] * fA2 + this.elements[11] * fA1; kInv[11] = -this.elements[8] * fA4 + this.elements[9] * fA2 - this.elements[11] * fA0; kInv[15] = +this.elements[8] * fA3 - this.elements[9] * fA1 + this.elements[10] * fA0; // Inverse using Determinant var fInvDet = 1.0 / fDet; kInv[0] *= fInvDet; kInv[1] *= fInvDet; kInv[2] *= fInvDet; kInv[3] *= fInvDet; kInv[4] *= fInvDet; kInv[5] *= fInvDet; kInv[6] *= fInvDet; kInv[7] *= fInvDet; kInv[8] *= fInvDet; kInv[9] *= fInvDet; kInv[10] *= fInvDet; kInv[11] *= fInvDet; kInv[12] *= fInvDet; kInv[13] *= fInvDet; kInv[14] *= fInvDet; kInv[15] *= fInvDet; this.elements = kInv.slice(); return true; }, toString: function() { var str = ""; for (var i = 0; i < 15; i++) { str += this.elements[i] + ", "; } str += this.elements[15]; return str; }, print: function() { var digits = printMatrixHelper(this.elements); var output = ""; output += p.nfs(this.elements[0], digits, 4) + " " + p.nfs(this.elements[1], digits, 4) + " " + p.nfs(this.elements[2], digits, 4) + " " + p.nfs(this.elements[3], digits, 4) + "\n"; output += p.nfs(this.elements[4], digits, 4) + " " + p.nfs(this.elements[5], digits, 4) + " " + p.nfs(this.elements[6], digits, 4) + " " + p.nfs(this.elements[7], digits, 4) + "\n"; output += p.nfs(this.elements[8], digits, 4) + " " + p.nfs(this.elements[9], digits, 4) + " " + p.nfs(this.elements[10], digits, 4) + " " + p.nfs(this.elements[11], digits, 4) + "\n"; output += p.nfs(this.elements[12], digits, 4) + " " + p.nfs(this.elements[13], digits, 4) + " " + p.nfs(this.elements[14], digits, 4) + " " + p.nfs(this.elements[15], digits, 4) + "\n\n"; p.println(output); }, invTranslate: function(tx, ty, tz) { this.preApply(1, 0, 0, -tx, 0, 1, 0, -ty, 0, 0, 1, -tz, 0, 0, 0, 1); }, invRotateX: function(angle) { var c = p.cos(-angle); var s = p.sin(-angle); this.preApply([1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1]); }, invRotateY: function(angle) { var c = p.cos(-angle); var s = p.sin(-angle); this.preApply([c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1]); }, invRotateZ: function(angle) { var c = p.cos(-angle); var s = p.sin(-angle); this.preApply([c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); }, invScale: function(x, y, z) { this.preApply([1 / x, 0, 0, 0, 0, 1 / y, 0, 0, 0, 0, 1 / z, 0, 0, 0, 0, 1]); } }; //////////////////////////////////////////////////////////////////////////// // Matrix Stack //////////////////////////////////////////////////////////////////////////// var PMatrixStack = function PMatrixStack() { this.matrixStack = []; }; PMatrixStack.prototype.load = function load() { var tmpMatrix; if (p.use3DContext) { tmpMatrix = new PMatrix3D(); } else { tmpMatrix = new PMatrix2D(); } if (arguments.length === 1) { tmpMatrix.set(arguments[0]); } else { tmpMatrix.set(arguments); } this.matrixStack.push(tmpMatrix); }; PMatrixStack.prototype.push = function push() { this.matrixStack.push(this.peek()); }; PMatrixStack.prototype.pop = function pop() { return this.matrixStack.pop(); }; PMatrixStack.prototype.peek = function peek() { var tmpMatrix; if (p.use3DContext) { tmpMatrix = new PMatrix3D(); } else { tmpMatrix = new PMatrix2D(); } tmpMatrix.set(this.matrixStack[this.matrixStack.length - 1]); return tmpMatrix; }; PMatrixStack.prototype.mult = function mult(matrix) { this.matrixStack[this.matrixStack.length - 1].apply(matrix); }; //////////////////////////////////////////////////////////////////////////// // Array handling //////////////////////////////////////////////////////////////////////////// p.split = function(str, delim) { return str.split(delim); }; p.splitTokens = function(str, tokens) { if (arguments.length === 1) { tokens = "\n\t\r\f "; } tokens = "[" + tokens + "]"; var ary = new Array(0); var index = 0; var pos = str.search(tokens); while (pos >= 0) { if (pos === 0) { str = str.substring(1); } else { ary[index] = str.substring(0, pos); index++; str = str.substring(pos); } pos = str.search(tokens); } if (str.length > 0) { ary[index] = str; } if (ary.length === 0) { ary = undefined; } return ary; }; p.append = function(array, element) { array[array.length] = element; return array; }; p.concat = function(array1, array2) { return array1.concat(array2); }; p.sort = function(array, numElem) { var ret = []; // depending on the type used (int, float) or string // we'll need to use a different compare function if (array.length > 0) { // copy since we need to return another array var elemsToCopy = numElem > 0 ? numElem : array.length; for (var i = 0; i < elemsToCopy; i++) { ret.push(array[i]); } if (typeof array[0] === "string") { ret.sort(); } // int or float else { ret.sort(function(a, b) { return a - b; }); } // copy on the rest of the elements that were not sorted in case the user // only wanted a subset of an array to be sorted. if (numElem > 0) { for (var j = ret.length; j < array.length; j++) { ret.push(array[j]); } } } return ret; }; p.splice = function(array, value, index) { if (array.length === 0 && value.length === 0) { return array; } if (value instanceof Array) { for (var i = 0, j = index; i < value.length; j++, i++) { array.splice(j, 0, value[i]); } } else { array.splice(index, 0, value); } return array; }; p.subset = function(array, offset, length) { if (arguments.length === 2) { return p.subset(array, offset, array.length - offset); } else if (arguments.length === 3) { return array.slice(offset, offset + length); } }; p.join = function(array, seperator) { return array.join(seperator); }; p.shorten = function(ary) { var newary = new Array(0); // copy array into new array var len = ary.length; for (var i = 0; i < len; i++) { newary[i] = ary[i]; } newary.pop(); return newary; }; p.expand = function(ary, newSize) { var newary = new Array(0); var len = ary.length; for (var i = 0; i < len; i++) { newary[i] = ary[i]; } if (arguments.length === 1) { // double size of array newary.length *= 2; } else if (arguments.length === 2) { // size is newSize newary.length = newSize; } return newary; }; p.arrayCopy = function(src, srcPos, dest, destPos, length) { if (arguments.length === 2) { // recall itself and copy src to dest from start index 0 to 0 of src.length p.arrayCopy(src, 0, srcPos, 0, src.length); } else if (arguments.length === 3) { // recall itself and copy src to dest from start index 0 to 0 of length p.arrayCopy(src, 0, srcPos, 0, dest); } else if (arguments.length === 5) { // copy src to dest from index srcPos to index destPos of length recursivly on objects for (var i = srcPos, j = destPos; i < length + srcPos; i++, j++) { if (src[i] && typeof src[i] === "object") { // src[i] is not null and is another object or array. go recursive p.arrayCopy(src[i], 0, dest[j], 0, src[i].length); } else { // standard type, just copy dest[j] = src[i]; } } } }; p.ArrayList = function() { var createArrayList = function(args){ var array = []; for (var i = 0; i < args[0]; i++){ array[i] = (args.length > 1 ? createArrayList(args.slice(1)) : 0 ); } array.get = function(i) { return this[i]; }; array.contains = function(item) { return this.indexOf(item) !== -1; }; array.add = function(item) { return this.push(item); }; array.size = function() { return this.length; }; array.clear = function() { this.length = 0; }; array.remove = function(i) { return this.splice(i, 1)[0]; }; array.isEmpty = function() { return !this.length; }; array.clone = function() { var size = this.length; var a = new p.ArrayList(size); for (var i = 0; i < size; i++) { a[i] = this[i]; } return a; }; return array; }; return createArrayList(Array.prototype.slice.call(arguments)); }; p.reverse = function(array) { return array.reverse(); }; //////////////////////////////////////////////////////////////////////////// // HashMap //////////////////////////////////////////////////////////////////////////// var virtHashCode = function virtHashCode(obj) { if (obj.constructor === String) { var hash = 0; for (var i = 0; i < obj.length; ++i) { hash = (hash * 31 + obj.charCodeAt(i)) & 0xFFFFFFFF; } return hash; } else if (typeof(obj) !== "object") { return obj & 0xFFFFFFFF; } else if ("hashCode" in obj) { return obj.hashCode.call(obj); } else { if (obj.$id === undefined) { obj.$id = ((Math.floor(Math.random() * 0x10000) - 0x8000) << 16) | Math.floor(Math.random() * 0x10000); } return obj.$id; } }; var virtEquals = function virtEquals(obj, other) { if (obj === null || other === null) { return (obj === null) && (other === null); } else if (obj.constructor === String) { return obj === other; } else if (typeof(obj) !== "object") { return obj === other; } else if ("equals" in obj) { return obj.equals.call(obj, other); } else { return obj === other; } }; p.HashMap = function HashMap() { if (arguments.length === 1 && arguments[0].constructor === HashMap) { return arguments[0].clone(); } var initialCapacity = arguments.length > 0 ? arguments[0] : 16; var loadFactor = arguments.length > 1 ? arguments[1] : 0.75; var buckets = new Array(initialCapacity); var count = 0; var hashMap = this; function ensureLoad() { if (count <= loadFactor * buckets.length) { return; } var allEntries = []; for (var i = 0; i < buckets.length; ++i) { if (buckets[i] !== undefined) { allEntries = allEntries.concat(buckets[i]); } } buckets = new Array(buckets.length * 2); for (var j = 0; j < allEntries.length; ++j) { var index = virtHashCode(allEntries[j].key) % buckets.length; var bucket = buckets[index]; if (bucket === undefined) { buckets[index] = bucket = []; } bucket.push(allEntries[j]); } } function Iterator(conversion, removeItem) { var bucketIndex = 0; var itemIndex = -1; var endOfBuckets = false; function findNext() { while (!endOfBuckets) { ++itemIndex; if (bucketIndex >= buckets.length) { endOfBuckets = true; } else if (typeof(buckets[bucketIndex]) === 'undefined' || itemIndex >= buckets[bucketIndex].length) { itemIndex = -1; ++bucketIndex; } else { return; } } } this.hasNext = function() { return !endOfBuckets; }; this.next = function() { var result = conversion(buckets[bucketIndex][itemIndex]); findNext(); return result; }; this.remove = function() { removeItem(this.next()); --itemIndex; }; findNext(); } function Set(conversion, isIn, removeItem) { this.clear = function() { hashMap.clear(); }; this.contains = function(o) { return isIn(o); }; this.containsAll = function(o) { var it = o.iterator(); while (it.hasNext()) { if (!this.contains(it.next())) { return false; } } return true; }; this.isEmpty = function() { return hashMap.isEmpty(); }; this.iterator = function() { return new Iterator(conversion, removeItem); }; this.remove = function(o) { if (this.contains(o)) { removeItem(o); return true; } return false; }; this.removeAll = function(c) { var it = c.iterator(); var changed = false; while (it.hasNext()) { var item = it.next(); if (this.contains(item)) { removeItem(item); changed = true; } } return true; }; this.retainAll = function(c) { var it = this.iterator(); var toRemove = []; while (it.hasNext()) { var entry = it.next(); if (!c.contains(entry)) { toRemove.push(entry); } } for (var i = 0; i < toRemove.length; ++i) { removeItem(toRemove[i]); } return toRemove.length > 0; }; this.size = function() { return hashMap.size(); }; this.toArray = function() { var result = new p.ArrayList(0); var it = this.iterator(); while (it.hasNext()) { result.push(it.next()); } return result; }; } function Entry(pair) { this._isIn = function(map) { return map === hashMap && (typeof(pair.removed) === 'undefined'); }; this.equals = function(o) { return virtEquals(pair.key, o.getKey()); }; this.getKey = function() { return pair.key; }; this.getValue = function() { return pair.value; }; this.hashCode = function(o) { return virtHashCode(pair.key); }; this.setValue = function(value) { var old = pair.value; pair.value = value; return old; }; } this.clear = function() { count = 0; buckets = new Array(initialCapacity); }; this.clone = function() { var map = new p.HashMap(); map.putAll(this); return map; }; this.containsKey = function(key) { var index = virtHashCode(key) % buckets.length; var bucket = buckets[index]; if (bucket === undefined) { return false; } for (var i = 0; i < bucket.length; ++i) { if (virtEquals(bucket[i].key, key)) { return true; } } return false; }; this.containsValue = function(value) { for (var i = 0; i < buckets.length; ++i) { var bucket = buckets[i]; if (bucket === undefined) { continue; } for (var j = 0; j < bucket.length; ++j) { if (virtEquals(bucket[j].value, value)) { return true; } } } return false; }; this.entrySet = function() { return new Set( function(pair) { return new Entry(pair); }, function(pair) { return pair.constructor === Entry && pair._isIn(hashMap); }, function(pair) { return hashMap.remove(pair.getKey()); }); }; this.get = function(key) { var index = virtHashCode(key) % buckets.length; var bucket = buckets[index]; if (bucket === undefined) { return null; } for (var i = 0; i < bucket.length; ++i) { if (virtEquals(bucket[i].key, key)) { return bucket[i].value; } } return null; }; this.isEmpty = function() { return count === 0; }; this.keySet = function() { return new Set( function(pair) { return pair.key; }, function(key) { return hashMap.containsKey(key); }, function(key) { return hashMap.remove(key); }); }; this.put = function(key, value) { var index = virtHashCode(key) % buckets.length; var bucket = buckets[index]; if (bucket === undefined) { ++count; buckets[index] = [{ key: key, value: value }]; ensureLoad(); return null; } for (var i = 0; i < bucket.length; ++i) { if (virtEquals(bucket[i].key, key)) { var previous = bucket[i].value; bucket[i].value = value; return previous; } }++count; bucket.push({ key: key, value: value }); ensureLoad(); return null; }; this.putAll = function(m) { var it = m.entrySet().iterator(); while (it.hasNext()) { var entry = it.next(); this.put(entry.getKey(), entry.getValue()); } }; this.remove = function(key) { var index = virtHashCode(key) % buckets.length; var bucket = buckets[index]; if (bucket === undefined) { return null; } for (var i = 0; i < bucket.length; ++i) { if (virtEquals(bucket[i].key, key)) { --count; var previous = bucket[i].value; bucket[i].removed = true; if (bucket.length > 1) { bucket.splice(i, 1); } else { buckets[index] = undefined; } return previous; } } return null; }; this.size = function() { return count; }; this.values = function() { var result = new p.ArrayList(0); var it = this.entrySet().iterator(); while (it.hasNext()) { var entry = it.next(); result.push(entry.getValue()); } return result; }; }; //////////////////////////////////////////////////////////////////////////// // Color functions //////////////////////////////////////////////////////////////////////////// // helper functions for internal blending modes p.mix = function(a, b, f) { return a + (((b - a) * f) >> 8); }; p.peg = function(n) { return (n < 0) ? 0 : ((n > 255) ? 255 : n); }; // blending modes p.modes = { replace: function(c1, c2) { return c2; }, blend: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | p.mix(c1 & p.RED_MASK, c2 & p.RED_MASK, f) & p.RED_MASK | p.mix(c1 & p.GREEN_MASK, c2 & p.GREEN_MASK, f) & p.GREEN_MASK | p.mix(c1 & p.BLUE_MASK, c2 & p.BLUE_MASK, f)); }, add: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | Math.min(((c1 & p.RED_MASK) + ((c2 & p.RED_MASK) >> 8) * f), p.RED_MASK) & p.RED_MASK | Math.min(((c1 & p.GREEN_MASK) + ((c2 & p.GREEN_MASK) >> 8) * f), p.GREEN_MASK) & p.GREEN_MASK | Math.min((c1 & p.BLUE_MASK) + (((c2 & p.BLUE_MASK) * f) >> 8), p.BLUE_MASK)); }, subtract: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | Math.max(((c1 & p.RED_MASK) - ((c2 & p.RED_MASK) >> 8) * f), p.GREEN_MASK) & p.RED_MASK | Math.max(((c1 & p.GREEN_MASK) - ((c2 & p.GREEN_MASK) >> 8) * f), p.BLUE_MASK) & p.GREEN_MASK | Math.max((c1 & p.BLUE_MASK) - (((c2 & p.BLUE_MASK) * f) >> 8), 0)); }, lightest: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | Math.max(c1 & p.RED_MASK, ((c2 & p.RED_MASK) >> 8) * f) & p.RED_MASK | Math.max(c1 & p.GREEN_MASK, ((c2 & p.GREEN_MASK) >> 8) * f) & p.GREEN_MASK | Math.max(c1 & p.BLUE_MASK, ((c2 & p.BLUE_MASK) * f) >> 8)); }, darkest: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | p.mix(c1 & p.RED_MASK, Math.min(c1 & p.RED_MASK, ((c2 & p.RED_MASK) >> 8) * f), f) & p.RED_MASK | p.mix(c1 & p.GREEN_MASK, Math.min(c1 & p.GREEN_MASK, ((c2 & p.GREEN_MASK) >> 8) * f), f) & p.GREEN_MASK | p.mix(c1 & p.BLUE_MASK, Math.min(c1 & p.BLUE_MASK, ((c2 & p.BLUE_MASK) * f) >> 8), f)); }, difference: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; var ar = (c1 & p.RED_MASK) >> 16; var ag = (c1 & p.GREEN_MASK) >> 8; var ab = (c1 & p.BLUE_MASK); var br = (c2 & p.RED_MASK) >> 16; var bg = (c2 & p.GREEN_MASK) >> 8; var bb = (c2 & p.BLUE_MASK); // formula: var cr = (ar > br) ? (ar - br) : (br - ar); var cg = (ag > bg) ? (ag - bg) : (bg - ag); var cb = (ab > bb) ? (ab - bb) : (bb - ab); // alpha blend (this portion will always be the same) return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (p.peg(ar + (((cr - ar) * f) >> 8)) << 16) | (p.peg(ag + (((cg - ag) * f) >> 8)) << 8) | (p.peg(ab + (((cb - ab) * f) >> 8)))); }, exclusion: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; var ar = (c1 & p.RED_MASK) >> 16; var ag = (c1 & p.GREEN_MASK) >> 8; var ab = (c1 & p.BLUE_MASK); var br = (c2 & p.RED_MASK) >> 16; var bg = (c2 & p.GREEN_MASK) >> 8; var bb = (c2 & p.BLUE_MASK); // formula: var cr = ar + br - ((ar * br) >> 7); var cg = ag + bg - ((ag * bg) >> 7); var cb = ab + bb - ((ab * bb) >> 7); // alpha blend (this portion will always be the same) return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (p.peg(ar + (((cr - ar) * f) >> 8)) << 16) | (p.peg(ag + (((cg - ag) * f) >> 8)) << 8) | (p.peg(ab + (((cb - ab) * f) >> 8)))); }, multiply: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; var ar = (c1 & p.RED_MASK) >> 16; var ag = (c1 & p.GREEN_MASK) >> 8; var ab = (c1 & p.BLUE_MASK); var br = (c2 & p.RED_MASK) >> 16; var bg = (c2 & p.GREEN_MASK) >> 8; var bb = (c2 & p.BLUE_MASK); // formula: var cr = (ar * br) >> 8; var cg = (ag * bg) >> 8; var cb = (ab * bb) >> 8; // alpha blend (this portion will always be the same) return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (p.peg(ar + (((cr - ar) * f) >> 8)) << 16) | (p.peg(ag + (((cg - ag) * f) >> 8)) << 8) | (p.peg(ab + (((cb - ab) * f) >> 8)))); }, screen: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; var ar = (c1 & p.RED_MASK) >> 16; var ag = (c1 & p.GREEN_MASK) >> 8; var ab = (c1 & p.BLUE_MASK); var br = (c2 & p.RED_MASK) >> 16; var bg = (c2 & p.GREEN_MASK) >> 8; var bb = (c2 & p.BLUE_MASK); // formula: var cr = 255 - (((255 - ar) * (255 - br)) >> 8); var cg = 255 - (((255 - ag) * (255 - bg)) >> 8); var cb = 255 - (((255 - ab) * (255 - bb)) >> 8); // alpha blend (this portion will always be the same) return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (p.peg(ar + (((cr - ar) * f) >> 8)) << 16) | (p.peg(ag + (((cg - ag) * f) >> 8)) << 8) | (p.peg(ab + (((cb - ab) * f) >> 8)))); }, hard_light: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; var ar = (c1 & p.RED_MASK) >> 16; var ag = (c1 & p.GREEN_MASK) >> 8; var ab = (c1 & p.BLUE_MASK); var br = (c2 & p.RED_MASK) >> 16; var bg = (c2 & p.GREEN_MASK) >> 8; var bb = (c2 & p.BLUE_MASK); // formula: var cr = (br < 128) ? ((ar * br) >> 7) : (255 - (((255 - ar) * (255 - br)) >> 7)); var cg = (bg < 128) ? ((ag * bg) >> 7) : (255 - (((255 - ag) * (255 - bg)) >> 7)); var cb = (bb < 128) ? ((ab * bb) >> 7) : (255 - (((255 - ab) * (255 - bb)) >> 7)); // alpha blend (this portion will always be the same) return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (p.peg(ar + (((cr - ar) * f) >> 8)) << 16) | (p.peg(ag + (((cg - ag) * f) >> 8)) << 8) | (p.peg(ab + (((cb - ab) * f) >> 8)))); }, soft_light: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; var ar = (c1 & p.RED_MASK) >> 16; var ag = (c1 & p.GREEN_MASK) >> 8; var ab = (c1 & p.BLUE_MASK); var br = (c2 & p.RED_MASK) >> 16; var bg = (c2 & p.GREEN_MASK) >> 8; var bb = (c2 & p.BLUE_MASK); // formula: var cr = ((ar * br) >> 7) + ((ar * ar) >> 8) - ((ar * ar * br) >> 15); var cg = ((ag * bg) >> 7) + ((ag * ag) >> 8) - ((ag * ag * bg) >> 15); var cb = ((ab * bb) >> 7) + ((ab * ab) >> 8) - ((ab * ab * bb) >> 15); // alpha blend (this portion will always be the same) return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (p.peg(ar + (((cr - ar) * f) >> 8)) << 16) | (p.peg(ag + (((cg - ag) * f) >> 8)) << 8) | (p.peg(ab + (((cb - ab) * f) >> 8)))); }, overlay: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; var ar = (c1 & p.RED_MASK) >> 16; var ag = (c1 & p.GREEN_MASK) >> 8; var ab = (c1 & p.BLUE_MASK); var br = (c2 & p.RED_MASK) >> 16; var bg = (c2 & p.GREEN_MASK) >> 8; var bb = (c2 & p.BLUE_MASK); // formula: var cr = (ar < 128) ? ((ar * br) >> 7) : (255 - (((255 - ar) * (255 - br)) >> 7)); var cg = (ag < 128) ? ((ag * bg) >> 7) : (255 - (((255 - ag) * (255 - bg)) >> 7)); var cb = (ab < 128) ? ((ab * bb) >> 7) : (255 - (((255 - ab) * (255 - bb)) >> 7)); // alpha blend (this portion will always be the same) return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (p.peg(ar + (((cr - ar) * f) >> 8)) << 16) | (p.peg(ag + (((cg - ag) * f) >> 8)) << 8) | (p.peg(ab + (((cb - ab) * f) >> 8)))); }, dodge: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; var ar = (c1 & p.RED_MASK) >> 16; var ag = (c1 & p.GREEN_MASK) >> 8; var ab = (c1 & p.BLUE_MASK); var br = (c2 & p.RED_MASK) >> 16; var bg = (c2 & p.GREEN_MASK) >> 8; var bb = (c2 & p.BLUE_MASK); // formula: var cr = (br === 255) ? 255 : p.peg((ar << 8) / (255 - br)); // division requires pre-peg()-ing var cg = (bg === 255) ? 255 : p.peg((ag << 8) / (255 - bg)); // " var cb = (bb === 255) ? 255 : p.peg((ab << 8) / (255 - bb)); // " // alpha blend (this portion will always be the same) return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (p.peg(ar + (((cr - ar) * f) >> 8)) << 16) | (p.peg(ag + (((cg - ag) * f) >> 8)) << 8) | (p.peg(ab + (((cb - ab) * f) >> 8)))); }, burn: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; var ar = (c1 & p.RED_MASK) >> 16; var ag = (c1 & p.GREEN_MASK) >> 8; var ab = (c1 & p.BLUE_MASK); var br = (c2 & p.RED_MASK) >> 16; var bg = (c2 & p.GREEN_MASK) >> 8; var bb = (c2 & p.BLUE_MASK); // formula: var cr = (br === 0) ? 0 : 255 - p.peg(((255 - ar) << 8) / br); // division requires pre-peg()-ing var cg = (bg === 0) ? 0 : 255 - p.peg(((255 - ag) << 8) / bg); // " var cb = (bb === 0) ? 0 : 255 - p.peg(((255 - ab) << 8) / bb); // " // alpha blend (this portion will always be the same) return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (p.peg(ar + (((cr - ar) * f) >> 8)) << 16) | (p.peg(ag + (((cg - ag) * f) >> 8)) << 8) | (p.peg(ab + (((cb - ab) * f) >> 8)))); } }; p.color = function color(aValue1, aValue2, aValue3, aValue4) { var r, g, b, a, rgb, aColor; // 4 arguments: (R, G, B, A) or (H, S, B, A) if (aValue1 != null && aValue2 != null && aValue3 != null && aValue4 != null) { if (curColorMode === p.HSB) { rgb = p.color.toRGB(aValue1, aValue2, aValue3); r = rgb[0]; g = rgb[1]; b = rgb[2]; } else { r = Math.round(255 * (aValue1 / colorModeX)); g = Math.round(255 * (aValue2 / colorModeY)); b = Math.round(255 * (aValue3 / colorModeZ)); } a = Math.round(255 * (aValue4 / colorModeA)); // Limit values greater than 255 r = (r > 255) ? 255 : r; g = (g > 255) ? 255 : g; b = (b > 255) ? 255 : b; a = (a > 255) ? 255 : a; // Create color int aColor = (a << 24) & p.ALPHA_MASK | (r << 16) & p.RED_MASK | (g << 8) & p.GREEN_MASK | b & p.BLUE_MASK; } // 3 arguments: (R, G, B) or (H, S, B) else if (aValue1 != null && aValue2 != null && aValue3 != null) { aColor = p.color(aValue1, aValue2, aValue3, colorModeA); } // 2 arguments: (Color, A) or (Grayscale, A) else if (aValue1 != null && aValue2 != null) { // Color int and alpha if (aValue1 & p.ALPHA_MASK) { a = Math.round(255 * (aValue2 / colorModeA)); a = (a > 255) ? 255 : a; aColor = aValue1 - (aValue1 & p.ALPHA_MASK) + ((a << 24) & p.ALPHA_MASK); } // Grayscale and alpha else { switch(curColorMode) { case p.RGB: aColor = p.color(aValue1, aValue1, aValue1, aValue2); break; case p.HSB: aColor = p.color(0, 0, (aValue1 / colorModeX) * colorModeZ, aValue2); break; } } } // 1 argument: (Grayscale) or (Color) else if (typeof aValue1 === "number") { // Grayscale if (aValue1 <= colorModeX && aValue1 >= 0) { switch(curColorMode) { case p.RGB: aColor = p.color(aValue1, aValue1, aValue1, colorModeA); break; case p.HSB: aColor = p.color(0, 0, (aValue1 / colorModeX) * colorModeZ, colorModeA); break; } } // Color int else if (aValue1) { aColor = aValue1; } } // Default else { aColor = p.color(colorModeX, colorModeY, colorModeZ, colorModeA); } return aColor; }; // Ease of use function to extract the colour bits into a string p.color.toString = function(colorInt) { return "rgba(" + ((colorInt & p.RED_MASK) >>> 16) + "," + ((colorInt & p.GREEN_MASK) >>> 8) + "," + ((colorInt & p.BLUE_MASK)) + "," + ((colorInt & p.ALPHA_MASK) >>> 24) / 255 + ")"; }; // Easy of use function to pack rgba values into a single bit-shifted color int. p.color.toInt = function(r, g, b, a) { return (a << 24) & p.ALPHA_MASK | (r << 16) & p.RED_MASK | (g << 8) & p.GREEN_MASK | b & p.BLUE_MASK; }; // Creates a simple array in [R, G, B, A] format, [255, 255, 255, 255] p.color.toArray = function(colorInt) { return [(colorInt & p.RED_MASK) >>> 16, (colorInt & p.GREEN_MASK) >>> 8, colorInt & p.BLUE_MASK, (colorInt & p.ALPHA_MASK) >>> 24]; }; // Creates a WebGL color array in [R, G, B, A] format. WebGL wants the color ranges between 0 and 1, [1, 1, 1, 1] p.color.toGLArray = function(colorInt) { return [((colorInt & p.RED_MASK) >>> 16) / 255, ((colorInt & p.GREEN_MASK) >>> 8) / 255, (colorInt & p.BLUE_MASK) / 255, ((colorInt & p.ALPHA_MASK) >>> 24) / 255]; }; // HSB conversion function from Mootools, MIT Licensed p.color.toRGB = function(h, s, b) { // Limit values greater than range h = (h > colorModeX) ? colorModeX : h; s = (s > colorModeY) ? colorModeY : s; b = (b > colorModeZ) ? colorModeZ : b; h = (h / colorModeX) * 360; s = (s / colorModeY) * 100; b = (b / colorModeZ) * 100; var br = Math.round(b / 100 * 255); if (s === 0) { // Grayscale return [br, br, br]; } else { var hue = h % 360; var f = hue % 60; var p = Math.round((b * (100 - s)) / 10000 * 255); var q = Math.round((b * (6000 - s * f)) / 600000 * 255); var t = Math.round((b * (6000 - s * (60 - f))) / 600000 * 255); switch (Math.floor(hue / 60)) { case 0: return [br, t, p]; case 1: return [q, br, p]; case 2: return [p, br, t]; case 3: return [p, q, br]; case 4: return [t, p, br]; case 5: return [br, p, q]; } } }; p.color.toHSB = function( colorInt ) { var red, green, blue; red = ((colorInt & p.RED_MASK) >>> 16) / 255; green = ((colorInt & p.GREEN_MASK) >>> 8) / 255; blue = (colorInt & p.BLUE_MASK) / 255; var max = p.max(p.max(red,green), blue), min = p.min(p.min(red,green), blue), hue, saturation; if (min === max) { return [0, 0, max]; } else { saturation = (max - min) / max; if (red === max) { hue = (green - blue) / (max - min); } else if (green === max) { hue = 2 + ((blue - red) / (max - min)); } else { hue = 4 + ((red - green) / (max - min)); } hue /= 6; if (hue < 0) { hue += 1; } else if (hue > 1) { hue -= 1; } } return [hue*colorModeX, saturation*colorModeY, max*colorModeZ]; }; p.brightness = function(colInt){ return p.color.toHSB(colInt)[2]; }; p.saturation = function(colInt){ return p.color.toHSB(colInt)[1]; }; p.hue = function(colInt){ return p.color.toHSB(colInt)[0]; }; var verifyChannel = function verifyChannel(aColor) { if (aColor.constructor === Array) { return aColor; } else { return p.color(aColor); } }; p.red = function(aColor) { return ((aColor & p.RED_MASK) >>> 16) / 255 * colorModeX; }; p.green = function(aColor) { return ((aColor & p.GREEN_MASK) >>> 8) / 255 * colorModeY; }; p.blue = function(aColor) { return (aColor & p.BLUE_MASK) / 255 * colorModeZ; }; p.alpha = function(aColor) { return ((aColor & p.ALPHA_MASK) >>> 24) / 255 * colorModeA; }; p.lerpColor = function lerpColor(c1, c2, amt) { // Get RGBA values for Color 1 to floats var colorBits1 = p.color(c1); var r1 = (colorBits1 & p.RED_MASK) >>> 16; var g1 = (colorBits1 & p.GREEN_MASK) >>> 8; var b1 = (colorBits1 & p.BLUE_MASK); var a1 = ((colorBits1 & p.ALPHA_MASK) >>> 24) / colorModeA; // Get RGBA values for Color 2 to floats var colorBits2 = p.color(c2); var r2 = (colorBits2 & p.RED_MASK) >>> 16; var g2 = (colorBits2 & p.GREEN_MASK) >>> 8; var b2 = (colorBits2 & p.BLUE_MASK); var a2 = ((colorBits2 & p.ALPHA_MASK) >>> 24) / colorModeA; // Return lerp value for each channel, INT for color, Float for Alpha-range var r = parseInt(p.lerp(r1, r2, amt), 10); var g = parseInt(p.lerp(g1, g2, amt), 10); var b = parseInt(p.lerp(b1, b2, amt), 10); var a = parseFloat(p.lerp(a1, a2, amt) * colorModeA, 10); return p.color.toInt(r, g, b, a); }; // Forced default color mode for #aaaaaa style p.defaultColor = function(aValue1, aValue2, aValue3) { var tmpColorMode = curColorMode; curColorMode = p.RGB; var c = p.color(aValue1 / 255 * colorModeX, aValue2 / 255 * colorModeY, aValue3 / 255 * colorModeZ); curColorMode = tmpColorMode; return c; }; p.colorMode = function colorMode(mode, range1, range2, range3, range4) { curColorMode = mode; if (arguments.length >= 4) { colorModeX = range1; colorModeY = range2; colorModeZ = range3; } if (arguments.length === 5) { colorModeA = range4; } if (arguments.length === 2) { p.colorMode(mode, range1, range1, range1, range1); } }; p.blendColor = function(c1, c2, mode) { var color = 0; switch (mode) { case p.REPLACE: color = p.modes.replace(c1, c2); break; case p.BLEND: color = p.modes.blend(c1, c2); break; case p.ADD: color = p.modes.add(c1, c2); break; case p.SUBTRACT: color = p.modes.subtract(c1, c2); break; case p.LIGHTEST: color = p.modes.lightest(c1, c2); break; case p.DARKEST: color = p.modes.darkest(c1, c2); break; case p.DIFFERENCE: color = p.modes.difference(c1, c2); break; case p.EXCLUSION: color = p.modes.exclusion(c1, c2); break; case p.MULTIPLY: color = p.modes.multiply(c1, c2); break; case p.SCREEN: color = p.modes.screen(c1, c2); break; case p.HARD_LIGHT: color = p.modes.hard_light(c1, c2); break; case p.SOFT_LIGHT: color = p.modes.soft_light(c1, c2); break; case p.OVERLAY: color = p.modes.overlay(c1, c2); break; case p.DODGE: color = p.modes.dodge(c1, c2); break; case p.BURN: color = p.modes.burn(c1, c2); break; } return color; }; //////////////////////////////////////////////////////////////////////////// // Canvas-Matrix manipulation //////////////////////////////////////////////////////////////////////////// p.printMatrix = function printMatrix() { modelView.print(); }; p.translate = function translate(x, y, z) { if (p.use3DContext) { forwardTransform.translate(x, y, z); reverseTransform.invTranslate(x, y, z); } else { curContext.translate(x, y); } }; p.scale = function scale(x, y, z) { if (p.use3DContext) { forwardTransform.scale(x, y, z); reverseTransform.invScale(x, y, z); } else { curContext.scale(x, y || x); } }; p.pushMatrix = function pushMatrix() { if (p.use3DContext) { userMatrixStack.load(modelView); } else { curContext.save(); } }; p.popMatrix = function popMatrix() { if (p.use3DContext) { modelView.set(userMatrixStack.pop()); } else { curContext.restore(); } }; p.resetMatrix = function resetMatrix() { forwardTransform.reset(); reverseTransform.reset(); }; p.applyMatrix = function applyMatrix() { var a = arguments; if (!p.use3DContext) { for (var cnt = a.length; cnt < 16; cnt++) { a[cnt] = 0; } a[10] = a[15] = 1; } forwardTransform.apply(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]); reverseTransform.invApply(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]); }; p.rotateX = function(angleInRadians) { forwardTransform.rotateX(angleInRadians); reverseTransform.invRotateX(angleInRadians); }; p.rotateZ = function(angleInRadians) { forwardTransform.rotateZ(angleInRadians); reverseTransform.invRotateZ(angleInRadians); }; p.rotateY = function(angleInRadians) { forwardTransform.rotateY(angleInRadians); reverseTransform.invRotateY(angleInRadians); }; p.rotate = function rotate(angleInRadians) { if (p.use3DContext) { forwardTransform.rotateZ(angleInRadians); reverseTransform.invRotateZ(angleInRadians); } else { curContext.rotate(angleInRadians); } }; p.pushStyle = function pushStyle() { // Save the canvas state. curContext.save(); p.pushMatrix(); var newState = { 'doFill': doFill, 'doStroke': doStroke, 'curTint': curTint, 'curRectMode': curRectMode, 'curColorMode': curColorMode, 'colorModeX': colorModeX, 'colorModeZ': colorModeZ, 'colorModeY': colorModeY, 'colorModeA': colorModeA, 'curTextFont': curTextFont, 'curTextSize': curTextSize }; styleArray.push(newState); }; p.popStyle = function popStyle() { var oldState = styleArray.pop(); if (oldState) { curContext.restore(); p.popMatrix(); doFill = oldState.doFill; doStroke = oldState.doStroke; curTint = oldState.curTint; curRectMode = oldState.curRectmode; curColorMode = oldState.curColorMode; colorModeX = oldState.colorModeX; colorModeZ = oldState.colorModeZ; colorModeY = oldState.colorModeY; colorModeA = oldState.colorModeA; curTextFont = oldState.curTextFont; curTextSize = oldState.curTextSize; } else { throw "Too many popStyle() without enough pushStyle()"; } }; //////////////////////////////////////////////////////////////////////////// // Time based functions //////////////////////////////////////////////////////////////////////////// p.year = function year() { return new Date().getFullYear(); }; p.month = function month() { return new Date().getMonth() + 1; }; p.day = function day() { return new Date().getDate(); }; p.hour = function hour() { return new Date().getHours(); }; p.minute = function minute() { return new Date().getMinutes(); }; p.second = function second() { return new Date().getSeconds(); }; p.millis = function millis() { return new Date().getTime() - start; }; p.noLoop = function noLoop() { doLoop = false; loopStarted = false; clearInterval(looping); }; p.redraw = function redraw() { var sec = (new Date().getTime() - timeSinceLastFPS) / 1000; framesSinceLastFPS++; var fps = framesSinceLastFPS / sec; // recalculate FPS every half second for better accuracy. if (sec > 0.5) { timeSinceLastFPS = new Date().getTime(); framesSinceLastFPS = 0; p.FRAME_RATE = fps; } p.frameCount++; inDraw = true; if (p.use3DContext) { // Delete all the lighting states and the materials the // user set in the last draw() call. p.noLights(); p.lightFalloff(1, 0, 0); p.shininess(1); p.ambient(255, 255, 255); p.specular(0, 0, 0); p.camera(); p.draw(); } else { curContext.save(); p.draw(); curContext.restore(); } inDraw = false; }; p.loop = function loop() { if (loopStarted) { return; } looping = window.setInterval(function() { try { try { p.focused = document.hasFocus(); } catch(e) {} p.redraw(); } catch(e_loop) { window.clearInterval(looping); throw e_loop; } }, curMsPerFrame); doLoop = true; loopStarted = true; }; p.frameRate = function frameRate(aRate) { curFrameRate = aRate; curMsPerFrame = 1000 / curFrameRate; }; p.exit = function exit() { window.clearInterval(looping); for (var i=0, ehl=p.pjs.eventHandlers.length; i<ehl; i++) { var elem = p.pjs.eventHandlers[i][0], type = p.pjs.eventHandlers[i][1], fn = p.pjs.eventHandlers[i][2]; if (elem.removeEventListener) { elem.removeEventListener(type, fn, false); } else if (elem.detachEvent) { elem.detachEvent("on" + type, fn); } } }; //////////////////////////////////////////////////////////////////////////// // MISC functions //////////////////////////////////////////////////////////////////////////// p.cursor = function cursor() { if (arguments.length > 1 || (arguments.length === 1 && arguments[0] instanceof p.PImage)) { var image = arguments[0], x, y; if (arguments.length >= 3) { x = arguments[1]; y = arguments[2]; if (x < 0 || y < 0 || y >= image.height || x >= image.width) { throw "x and y must be non-negative and less than the dimensions of the image"; } } else { x = image.width >>> 1; y = image.height >>> 1; } // see https://developer.mozilla.org/en/Using_URL_values_for_the_cursor_property var imageDataURL = image.toDataURL(); var style = "url(\"" + imageDataURL + "\") " + x + " " + y + ", default"; curCursor = curElement.style.cursor = style; } else if (arguments.length === 1) { var mode = arguments[0]; curCursor = curElement.style.cursor = mode; } else { curCursor = curElement.style.cursor = oldCursor; } }; p.noCursor = function noCursor() { curCursor = curElement.style.cursor = p.NOCURSOR; }; p.link = function(href, target) { if (typeof target !== 'undefined') { window.open(href, target); } else { window.location = href; } }; // PGraphics methods // TODO: These functions are suppose to be called before any operations are called on the // PGraphics object. They currently do nothing. p.beginDraw = function beginDraw() {}; p.endDraw = function endDraw() {}; // Imports an external Processing.js library p.Import = function Import(lib) { // Replace evil-eval method with a DOM <script> tag insert method that // binds new lib code to the Processing.lib names-space and the current // p context. -F1LT3R }; var contextMenu = function(e) { e.preventDefault(); e.stopPropagation(); }; p.disableContextMenu = function disableContextMenu() { curElement.addEventListener('contextmenu', contextMenu, false); }; p.enableContextMenu = function enableContextMenu() { curElement.removeEventListener('contextmenu', contextMenu, false); }; //////////////////////////////////////////////////////////////////////////// // Binary Functions //////////////////////////////////////////////////////////////////////////// function decToBin(value, numBitsInValue) { var mask = 1; mask = mask << (numBitsInValue - 1); var str = ""; for (var i = 0; i < numBitsInValue; i++) { str += (mask & value) ? "1" : "0"; mask = mask >>> 1; } return str; } p.binary = function(num, numBits) { var numBitsInValue = 32; // color if (typeof num === "string" && num.length > 1) { var c = num.slice(5, -1).split(","); // if all components are zero, a single "0" is returned for some reason // [0] alpha is normalized, [1] r, [2] g, [3] b var sbin = [ decToBin(c[3] * 255, 8), decToBin(c[0], 8), decToBin(c[1], 8), decToBin(c[2], 8) ]; var s = sbin[0] + sbin[1] + sbin[2] + sbin[3]; if (numBits) { s = s.substr(-numBits); } // if the user didn't specify number of bits, // trim leading zeros. else { s = s.replace(/^0+$/g, "0"); s = s.replace(/^0{1,}1/g, "1"); } return s; } // char if (typeof num === "string" || num instanceof Char) { if (num instanceof Char) { num = num.toString().charCodeAt(0); } else { num = num.charCodeAt(0); } if (numBits) { numBitsInValue = 32; } else { numBitsInValue = 16; } } var str = decToBin(num, numBitsInValue); // trim string if user wanted less chars if (numBits) { str = str.substr(-numBits); } return str; }; p.unbinary = function unbinary(binaryString) { var binaryPattern = new RegExp("^[0|1]{8}$"); var addUp = 0; if (isNaN(binaryString)) { throw "NaN_Err"; } else { if (arguments.length === 1 || binaryString.length === 8) { if (binaryPattern.test(binaryString)) { for (var i = 0; i < 8; i++) { addUp += (Math.pow(2, i) * parseInt(binaryString.charAt(7 - i), 10)); } return addUp + ""; } else { throw "notBinary: the value passed into unbinary was not an 8 bit binary number"; } } else { throw "longErr"; } } }; p.nfs = function(num, left, right) { var str, len, formatLength, rounded; // array handling if (typeof num === "object" && num.constructor === Array) { str = new Array(0); len = num.length; for (var i = 0; i < len; i++) { str[i] = p.nfs(num[i], left, right); } } else if (arguments.length === 3) { var negative = num < 0 ? true : false; // Make it work exactly like p5 for right = 0 if (right === 0) { right = 1; } if (right < 0) { rounded = Math.round(num); } else { // round to 'right' decimal places rounded = Math.round(num * Math.pow(10, right)) / Math.pow(10, right); } // split number into whole and fractional components var splitNum = Math.abs(rounded).toString().split("."); // [0] whole number, [1] fractional number // format whole part formatLength = left - splitNum[0].length; for (; formatLength > 0; formatLength--) { splitNum[0] = "0" + splitNum[0]; } // format fractional part if (splitNum.length === 2 || right > 0) { splitNum[1] = splitNum.length === 2 ? splitNum[1] : ""; formatLength = right - splitNum[1].length; for (; formatLength > 0; formatLength--) { splitNum[1] += "0"; } str = splitNum.join("."); } else { str = splitNum[0]; } str = (negative ? "-" : " ") + str; } else if (arguments.length === 2) { str = p.nfs(num, left, -1); } return str; }; p.nfp = function(num, left, right) { var str, len, formatLength, rounded; // array handling if (typeof num === "object" && num.constructor === Array) { str = new Array(0); len = num.length; for (var i = 0; i < len; i++) { str[i] = p.nfp(num[i], left, right); } } else if (arguments.length === 3) { var negative = num < 0 ? true : false; // Make it work exactly like p5 for right = 0 if (right === 0) { right = 1; } if (right < 0) { rounded = Math.round(num); } else { // round to 'right' decimal places rounded = Math.round(num * Math.pow(10, right)) / Math.pow(10, right); } // split number into whole and fractional components var splitNum = Math.abs(rounded).toString().split("."); // [0] whole number, [1] fractional number // format whole part formatLength = left - splitNum[0].length; for (; formatLength > 0; formatLength--) { splitNum[0] = "0" + splitNum[0]; } // format fractional part if (splitNum.length === 2 || right > 0) { splitNum[1] = splitNum.length === 2 ? splitNum[1] : ""; formatLength = right - splitNum[1].length; for (; formatLength > 0; formatLength--) { splitNum[1] += "0"; } str = splitNum.join("."); } else { str = splitNum[0]; } str = (negative ? "-" : "+") + str; } else if (arguments.length === 2) { str = p.nfp(num, left, -1); } return str; }; p.nfc = function(num, right) { var str; var decimals = right >= 0 ? right : 0; if (typeof num === "object") { str = new Array(0); for (var i = 0; i < num.length; i++) { str[i] = p.nfc(num[i], decimals); } } else if (arguments.length === 2) { var rawStr = p.nfs(num, 0, decimals); var ary = new Array(0); ary = rawStr.split('.'); // ary[0] contains left of decimal, ary[1] contains decimal places if they exist // insert commas now, then append ary[1] if it exists var leftStr = ary[0]; var rightStr = ary.length > 1 ? '.' + ary[1] : ''; var commas = /(\d+)(\d{3})/; while (commas.test(leftStr)) { leftStr = leftStr.replace(commas, '$1' + ',' + '$2'); } str = leftStr + rightStr; } else if (arguments.length === 1) { str = p.nfc(num, 0); } return str; }; var decimalToHex = function decimalToHex(d, padding) { //if there is no padding value added, default padding to 8 else go into while statement. padding = typeof(padding) === "undefined" || padding === null ? padding = 8 : padding; if (d < 0) { d = 0xFFFFFFFF + d + 1; } var hex = Number(d).toString(16).toUpperCase(); while (hex.length < padding) { hex = "0" + hex; } if (hex.length >= padding) { hex = hex.substring(hex.length - padding, hex.length); } return hex; }; // note: since we cannot keep track of byte, int types by default the returned string is 8 chars long // if no 2nd argument is passed. closest compromise we can use to match java implementation Feb 5 2010 // also the char parser has issues with chars that are not digits or letters IE: !@#$%^&* p.hex = function hex(value, len) { var hexstring = ""; if (arguments.length === 1) { if (value instanceof Char) { hexstring = hex(value, 4); } else { // int or byte, indistinguishable at the moment, default to 8 hexstring = hex(value, 8); } } else { // pad to specified length hexstring = decimalToHex(value, len); } return hexstring; }; p.unhex = function(str) { var value = 0, multiplier = 1, num = 0; var len = str.length - 1; for (var i = len; i >= 0; i--) { try { switch (str[i]) { case "0": num = 0; break; case "1": num = 1; break; case "2": num = 2; break; case "3": num = 3; break; case "4": num = 4; break; case "5": num = 5; break; case "6": num = 6; break; case "7": num = 7; break; case "8": num = 8; break; case "9": num = 9; break; case "A": case "a": num = 10; break; case "B": case "b": num = 11; break; case "C": case "c": num = 12; break; case "D": case "d": num = 13; break; case "E": case "e": num = 14; break; case "F": case "f": num = 15; break; default: return 0; } value += num * multiplier; multiplier *= 16; } catch(e) { Processing.debug(e); } // correct for int overflow java expectation if (value > 2147483647) { value -= 4294967296; } } return value; }; // Load a file or URL into strings p.loadStrings = function loadStrings(url) { return ajax(url).split("\n"); }; p.loadBytes = function loadBytes(url) { var string = ajax(url); var ret = new Array(string.length); for (var i = 0; i < string.length; i++) { ret[i] = string.charCodeAt(i); } return ret; }; // nf() should return an array when being called on an array, at the moment it only returns strings. -F1LT3R // This breaks the join() ref-test. The Processing.org documentation says String or String[]. SHOULD BE FIXED NOW p.nf = function() { var str, num, pad, arr, left, right, isNegative, test, i; if (arguments.length === 2 && typeof arguments[0] === 'number' && typeof arguments[1] === 'number' && (arguments[0] + "").indexOf('.') === -1) { num = arguments[0]; pad = arguments[1]; isNegative = num < 0; if (isNegative) { num = Math.abs(num); } str = "" + num; for (i = pad - str.length; i > 0; i--) { str = "0" + str; } if (isNegative) { str = "-" + str; } } else if (arguments.length === 2 && typeof arguments[0] === 'object' && arguments[0].constructor === Array && typeof arguments[1] === 'number') { arr = arguments[0]; pad = arguments[1]; str = new Array(arr.length); for (i = 0; i < arr.length && str !== undefined; i++) { test = p.nf(arr[i], pad); if (test === undefined) { str = undefined; } else { str[i] = test; } } } else if (arguments.length === 3 && typeof arguments[0] === 'number' && typeof arguments[1] === 'number' && typeof arguments[2] === 'number' && (arguments[0] + "").indexOf('.') >= 0) { num = arguments[0]; left = arguments[1]; right = arguments[2]; isNegative = num < 0; if (isNegative) { num = Math.abs(num); } // Change the way the number is 'floored' based on whether it is odd or even. if (right < 0 && Math.floor(num) % 2 === 1) { // Make sure 1.49 rounds to 1, but 1.5 rounds to 2. if ((num) - Math.floor(num) >= 0.5) { num = num + 1; } } str = "" + num; for (i = left - str.indexOf('.'); i > 0; i--) { str = "0" + str; } var numDec = str.length - str.indexOf('.') - 1; if (numDec <= right) { for (i = right - (str.length - str.indexOf('.') - 1); i > 0; i--) { str = str + "0"; } } else if (right > 0) { str = str.substring(0, str.length - (numDec - right)); } else if (right < 0) { str = str.substring(0, str.indexOf('.')); } if (isNegative) { str = "-" + str; } } else if (arguments.length === 3 && typeof arguments[0] === 'object' && arguments[0].constructor === Array && typeof arguments[1] === 'number' && typeof arguments[2] === 'number') { arr = arguments[0]; left = arguments[1]; right = arguments[2]; str = new Array(arr.length); for (i = 0; i < arr.length && str !== undefined; i++) { test = p.nf(arr[i], left, right); if (test === undefined) { str = undefined; } else { str[i] = test; } } } return str; }; //////////////////////////////////////////////////////////////////////////// // String Functions //////////////////////////////////////////////////////////////////////////// p.matchAll = function matchAll(aString, aRegExp) { var results = [], latest; var regexp = new RegExp(aRegExp, "g"); while ((latest = regexp.exec(aString)) !== null) { results.push(latest); if (latest[0].length === 0) { ++regexp.lastIndex; } } return results.length > 0 ? results : null; }; String.prototype.replaceAll = function(re, replace) { return this.replace(new RegExp(re, "g"), replace); }; String.prototype.equals = function equals(str) { return this.valueOf() === str.valueOf(); }; String.prototype.toCharArray = function() { var chars = this.split(""); for (var i = chars.length - 1; i >= 0; i--) { chars[i] = new Char(chars[i]); } return chars; }; p.match = function(str, regexp) { return str.match(regexp); }; // tinylog lite JavaScript library /*global tinylog,print*/ var tinylogLite = (function() { "use strict"; var tinylogLite = {}, undef = "undefined", func = "function", False = !1, True = !0, log = "log"; if (typeof tinylog !== undef && typeof tinylog[log] === func) { // pre-existing tinylog present tinylogLite[log] = tinylog[log]; } else if (typeof document !== undef && !document.fake) { (function() { // DOM document var doc = document, $div = "div", $style = "style", $title = "title", containerStyles = { zIndex: 10000, position: "fixed", bottom: "0px", width: "100%", height: "15%", fontFamily: "sans-serif", color: "#ccc", backgroundColor: "black" }, outputStyles = { position: "relative", fontFamily: "monospace", overflow: "auto", height: "100%", paddingTop: "5px" }, resizerStyles = { height: "5px", marginTop: "-5px", cursor: "n-resize", backgroundColor: "darkgrey" }, closeButtonStyles = { position: "absolute", top: "5px", right: "20px", color: "#111", MozBorderRadius: "4px", webkitBorderRadius: "4px", borderRadius: "4px", cursor: "pointer", fontWeight: "normal", textAlign: "center", padding: "3px 5px", backgroundColor: "#333", fontSize: "12px" }, entryStyles = { //borderBottom: "1px solid #d3d3d3", minHeight: "16px" }, entryTextStyles = { fontSize: "12px", margin: "0 8px 0 8px", maxWidth: "100%", whiteSpace: "pre-wrap", overflow: "auto" }, view = doc.defaultView, docElem = doc.documentElement, docElemStyle = docElem[$style], setStyles = function() { var i = arguments.length, elemStyle, styles, style; while (i--) { styles = arguments[i--]; elemStyle = arguments[i][$style]; for (style in styles) { if (styles.hasOwnProperty(style)) { elemStyle[style] = styles[style]; } } } }, observer = function(obj, event, handler) { if (obj.addEventListener) { obj.addEventListener(event, handler, False); } else if (obj.attachEvent) { obj.attachEvent("on" + event, handler); } return [obj, event, handler]; }, unobserve = function(obj, event, handler) { if (obj.removeEventListener) { obj.removeEventListener(event, handler, False); } else if (obj.detachEvent) { obj.detachEvent("on" + event, handler); } }, clearChildren = function(node) { var children = node.childNodes, child = children.length; while (child--) { node.removeChild(children.item(0)); } }, append = function(to, elem) { return to.appendChild(elem); }, createElement = function(localName) { return doc.createElement(localName); }, createTextNode = function(text) { return doc.createTextNode(text); }, createLog = tinylogLite[log] = function(message) { // don't show output log until called once var uninit, originalPadding = docElemStyle.paddingBottom, container = createElement($div), containerStyle = container[$style], resizer = append(container, createElement($div)), output = append(container, createElement($div)), closeButton = append(container, createElement($div)), resizingLog = False, previousHeight = False, previousScrollTop = False, updateSafetyMargin = function() { // have a blank space large enough to fit the output box at the page bottom docElemStyle.paddingBottom = container.clientHeight + "px"; }, setContainerHeight = function(height) { var viewHeight = view.innerHeight, resizerHeight = resizer.clientHeight; // constrain the container inside the viewport's dimensions if (height < 0) { height = 0; } else if (height + resizerHeight > viewHeight) { height = viewHeight - resizerHeight; } containerStyle.height = height / viewHeight * 100 + "%"; updateSafetyMargin(); }, observers = [ observer(doc, "mousemove", function(evt) { if (resizingLog) { setContainerHeight(view.innerHeight - evt.clientY); output.scrollTop = previousScrollTop; } }), observer(doc, "mouseup", function() { if (resizingLog) { resizingLog = previousScrollTop = False; } }), observer(resizer, "dblclick", function(evt) { evt.preventDefault(); if (previousHeight) { setContainerHeight(previousHeight); previousHeight = False; } else { previousHeight = container.clientHeight; containerStyle.height = "0px"; } }), observer(resizer, "mousedown", function(evt) { evt.preventDefault(); resizingLog = True; previousScrollTop = output.scrollTop; }), observer(resizer, "contextmenu", function() { resizingLog = False; }), observer(closeButton, "click", function() { uninit(); }) ]; uninit = function() { // remove observers var i = observers.length; while (i--) { unobserve.apply(tinylogLite, observers[i]); } // remove tinylog lite from the DOM docElem.removeChild(container); docElemStyle.paddingBottom = originalPadding; clearChildren(output); clearChildren(container); tinylogLite[log] = createLog; }; setStyles( container, containerStyles, output, outputStyles, resizer, resizerStyles, closeButton, closeButtonStyles); closeButton[$title] = "Close Log"; append(closeButton, createTextNode("\u2716")); resizer[$title] = "Double-click to toggle log minimization"; docElem.insertBefore(container, docElem.firstChild); tinylogLite[log] = function(message) { var entry = append(output, createElement($div)), entryText = append(entry, createElement($div)); entry[$title] = (new Date()).toLocaleTimeString(); setStyles( entry, entryStyles, entryText, entryTextStyles); append(entryText, createTextNode(message)); output.scrollTop = output.scrollHeight; }; tinylogLite[log](message); }; }()); } else if (typeof print === func) { // JS shell tinylogLite[log] = print; } return tinylogLite; }()), logBuffer = []; p.console = window.console || tinylogLite; p.println = function println(message) { var bufferLen = logBuffer.length; if (bufferLen) { tinylogLite.log(logBuffer.join("")); logBuffer.length = 0; // clear log buffer } if (arguments.length === 0 && bufferLen === 0) { tinylogLite.log(""); } else if (arguments.length !== 0) { tinylogLite.log(message); } }; p.print = function print(message) { logBuffer.push(message); }; // Alphanumeric chars arguments automatically converted to numbers when // passed in, and will come out as numbers. p.str = function str(val) { var ret; if (arguments.length === 1) { if (typeof val === "string" && val.length === 1) { // No strings allowed. ret = val; } else if (typeof val === "object" && val.constructor === Array) { ret = new Array(0); for (var i = 0; i < val.length; i++) { ret[i] = str(val[i]); } } else { ret = val + ""; } } return ret; }; p.trim = function(str) { var newstr; if (typeof str === "object" && str.constructor === Array) { newstr = new Array(0); for (var i = 0; i < str.length; i++) { newstr[i] = p.trim(str[i]); } } else { // if str is not an array then remove all whitespace, tabs, and returns newstr = str.replace(/^\s*/, '').replace(/\s*$/, '').replace(/\r*$/, ''); } return newstr; }; // Conversion p['boolean'] = function(val) { if (typeof val === 'number') { return val !== 0; } else if (typeof val === 'boolean') { return val; } else if (typeof val === 'string') { return val.toLowerCase() === 'true'; } else if (val instanceof Char) { // 1, T or t return val.code === 49 || val.code === 84 || val.code === 116; } else if (typeof val === 'object' && val.constructor === Array) { var ret = new Array(val.length); for (var i = 0; i < val.length; i++) { ret[i] = p['boolean'](val[i]); } return ret; } }; // a byte is a number between -128 and 127 p['byte'] = function(aNumber) { if (typeof aNumber === 'object' && aNumber.constructor === Array) { var bytes = []; for (var i = 0; i < aNumber.length; i++) { bytes[i] = p['byte'](aNumber[i]); } return bytes; } else { return (0 - (aNumber & 0x80)) | (aNumber & 0x7F); } }; p['char'] = function(key) { if (arguments.length === 1 && typeof key === "number") { return new Char(String.fromCharCode(key & 0xFFFF)); } else if (arguments.length === 1 && typeof key === "object" && key.constructor === Array) { var ret = new Array(key.length); for (var i = 0; i < key.length; i++) { ret[i] = p['char'](key[i]); } return ret; } else { throw "char() may receive only one argument of type int, byte, int[], or byte[]."; } }; // Processing doc claims good argument types are: int, char, byte, boolean, // String, int[], char[], byte[], boolean[], String[]. // floats should not work. However, floats with only zeroes right of the // decimal will work because JS converts those to int. p['float'] = function(val) { if (arguments.length === 1) { if (typeof val === 'number') { return val; } else if (typeof val === 'boolean') { return val ? 1 : 0; } else if (typeof val === 'string') { return parseFloat(val); } else if (val instanceof Char) { return val.code; } else if (typeof val === 'object' && val.constructor === Array) { var ret = new Array(val.length); for (var i = 0; i < val.length; i++) { ret[i] = p['float'](val[i]); } return ret; } } }; p['int'] = function(val) { if (typeof val === 'number') { return val & 0xFFFFFFFF; } else if (typeof val === 'boolean') { return val ? 1 : 0; } else if (typeof val === 'string') { var number = parseInt(val, 10); // Force decimal radix. Don't convert hex or octal (just like p5) return number & 0xFFFFFFFF; } else if (val instanceof Char) { return val.code; } else if (typeof val === 'object' && val.constructor === Array) { var ret = new Array(val.length); for (var i = 0; i < val.length; i++) { if (typeof val[i] === 'string' && !/^\s*[+\-]?\d+\s*$/.test(val[i])) { ret[i] = 0; } else { ret[i] = p['int'](val[i]); } } return ret; } }; //////////////////////////////////////////////////////////////////////////// // Math functions //////////////////////////////////////////////////////////////////////////// // Calculation p.abs = Math.abs; p.ceil = Math.ceil; p.constrain = function(aNumber, aMin, aMax) { return aNumber > aMax ? aMax : aNumber < aMin ? aMin : aNumber; }; p.dist = function() { var dx, dy, dz; if (arguments.length === 4) { dx = arguments[0] - arguments[2]; dy = arguments[1] - arguments[3]; return Math.sqrt(dx * dx + dy * dy); } else if (arguments.length === 6) { dx = arguments[0] - arguments[3]; dy = arguments[1] - arguments[4]; dz = arguments[2] - arguments[5]; return Math.sqrt(dx * dx + dy * dy + dz * dz); } }; p.exp = Math.exp; p.floor = Math.floor; p.lerp = function(value1, value2, amt) { return ((value2 - value1) * amt) + value1; }; p.log = Math.log; p.mag = function(a, b, c) { if (arguments.length === 2) { return Math.sqrt(a * a + b * b); } else if (arguments.length === 3) { return Math.sqrt(a * a + b * b + c * c); } }; p.map = function(value, istart, istop, ostart, ostop) { return ostart + (ostop - ostart) * ((value - istart) / (istop - istart)); }; p.max = function() { if (arguments.length === 2) { return arguments[0] < arguments[1] ? arguments[1] : arguments[0]; } else { var numbers = arguments.length === 1 ? arguments[0] : arguments; // if single argument, array is used if (! ("length" in numbers && numbers.length > 0)) { throw "Non-empty array is expected"; } var max = numbers[0], count = numbers.length; for (var i = 1; i < count; ++i) { if (max < numbers[i]) { max = numbers[i]; } } return max; } }; p.min = function() { if (arguments.length === 2) { return arguments[0] < arguments[1] ? arguments[0] : arguments[1]; } else { var numbers = arguments.length === 1 ? arguments[0] : arguments; // if single argument, array is used if (! ("length" in numbers && numbers.length > 0)) { throw "Non-empty array is expected"; } var min = numbers[0], count = numbers.length; for (var i = 1; i < count; ++i) { if (min > numbers[i]) { min = numbers[i]; } } return min; } }; p.norm = function(aNumber, low, high) { return (aNumber - low) / (high - low); }; p.pow = Math.pow; p.round = Math.round; p.sq = function(aNumber) { return aNumber * aNumber; }; p.sqrt = Math.sqrt; // Trigonometry p.acos = Math.acos; p.asin = Math.asin; p.atan = Math.atan; p.atan2 = Math.atan2; p.cos = Math.cos; p.degrees = function(aAngle) { return (aAngle * 180) / Math.PI; }; p.radians = function(aAngle) { return (aAngle / 180) * Math.PI; }; p.sin = Math.sin; p.tan = Math.tan; var currentRandom = Math.random; p.random = function random() { if(arguments.length === 0) { return currentRandom(); } else if(arguments.length === 1) { return currentRandom() * arguments[0]; } else { var aMin = arguments[0], aMax = arguments[1]; return currentRandom() * (aMax - aMin) + aMin; } }; // Pseudo-random generator function Marsaglia(i1, i2) { // from http://www.math.uni-bielefeld.de/~sillke/ALGORITHMS/random/marsaglia-c var z=i1 || 362436069, w= i2 || 521288629; var nextInt = function() { z=(36969*(z&65535)+(z>>>16)) & 0xFFFFFFFF; w=(18000*(w&65535)+(w>>>16)) & 0xFFFFFFFF; return (((z&0xFFFF)<<16) | (w&0xFFFF)) & 0xFFFFFFFF; }; this.nextDouble = function() { var i = nextInt() / 4294967296; return i < 0 ? 1 + i : i; }; this.nextInt = nextInt; } Marsaglia.createRandomized = function() { var now = new Date(); return new Marsaglia((now / 60000) & 0xFFFFFFFF, now & 0xFFFFFFFF); }; p.randomSeed = function(seed) { currentRandom = (new Marsaglia(seed)).nextDouble; }; // Random p.Random = function(seed) { var haveNextNextGaussian = false, nextNextGaussian, random; this.nextGaussian = function() { if (haveNextNextGaussian) { haveNextNextGaussian = false; return nextNextGaussian; } else { var v1, v2, s; do { v1 = 2 * random() - 1; // between -1.0 and 1.0 v2 = 2 * random() - 1; // between -1.0 and 1.0 s = v1 * v1 + v2 * v2; } while (s >= 1 || s === 0); var multiplier = Math.sqrt(-2 * Math.log(s) / s); nextNextGaussian = v2 * multiplier; haveNextNextGaussian = true; return v1 * multiplier; } }; // by default use standard random, otherwise seeded random = seed === undefined ? Math.random : (new Marsaglia(seed)).nextDouble; }; // Noise functions and helpers function PerlinNoise(seed) { var rnd = seed !== undefined ? new Marsaglia(seed) : Marsaglia.createRandomized(); var i, j; // http://www.noisemachine.com/talk1/17b.html // http://mrl.nyu.edu/~perlin/noise/ // generate permutation var p = new Array(512); for(i=0;i<256;++i) { p[i] = i; } for(i=0;i<256;++i) { var t = p[j = rnd.nextInt() & 0xFF]; p[j] = p[i]; p[i] = t; } // copy to avoid taking mod in p[0]; for(i=0;i<256;++i) { p[i + 256] = p[i]; } function grad3d(i,x,y,z) { var h = i & 15; // convert into 12 gradient directions var u = h<8 ? x : y, v = h<4 ? y : h===12||h===14 ? x : z; return ((h&1) === 0 ? u : -u) + ((h&2) === 0 ? v : -v); } function grad2d(i,x,y) { var v = (i & 1) === 0 ? x : y; return (i&2) === 0 ? -v : v; } function grad1d(i,x) { return (i&1) === 0 ? -x : x; } function lerp(t,a,b) { return a + t * (b - a); } this.noise3d = function(x, y, z) { var X = Math.floor(x)&255, Y = Math.floor(y)&255, Z = Math.floor(z)&255; x -= Math.floor(x); y -= Math.floor(y); z -= Math.floor(z); var fx = (3-2*x)*x*x, fy = (3-2*y)*y*y, fz = (3-2*z)*z*z; var p0 = p[X]+Y, p00 = p[p0] + Z, p01 = p[p0 + 1] + Z, p1 = p[X + 1] + Y, p10 = p[p1] + Z, p11 = p[p1 + 1] + Z; return lerp(fz, lerp(fy, lerp(fx, grad3d(p[p00], x, y, z), grad3d(p[p10], x-1, y, z)), lerp(fx, grad3d(p[p01], x, y-1, z), grad3d(p[p11], x-1, y-1,z))), lerp(fy, lerp(fx, grad3d(p[p00 + 1], x, y, z-1), grad3d(p[p10 + 1], x-1, y, z-1)), lerp(fx, grad3d(p[p01 + 1], x, y-1, z-1), grad3d(p[p11 + 1], x-1, y-1,z-1)))); }; this.noise2d = function(x, y) { var X = Math.floor(x)&255, Y = Math.floor(y)&255; x -= Math.floor(x); y -= Math.floor(y); var fx = (3-2*x)*x*x, fy = (3-2*y)*y*y; var p0 = p[X]+Y, p1 = p[X + 1] + Y; return lerp(fy, lerp(fx, grad2d(p[p0], x, y), grad2d(p[p1], x-1, y)), lerp(fx, grad2d(p[p0 + 1], x, y-1), grad2d(p[p1 + 1], x-1, y-1))); }; this.noise1d = function(x) { var X = Math.floor(x)&255; x -= Math.floor(x); var fx = (3-2*x)*x*x; return lerp(fx, grad1d(p[X], x), grad1d(p[X+1], x-1)); }; } // processing defaults var noiseProfile = { generator: undefined, octaves: 4, fallout: 0.5, seed: undefined}; p.noise = function(x, y, z) { if(noiseProfile.generator === undefined) { // caching noiseProfile.generator = new PerlinNoise(noiseProfile.seed); } var generator = noiseProfile.generator; var effect = 1, k = 1, sum = 0; for(var i=0; i<noiseProfile.octaves; ++i) { effect *= noiseProfile.fallout; switch (arguments.length) { case 1: sum += effect * (1 + generator.noise1d(k*x))/2; break; case 2: sum += effect * (1 + generator.noise2d(k*x, k*y))/2; break; case 3: sum += effect * (1 + generator.noise3d(k*x, k*y, k*z))/2; break; } k *= 2; } return sum; }; p.noiseDetail = function(octaves, fallout) { noiseProfile.octaves = octaves; if(fallout !== undefined) { noiseProfile.fallout = fallout; } }; p.noiseSeed = function(seed) { noiseProfile.seed = seed; noiseProfile.generator = undefined; }; // Changes the size of the Canvas ( this resets context properties like 'lineCap', etc. p.size = function size(aWidth, aHeight, aMode) { if (aMode && (aMode === p.WEBGL)) { // get the 3D rendering context try { // If the HTML <canvas> dimensions differ from the // dimensions specified in the size() call in the sketch, for // 3D sketches, browsers will either not render or render the // scene incorrectly. To fix this, we need to adjust the // width and height attributes of the canvas. if (curElement.width !== aWidth || curElement.height !== aHeight) { curElement.setAttribute("width", aWidth); curElement.setAttribute("height", aHeight); } curContext = curElement.getContext("experimental-webgl"); } catch(e_size) { p.debug(e_size); } if (!curContext) { throw "OPENGL 3D context is not supported on this browser."; } else { for (var i = 0; i < p.SINCOS_LENGTH; i++) { sinLUT[i] = p.sin(i * (p.PI / 180) * 0.5); cosLUT[i] = p.cos(i * (p.PI / 180) * 0.5); } // Set defaults curContext.viewport(0, 0, curElement.width, curElement.height); curContext.clearColor(204 / 255, 204 / 255, 204 / 255, 1.0); curContext.clear(curContext.COLOR_BUFFER_BIT); curContext.enable(curContext.DEPTH_TEST); curContext.enable(curContext.BLEND); curContext.blendFunc(curContext.SRC_ALPHA, curContext.ONE_MINUS_SRC_ALPHA); // Create the program objects to render 2D (points, lines) and // 3D (spheres, boxes) shapes. Because 2D shapes are not lit, // lighting calculations could be ommitted from that program object. programObject2D = createProgramObject(curContext, vertexShaderSource2D, fragmentShaderSource2D); programObject3D = createProgramObject(curContext, vertexShaderSource3D, fragmentShaderSource3D); // Now that the programs have been compiled, we can set the default // states for the lights. curContext.useProgram(programObject3D); p.lightFalloff(1, 0, 0); p.shininess(1); p.ambient(255, 255, 255); p.specular(0, 0, 0); // Create buffers for 3D primitives boxBuffer = curContext.createBuffer(); curContext.bindBuffer(curContext.ARRAY_BUFFER, boxBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, newWebGLArray(boxVerts), curContext.STATIC_DRAW); boxNormBuffer = curContext.createBuffer(); curContext.bindBuffer(curContext.ARRAY_BUFFER, boxNormBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, newWebGLArray(boxNorms), curContext.STATIC_DRAW); boxOutlineBuffer = curContext.createBuffer(); curContext.bindBuffer(curContext.ARRAY_BUFFER, boxOutlineBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, newWebGLArray(boxOutlineVerts), curContext.STATIC_DRAW); // The sphere vertices are specified dynamically since the user // can change the level of detail. Everytime the user does that // using sphereDetail(), the new vertices are calculated. sphereBuffer = curContext.createBuffer(); lineBuffer = curContext.createBuffer(); curContext.bindBuffer(curContext.ARRAY_BUFFER, lineBuffer); fillBuffer = curContext.createBuffer(); curContext.bindBuffer(curContext.ARRAY_BUFFER, fillBuffer); pointBuffer = curContext.createBuffer(); curContext.bindBuffer(curContext.ARRAY_BUFFER, pointBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, newWebGLArray([0, 0, 0]), curContext.STATIC_DRAW); cam = new PMatrix3D(); cameraInv = new PMatrix3D(); forwardTransform = new PMatrix3D(); reverseTransform = new PMatrix3D(); modelView = new PMatrix3D(); modelViewInv = new PMatrix3D(); projection = new PMatrix3D(); p.camera(); p.perspective(); forwardTransform = modelView; reverseTransform = modelViewInv; userMatrixStack = new PMatrixStack(); // used by both curve and bezier, so just init here curveBasisMatrix = new PMatrix3D(); curveToBezierMatrix = new PMatrix3D(); curveDrawMatrix = new PMatrix3D(); bezierBasisInverse = new PMatrix3D(); bezierBasisMatrix = new PMatrix3D(); bezierBasisMatrix.set(-1, 3, -3, 1, 3, -6, 3, 0, -3, 3, 0, 0, 1, 0, 0, 0); } p.stroke(0); p.fill(255); } else { if (typeof curContext === "undefined") { // size() was called without p.init() default context, ie. p.createGraphics() curContext = curElement.getContext("2d"); userMatrixStack = new PMatrixStack(); modelView = new PMatrix2D(); } } // The default 2d context has already been created in the p.init() stage if // a 3d context was not specified. This is so that a 2d context will be // available if size() was not called. var props = { fillStyle: curContext.fillStyle, strokeStyle: curContext.strokeStyle, lineCap: curContext.lineCap, lineJoin: curContext.lineJoin }; curElement.width = p.width = aWidth; curElement.height = p.height = aHeight; for (var j in props) { if (props) { curContext[j] = props[j]; } } // redraw the background if background was called before size refreshBackground(); p.context = curContext; // added for createGraphics p.toImageData = function() { return curContext.getImageData(0, 0, this.width, this.height); }; }; //////////////////////////////////////////////////////////////////////////// // 3D Functions //////////////////////////////////////////////////////////////////////////// /* Sets the uniform variable 'varName' to the value specified by 'value'. Before calling this function, make sure the correct program object has been installed as part of the current rendering state. On some systems, if the variable exists in the shader but isn't used, the compiler will optimize it out and this function will fail. */ function uniformf(programObj, varName, varValue) { var varLocation = curContext.getUniformLocation(programObj, varName); // the variable won't be found if it was optimized out. if (varLocation !== -1) { if (varValue.length === 4) { curContext.uniform4fv(varLocation, varValue); } else if (varValue.length === 3) { curContext.uniform3fv(varLocation, varValue); } else if (varValue.length === 2) { curContext.uniform2fv(varLocation, varValue); } else { curContext.uniform1f(varLocation, varValue); } } } function uniformi(programObj, varName, varValue) { var varLocation = curContext.getUniformLocation(programObj, varName); // the variable won't be found if it was optimized out. if (varLocation !== -1) { if (varValue.length === 4) { curContext.uniform4iv(varLocation, varValue); } else if (varValue.length === 3) { curContext.uniform3iv(varLocation, varValue); } else if (varValue.length === 2) { curContext.uniform2iv(varLocation, varValue); } else { curContext.uniform1i(varLocation, varValue); } } } function vertexAttribPointer(programObj, varName, size, VBO) { var varLocation = curContext.getAttribLocation(programObj, varName); if (varLocation !== -1) { curContext.bindBuffer(curContext.ARRAY_BUFFER, VBO); curContext.vertexAttribPointer(varLocation, size, curContext.FLOAT, false, 0, 0); curContext.enableVertexAttribArray(varLocation); } } function uniformMatrix(programObj, varName, transpose, matrix) { var varLocation = curContext.getUniformLocation(programObj, varName); // the variable won't be found if it was optimized out. if (varLocation !== -1) { if (matrix.length === 16) { curContext.uniformMatrix4fv(varLocation, transpose, matrix); } else if (matrix.length === 9) { curContext.uniformMatrix3fv(varLocation, transpose, matrix); } else { curContext.uniformMatrix2fv(varLocation, transpose, matrix); } } } //////////////////////////////////////////////////////////////////////////// // Lights //////////////////////////////////////////////////////////////////////////// p.ambientLight = function(r, g, b, x, y, z) { if (p.use3DContext) { if (lightCount === p.MAX_LIGHTS) { throw "can only create " + p.MAX_LIGHTS + " lights"; } var pos = new PVector(x, y, z); var view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); view.mult(pos, pos); curContext.useProgram(programObject3D); uniformf(programObject3D, "lights[" + lightCount + "].color", [r / 255, g / 255, b / 255]); uniformf(programObject3D, "lights[" + lightCount + "].position", pos.array()); uniformi(programObject3D, "lights[" + lightCount + "].type", 0); uniformi(programObject3D, "lightCount", ++lightCount); } }; p.directionalLight = function(r, g, b, nx, ny, nz) { if (p.use3DContext) { if (lightCount === p.MAX_LIGHTS) { throw "can only create " + p.MAX_LIGHTS + " lights"; } curContext.useProgram(programObject3D); // Less code than manually multiplying, but I'll fix // this when I have more time. var dir = [nx, ny, nz, 0.0000001]; var view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); view.mult(dir, dir); uniformf(programObject3D, "lights[" + lightCount + "].color", [r / 255, g / 255, b / 255]); uniformf(programObject3D, "lights[" + lightCount + "].position", [-dir[0], -dir[1], -dir[2]]); uniformi(programObject3D, "lights[" + lightCount + "].type", 1); uniformi(programObject3D, "lightCount", ++lightCount); } }; p.lightFalloff = function lightFalloff(constant, linear, quadratic) { if (p.use3DContext) { curContext.useProgram(programObject3D); uniformf(programObject3D, "falloff", [constant, linear, quadratic]); } }; p.lightSpecular = function lightSpecular(r, g, b) { if (p.use3DContext) { curContext.useProgram(programObject3D); uniformf(programObject3D, "specular", [r / 255, g / 255, b / 255]); } }; /* Sets the default ambient light, directional light, falloff, and specular values. P5 Documentation says specular() is set, but the code calls lightSpecular(). */ p.lights = function lights() { p.ambientLight(128, 128, 128); p.directionalLight(128, 128, 128, 0, 0, -1); p.lightFalloff(1, 0, 0); p.lightSpecular(0, 0, 0); }; p.pointLight = function(r, g, b, x, y, z) { if (p.use3DContext) { if (lightCount === p.MAX_LIGHTS) { throw "can only create " + p.MAX_LIGHTS + " lights"; } // place the point in view space once instead of once per vertex // in the shader. var pos = new PVector(x, y, z); var view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); view.mult(pos, pos); curContext.useProgram(programObject3D); uniformf(programObject3D, "lights[" + lightCount + "].color", [r / 255, g / 255, b / 255]); uniformf(programObject3D, "lights[" + lightCount + "].position", pos.array()); uniformi(programObject3D, "lights[" + lightCount + "].type", 2); uniformi(programObject3D, "lightCount", ++lightCount); } }; /* Disables lighting so the all shapes drawn after this will not be lit. */ p.noLights = function noLights() { if (p.use3DContext) { lightCount = 0; curContext.useProgram(programObject3D); uniformi(programObject3D, "lightCount", lightCount); } }; /* r,g,b - Color of the light x,y,z - position of the light in modeling space nx,ny,nz - direction of the spotlight angle - in radians concentration - */ p.spotLight = function spotLight(r, g, b, x, y, z, nx, ny, nz, angle, concentration) { if (p.use3DContext) { if (lightCount === p.MAX_LIGHTS) { throw "can only create " + p.MAX_LIGHTS + " lights"; } curContext.useProgram(programObject3D); // place the point in view space once instead of once per vertex // in the shader. var pos = new PVector(x, y, z); var view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); view.mult(pos, pos); // transform the spotlight's direction // need to find a solution for this one. Maybe manual mult? var dir = [nx, ny, nz, 0.0000001]; view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); view.mult(dir, dir); uniformf(programObject3D, "lights[" + lightCount + "].color", [r / 255, g / 255, b / 255]); uniformf(programObject3D, "lights[" + lightCount + "].position", pos.array()); uniformf(programObject3D, "lights[" + lightCount + "].direction", [dir[0], dir[1], dir[2]]); uniformf(programObject3D, "lights[" + lightCount + "].concentration", concentration); uniformf(programObject3D, "lights[" + lightCount + "].angle", angle); uniformi(programObject3D, "lights[" + lightCount + "].type", 3); uniformi(programObject3D, "lightCount", ++lightCount); } }; //////////////////////////////////////////////////////////////////////////// // Camera functions //////////////////////////////////////////////////////////////////////////// p.beginCamera = function beginCamera() { if (manipulatingCamera) { throw ("You cannot call beginCamera() again before calling endCamera()"); } else { manipulatingCamera = true; forwardTransform = cameraInv; reverseTransform = cam; } }; p.endCamera = function endCamera() { if (!manipulatingCamera) { throw ("You cannot call endCamera() before calling beginCamera()"); } else { modelView.set(cam); modelViewInv.set(cameraInv); forwardTransform = modelView; reverseTransform = modelViewInv; manipulatingCamera = false; } }; p.camera = function camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ) { if (arguments.length === 0) { //in case canvas is resized cameraX = curElement.width / 2; cameraY = curElement.height / 2; cameraZ = cameraY / Math.tan(cameraFOV / 2); p.camera(cameraX, cameraY, cameraZ, cameraX, cameraY, 0, 0, 1, 0); } else { var z = new p.PVector(eyeX - centerX, eyeY - centerY, eyeZ - centerZ); var y = new p.PVector(upX, upY, upZ); var transX, transY, transZ; z.normalize(); var x = p.PVector.cross(y, z); y = p.PVector.cross(z, x); x.normalize(); y.normalize(); cam.set(x.x, x.y, x.z, 0, y.x, y.y, y.z, 0, z.x, z.y, z.z, 0, 0, 0, 0, 1); cam.translate(-eyeX, -eyeY, -eyeZ); cameraInv.reset(); cameraInv.invApply(x.x, x.y, x.z, 0, y.x, y.y, y.z, 0, z.x, z.y, z.z, 0, 0, 0, 0, 1); cameraInv.translate(eyeX, eyeY, eyeZ); modelView.set(cam); modelViewInv.set(cameraInv); } }; p.perspective = function perspective(fov, aspect, near, far) { if (arguments.length === 0) { //in case canvas is resized cameraY = curElement.height / 2; cameraZ = cameraY / Math.tan(cameraFOV / 2); cameraNear = cameraZ / 10; cameraFar = cameraZ * 10; cameraAspect = curElement.width / curElement.height; p.perspective(cameraFOV, cameraAspect, cameraNear, cameraFar); } else { var a = arguments; var yMax, yMin, xMax, xMin; yMax = near * Math.tan(fov / 2); yMin = -yMax; xMax = yMax * aspect; xMin = yMin * aspect; p.frustum(xMin, xMax, yMin, yMax, near, far); } }; p.frustum = function frustum(left, right, bottom, top, near, far) { frustumMode = true; projection = new PMatrix3D(); projection.set((2 * near) / (right - left), 0, (right + left) / (right - left), 0, 0, (2 * near) / (top - bottom), (top + bottom) / (top - bottom), 0, 0, 0, -(far + near) / (far - near), -(2 * far * near) / (far - near), 0, 0, -1, 0); }; p.ortho = function ortho(left, right, bottom, top, near, far) { if (arguments.length === 0) { p.ortho(0, p.width, 0, p.height, -10, 10); } else { var x = 2 / (right - left); var y = 2 / (top - bottom); var z = -2 / (far - near); var tx = -(right + left) / (right - left); var ty = -(top + bottom) / (top - bottom); var tz = -(far + near) / (far - near); projection = new PMatrix3D(); projection.set(x, 0, 0, tx, 0, y, 0, ty, 0, 0, z, tz, 0, 0, 0, 1); frustumMode = false; } }; p.printProjection = function() { projection.print(); }; p.printCamera = function() { cam.print(); }; //////////////////////////////////////////////////////////////////////////// // Shapes //////////////////////////////////////////////////////////////////////////// p.box = function(w, h, d) { if (p.use3DContext) { // user can uniformly scale the box by // passing in only one argument. if (!h || !d) { h = d = w; } // Modeling transformation var model = new PMatrix3D(); model.scale(w, h, d); // viewing transformation needs to have Y flipped // becuase that's what Processing does. var view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); curContext.useProgram(programObject3D); uniformMatrix(programObject3D, "model", true, model.array()); uniformMatrix(programObject3D, "view", true, view.array()); uniformMatrix(programObject3D, "projection", true, projection.array()); if (doFill === true) { // fix stitching problems. (lines get occluded by triangles // since they share the same depth values). This is not entirely // working, but it's a start for drawing the outline. So // developers can start playing around with styles. curContext.enable(curContext.POLYGON_OFFSET_FILL); curContext.polygonOffset(1, 1); uniformf(programObject3D, "color", fillStyle); var v = new PMatrix3D(); v.set(view); var m = new PMatrix3D(); m.set(model); v.mult(m); var normalMatrix = new PMatrix3D(); normalMatrix.set(v); normalMatrix.invert(); uniformMatrix(programObject3D, "normalTransform", false, normalMatrix.array()); vertexAttribPointer(programObject3D, "Vertex", 3, boxBuffer); vertexAttribPointer(programObject3D, "Normal", 3, boxNormBuffer); curContext.drawArrays(curContext.TRIANGLES, 0, boxVerts.length / 3); curContext.disable(curContext.POLYGON_OFFSET_FILL); } if (lineWidth > 0 && doStroke) { curContext.useProgram(programObject3D); uniformMatrix(programObject3D, "model", true, model.array()); uniformMatrix(programObject3D, "view", true, view.array()); uniformMatrix(programObject3D, "projection", true, projection.array()); uniformf(programObject3D, "color", strokeStyle); curContext.lineWidth(lineWidth); vertexAttribPointer(programObject3D, "Vertex", 3, boxOutlineBuffer); curContext.drawArrays(curContext.LINES, 0, boxOutlineVerts.length / 3); } } }; var initSphere = function() { var i; sphereVerts = []; for (i = 0; i < sphereDetailU; i++) { sphereVerts.push(0); sphereVerts.push(-1); sphereVerts.push(0); sphereVerts.push(sphereX[i]); sphereVerts.push(sphereY[i]); sphereVerts.push(sphereZ[i]); } sphereVerts.push(0); sphereVerts.push(-1); sphereVerts.push(0); sphereVerts.push(sphereX[0]); sphereVerts.push(sphereY[0]); sphereVerts.push(sphereZ[0]); var v1, v11, v2; // middle rings var voff = 0; for (i = 2; i < sphereDetailV; i++) { v1 = v11 = voff; voff += sphereDetailU; v2 = voff; for (var j = 0; j < sphereDetailU; j++) { sphereVerts.push(parseFloat(sphereX[v1])); sphereVerts.push(parseFloat(sphereY[v1])); sphereVerts.push(parseFloat(sphereZ[v1++])); sphereVerts.push(parseFloat(sphereX[v2])); sphereVerts.push(parseFloat(sphereY[v2])); sphereVerts.push(parseFloat(sphereZ[v2++])); } // close each ring v1 = v11; v2 = voff; sphereVerts.push(parseFloat(sphereX[v1])); sphereVerts.push(parseFloat(sphereY[v1])); sphereVerts.push(parseFloat(sphereZ[v1])); sphereVerts.push(parseFloat(sphereX[v2])); sphereVerts.push(parseFloat(sphereY[v2])); sphereVerts.push(parseFloat(sphereZ[v2])); } // add the northern cap for (i = 0; i < sphereDetailU; i++) { v2 = voff + i; sphereVerts.push(parseFloat(sphereX[v2])); sphereVerts.push(parseFloat(sphereY[v2])); sphereVerts.push(parseFloat(sphereZ[v2])); sphereVerts.push(0); sphereVerts.push(1); sphereVerts.push(0); } sphereVerts.push(parseFloat(sphereX[voff])); sphereVerts.push(parseFloat(sphereY[voff])); sphereVerts.push(parseFloat(sphereZ[voff])); sphereVerts.push(0); sphereVerts.push(1); sphereVerts.push(0); //set the buffer data curContext.bindBuffer(curContext.ARRAY_BUFFER, sphereBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, newWebGLArray(sphereVerts), curContext.STATIC_DRAW); }; p.sphereDetail = function sphereDetail(ures, vres) { var i; if (arguments.length === 1) { ures = vres = arguments[0]; } if (ures < 3) { ures = 3; } // force a minimum res if (vres < 2) { vres = 2; } // force a minimum res // if it hasn't changed do nothing if ((ures === sphereDetailU) && (vres === sphereDetailV)) { return; } var delta = p.SINCOS_LENGTH / ures; var cx = new Array(ures); var cz = new Array(ures); // calc unit circle in XZ plane for (i = 0; i < ures; i++) { cx[i] = cosLUT[parseInt((i * delta) % p.SINCOS_LENGTH, 10)]; cz[i] = sinLUT[parseInt((i * delta) % p.SINCOS_LENGTH, 10)]; } // computing vertexlist // vertexlist starts at south pole var vertCount = ures * (vres - 1) + 2; var currVert = 0; // re-init arrays to store vertices sphereX = new Array(vertCount); sphereY = new Array(vertCount); sphereZ = new Array(vertCount); var angle_step = (p.SINCOS_LENGTH * 0.5) / vres; var angle = angle_step; // step along Y axis for (i = 1; i < vres; i++) { var curradius = sinLUT[parseInt(angle % p.SINCOS_LENGTH, 10)]; var currY = -cosLUT[parseInt(angle % p.SINCOS_LENGTH, 10)]; for (var j = 0; j < ures; j++) { sphereX[currVert] = cx[j] * curradius; sphereY[currVert] = currY; sphereZ[currVert++] = cz[j] * curradius; } angle += angle_step; } sphereDetailU = ures; sphereDetailV = vres; // make the sphere verts and norms initSphere(); }; p.sphere = function() { if (p.use3DContext) { var sRad = arguments[0], c; if ((sphereDetailU < 3) || (sphereDetailV < 2)) { p.sphereDetail(30); } // Modeling transformation var model = new PMatrix3D(); model.scale(sRad, sRad, sRad); // viewing transformation needs to have Y flipped // becuase that's what Processing does. var view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); curContext.useProgram(programObject3D); uniformMatrix(programObject3D, "model", true, model.array()); uniformMatrix(programObject3D, "view", true, view.array()); uniformMatrix(programObject3D, "projection", true, projection.array()); var v = new PMatrix3D(); v.set(view); var m = new PMatrix3D(); m.set(model); v.mult(m); var normalMatrix = new PMatrix3D(); normalMatrix.set(v); normalMatrix.invert(); uniformMatrix(programObject3D, "normalTransform", false, normalMatrix.array()); vertexAttribPointer(programObject3D, "Vertex", 3, sphereBuffer); vertexAttribPointer(programObject3D, "Normal", 3, sphereBuffer); if (doFill === true) { // fix stitching problems. (lines get occluded by triangles // since they share the same depth values). This is not entirely // working, but it's a start for drawing the outline. So // developers can start playing around with styles. curContext.enable(curContext.POLYGON_OFFSET_FILL); curContext.polygonOffset(1, 1); uniformf(programObject3D, "color", fillStyle); curContext.drawArrays(curContext.TRIANGLE_STRIP, 0, sphereVerts.length / 3); curContext.disable(curContext.POLYGON_OFFSET_FILL); } if (lineWidth > 0 && doStroke) { curContext.useProgram(programObject3D); vertexAttribPointer(programObject3D, "Vertex", 3, sphereBuffer); uniformMatrix(programObject3D, "model", true, model.array()); uniformMatrix(programObject3D, "view", true, view.array()); uniformMatrix(programObject3D, "projection", true, projection.array()); uniformf(programObject3D, "color", strokeStyle); curContext.lineWidth(lineWidth); curContext.drawArrays(curContext.LINE_STRIP, 0, sphereVerts.length / 3); } } }; //////////////////////////////////////////////////////////////////////////// // Coordinates //////////////////////////////////////////////////////////////////////////// p.modelX = function modelX(x, y, z) { var mv = modelView.array(); var ci = cameraInv.array(); var ax = mv[0] * x + mv[1] * y + mv[2] * z + mv[3]; var ay = mv[4] * x + mv[5] * y + mv[6] * z + mv[7]; var az = mv[8] * x + mv[9] * y + mv[10] * z + mv[11]; var aw = mv[12] * x + mv[13] * y + mv[14] * z + mv[15]; var ox = ci[0] * ax + ci[1] * ay + ci[2] * az + ci[3] * aw; var ow = ci[12] * ax + ci[13] * ay + ci[14] * az + ci[15] * aw; return (ow !== 0) ? ox / ow : ox; }; p.modelY = function modelY(x, y, z) { var mv = modelView.array(); var ci = cameraInv.array(); var ax = mv[0] * x + mv[1] * y + mv[2] * z + mv[3]; var ay = mv[4] * x + mv[5] * y + mv[6] * z + mv[7]; var az = mv[8] * x + mv[9] * y + mv[10] * z + mv[11]; var aw = mv[12] * x + mv[13] * y + mv[14] * z + mv[15]; var oy = ci[4] * ax + ci[5] * ay + ci[6] * az + ci[7] * aw; var ow = ci[12] * ax + ci[13] * ay + ci[14] * az + ci[15] * aw; return (ow !== 0) ? oy / ow : oy; }; p.modelZ = function modelZ(x, y, z) { var mv = modelView.array(); var ci = cameraInv.array(); var ax = mv[0] * x + mv[1] * y + mv[2] * z + mv[3]; var ay = mv[4] * x + mv[5] * y + mv[6] * z + mv[7]; var az = mv[8] * x + mv[9] * y + mv[10] * z + mv[11]; var aw = mv[12] * x + mv[13] * y + mv[14] * z + mv[15]; var oz = ci[8] * ax + ci[9] * ay + ci[10] * az + ci[11] * aw; var ow = ci[12] * ax + ci[13] * ay + ci[14] * az + ci[15] * aw; return (ow !== 0) ? oz / ow : oz; }; //////////////////////////////////////////////////////////////////////////// // Material Properties //////////////////////////////////////////////////////////////////////////// p.ambient = function ambient() { // create an alias to shorten code var a = arguments; // either a shade of gray or a 'color' object. if (p.use3DContext) { curContext.useProgram(programObject3D); uniformi(programObject3D, "usingMat", true); if (a.length === 1) { // color object was passed in if (typeof a[0] === "string") { var c = a[0].slice(5, -1).split(","); uniformf(programObject3D, "mat_ambient", [c[0] / 255, c[1] / 255, c[2] / 255]); } // else a single number was passed in for gray shade else { uniformf(programObject3D, "mat_ambient", [a[0] / 255, a[0] / 255, a[0] / 255]); } } // Otherwise three values were provided (r,g,b) else { uniformf(programObject3D, "mat_ambient", [a[0] / 255, a[1] / 255, a[2] / 255]); } } }; p.emissive = function emissive() { // create an alias to shorten code var a = arguments; if (p.use3DContext) { curContext.useProgram(programObject3D); uniformi(programObject3D, "usingMat", true); // If only one argument was provided, the user either gave us a // shade of gray or a 'color' object. if (a.length === 1) { // color object was passed in if (typeof a[0] === "string") { var c = a[0].slice(5, -1).split(","); uniformf(programObject3D, "mat_emissive", [c[0] / 255, c[1] / 255, c[2] / 255]); } // else a regular number was passed in for gray shade else { uniformf(programObject3D, "mat_emissive", [a[0] / 255, a[0] / 255, a[0] / 255]); } } // Otherwise three values were provided (r,g,b) else { uniformf(programObject3D, "mat_emissive", [a[0] / 255, a[1] / 255, a[2] / 255]); } } }; p.shininess = function shininess(shine) { if (p.use3DContext) { curContext.useProgram(programObject3D); uniformi(programObject3D, "usingMat", true); uniformf(programObject3D, "shininess", shine); } }; /* Documentation says the following calls are valid, but the Processing throws exceptions: specular(gray, alpha) specular(v1, v2, v3, alpha) So we don't support them either <corban> I dont think this matters so much, let us let color handle it. alpha values are not sent anyways. */ p.specular = function specular() { var c = p.color.apply(this, arguments); if (p.use3DContext) { curContext.useProgram(programObject3D); uniformi(programObject3D, "usingMat", true); uniformf(programObject3D, "mat_specular", p.color.toGLArray(c).slice(0, 3)); } }; //////////////////////////////////////////////////////////////////////////// // Coordinates //////////////////////////////////////////////////////////////////////////// p.screenX = function screenX( x, y, z ) { var mv = modelView.array(); var pj = projection.array(); var ax = mv[ 0]*x + mv[ 1]*y + mv[ 2]*z + mv[ 3]; var ay = mv[ 4]*x + mv[ 5]*y + mv[ 6]*z + mv[ 7]; var az = mv[ 8]*x + mv[ 9]*y + mv[10]*z + mv[11]; var aw = mv[12]*x + mv[13]*y + mv[14]*z + mv[15]; var ox = pj[ 0]*ax + pj[ 1]*ay + pj[ 2]*az + pj[ 3]*aw; var ow = pj[12]*ax + pj[13]*ay + pj[14]*az + pj[15]*aw; if ( ow !== 0 ){ ox /= ow; } return p.width * ( 1 + ox ) / 2.0; }; p.screenY = function screenY( x, y, z ) { var mv = modelView.array(); var pj = projection.array(); var ax = mv[ 0]*x + mv[ 1]*y + mv[ 2]*z + mv[ 3]; var ay = mv[ 4]*x + mv[ 5]*y + mv[ 6]*z + mv[ 7]; var az = mv[ 8]*x + mv[ 9]*y + mv[10]*z + mv[11]; var aw = mv[12]*x + mv[13]*y + mv[14]*z + mv[15]; var oy = pj[ 4]*ax + pj[ 5]*ay + pj[ 6]*az + pj[ 7]*aw; var ow = pj[12]*ax + pj[13]*ay + pj[14]*az + pj[15]*aw; if ( ow !== 0 ){ oy /= ow; } return p.height * ( 1 + oy ) / 2.0; }; p.screenZ = function screenZ( x, y, z ) { var mv = modelView.array(); var pj = projection.array(); var ax = mv[ 0]*x + mv[ 1]*y + mv[ 2]*z + mv[ 3]; var ay = mv[ 4]*x + mv[ 5]*y + mv[ 6]*z + mv[ 7]; var az = mv[ 8]*x + mv[ 9]*y + mv[10]*z + mv[11]; var aw = mv[12]*x + mv[13]*y + mv[14]*z + mv[15]; var oz = pj[ 8]*ax + pj[ 9]*ay + pj[10]*az + pj[11]*aw; var ow = pj[12]*ax + pj[13]*ay + pj[14]*az + pj[15]*aw; if ( ow !== 0 ) { oz /= ow; } return ( oz + 1 ) / 2.0; }; //////////////////////////////////////////////////////////////////////////// // Style functions //////////////////////////////////////////////////////////////////////////// p.fill = function fill() { doFill = true; var color = p.color(arguments[0], arguments[1], arguments[2], arguments[3]); if (p.use3DContext) { fillStyle = p.color.toGLArray(color); } else { curContext.fillStyle = p.color.toString(color); } }; p.noFill = function noFill() { doFill = false; }; p.stroke = function stroke() { doStroke = true; var color = p.color(arguments[0], arguments[1], arguments[2], arguments[3]); if (p.use3DContext) { strokeStyle = p.color.toGLArray(color); } else { curContext.strokeStyle = p.color.toString(color); } }; p.noStroke = function noStroke() { doStroke = false; }; p.strokeWeight = function strokeWeight(w) { if (p.use3DContext) { lineWidth = w; } else { curContext.lineWidth = w; } }; p.strokeCap = function strokeCap(value) { curContext.lineCap = value; }; p.strokeJoin = function strokeJoin(value) { curContext.lineJoin = value; }; p.smooth = function() { if (!p.use3DContext) { curElement.style.setProperty("image-rendering", "optimizeQuality", "important"); curContext.mozImageSmoothingEnabled = true; } }; p.noSmooth = function() { if (!p.use3DContext) { curElement.style.setProperty("image-rendering", "optimizeSpeed", "important"); curContext.mozImageSmoothingEnabled = false; } }; //////////////////////////////////////////////////////////////////////////// // Vector drawing functions //////////////////////////////////////////////////////////////////////////// p.Point = function Point(x, y) { this.x = x; this.y = y; this.copy = function() { return new Point(x, y); }; }; p.point = function point(x, y, z) { if (p.use3DContext) { var model = new PMatrix3D(); // move point to position model.translate(x, y, z || 0); var view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); curContext.useProgram(programObject2D); uniformMatrix(programObject2D, "model", true, model.array()); uniformMatrix(programObject2D, "view", true, view.array()); uniformMatrix(programObject2D, "projection", true, projection.array()); if (lineWidth > 0 && doStroke) { // this will be replaced with the new bit shifting color code uniformf(programObject2D, "color", strokeStyle); vertexAttribPointer(programObject2D, "Vertex", 3, pointBuffer); curContext.drawArrays(curContext.POINTS, 0, 1); } } else { if (doStroke) { var oldFill = curContext.fillStyle; curContext.fillStyle = curContext.strokeStyle; curContext.fillRect(Math.round(x), Math.round(y), 1, 1); curContext.fillStyle = oldFill; } } }; p.beginShape = function beginShape(type) { curShape = type; curShapeCount = 0; curvePoints = []; //textureImage = null; vertArray = []; if(p.use3DContext) { //normalMode = NORMAL_MODE_AUTO; } }; p.vertex = function vertex() { if(firstVert){ firstVert = false; } var vert = []; if(arguments.length === 4){ //x, y, u, v vert[0] = arguments[0]; vert[1] = arguments[1]; vert[2] = 0; vert[3] = arguments[2]; vert[4] = arguments[3]; } else{ // x, y, z, u, v vert[0] = arguments[0]; vert[1] = arguments[1]; vert[2] = arguments[2] || 0; vert[3] = arguments[3] || 0; vert[4] = arguments[4] || 0; } // fill rgba vert[5] = fillStyle[0]; vert[6] = fillStyle[1]; vert[7] = fillStyle[2]; vert[8] = fillStyle[3]; // stroke rgba vert[9] = strokeStyle[0]; vert[10] = strokeStyle[1]; vert[11] = strokeStyle[2]; vert[12] = strokeStyle[3]; //normals vert[13] = normalX; vert[14] = normalY; vert[15] = normalZ; vertArray.push(vert); }; var point2D = function point2D(vArray){ var model = new PMatrix3D(); var view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); curContext.useProgram(programObject2D); uniformMatrix(programObject2D, "model", true, model.array()); uniformMatrix(programObject2D, "view", true, view.array()); uniformMatrix(programObject2D, "projection", true, projection.array()); uniformf(programObject2D, "color", strokeStyle); vertexAttribPointer(programObject2D, "Vertex", 3, pointBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, newWebGLArray(vArray), curContext.STREAM_DRAW); curContext.drawArrays(curContext.POINTS, 0, vArray.length/3); }; var line2D = function line2D(vArray, mode){ var ctxMode; if (mode === "LINES"){ ctxMode = curContext.LINES; } else if(mode === "LINE_LOOP"){ ctxMode = curContext.LINE_LOOP; } else{ ctxMode = curContext.LINE_STRIP; } var model = new PMatrix3D(); var view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); curContext.useProgram(programObject2D); uniformMatrix(programObject2D, "model", true, model.array()); uniformMatrix(programObject2D, "view", true, view.array()); uniformMatrix(programObject2D, "projection", true, projection.array()); uniformf(programObject2D, "color", strokeStyle); vertexAttribPointer(programObject2D, "Vertex", 3, lineBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, newWebGLArray(vArray), curContext.STREAM_DRAW); curContext.drawArrays(ctxMode, 0, vArray.length/3); }; var fill2D = function fill2D(vArray, mode){ var ctxMode; if(mode === "TRIANGLES"){ ctxMode = curContext.TRIANGLES; } else if(mode === "TRIANGLE_FAN"){ ctxMode = curContext.TRIANGLE_FAN; } else{ ctxMode = curContext.TRIANGLE_STRIP; } var model = new PMatrix3D(); var view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); curContext.useProgram( programObject2D ); uniformMatrix( programObject2D, "model", true, model.array() ); uniformMatrix( programObject2D, "view", true, view.array() ); uniformMatrix( programObject2D, "projection", true, projection.array() ); curContext.enable( curContext.POLYGON_OFFSET_FILL ); curContext.polygonOffset( 1, 1 ); uniformf( programObject2D, "color", fillStyle); vertexAttribPointer(programObject2D, "Vertex", 3, fillBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, newWebGLArray(vArray), curContext.STREAM_DRAW); curContext.drawArrays( ctxMode, 0, vArray.length/3 ); curContext.disable( curContext.POLYGON_OFFSET_FILL ); }; p.endShape = function endShape(close){ firstVert = true; var i, j, k; var last = vertArray.length - 1; if(!close){ p.CLOSE = false; } else{ p.CLOSE = true; } if(isCurve && curShape === p.POLYGON || isCurve && curShape === undefined){ if(vertArray.length > 3){ if(p.use3DContext){ } else{ var b = [], s = 1 - curTightness; curContext.beginPath(); curContext.moveTo(vertArray[1][0], vertArray[1][1]); /* * Matrix to convert from Catmull-Rom to cubic Bezier * where t = curTightness * |0 1 0 0 | * |(t-1)/6 1 (1-t)/6 0 | * |0 (1-t)/6 1 (t-1)/6 | * |0 0 0 0 | */ for(i = 1; (i+2) < vertArray.length; i++){ b[0] = [vertArray[i][0], vertArray[i][1]]; b[1] = [vertArray[i][0] + (s * vertArray[i+1][0] - s * vertArray[i-1][0]) / 6, vertArray[i][1] + (s * vertArray[i+1][1] - s * vertArray[i-1][1]) / 6]; b[2] = [vertArray[i+1][0] + (s * vertArray[i][0] - s * vertArray[i+2][0]) / 6, vertArray[i+1][1] + (s * vertArray[i][1] - s * vertArray[i+2][1]) / 6]; b[3] = [vertArray[i+1][0], vertArray[i+1][1]]; curContext.bezierCurveTo(b[1][0], b[1][1], b[2][0], b[2][1], b[3][0], b[3][1]); } if(doFill){ curContext.fill(); } if(doStroke){ curContext.stroke(); } curContext.closePath(); } } } else if(isBezier && curShape === p.POLYGON || isBezier && curShape === undefined){ curContext.beginPath(); curContext.moveTo(vertArray[0][0], vertArray[0][1]); for(i = 1; i < vertArray.length; i++){ curContext.bezierCurveTo(vertArray[i][0], vertArray[i][1], vertArray[i][2], vertArray[i][3], vertArray[i][4], vertArray[i][5]); } if(doFill){ curContext.fill(); } if(doStroke){ curContext.stroke(); } curContext.closePath(); } else{ if(p.use3DContext){ // 3D context var lineVertArray = []; var fillVertArray = []; for(i = 0; i < vertArray.length; i++){ for(j = 0; j < 3; j++){ fillVertArray.push(vertArray[i][j]); } } fillVertArray.push(vertArray[0][0]); fillVertArray.push(vertArray[0][1]); fillVertArray.push(vertArray[0][2]); if (curShape === p.POINTS){ for(i = 0; i < vertArray.length; i++){ for(j = 0; j < 3; j++){ lineVertArray.push(vertArray[i][j]); } } point2D(lineVertArray); } else if(curShape === p.LINES){ for(i = 0; i < vertArray.length; i++){ for(j = 0; j < 3; j++){ lineVertArray.push(vertArray[i][j]); } } line2D(lineVertArray, "LINES"); } else if(curShape === p.TRIANGLES){ if(vertArray.length > 2){ for(i = 0; (i+2) < vertArray.length; i+=3){ fillVertArray = []; lineVertArray = []; for(j = 0; j < 3; j++){ for(k = 0; k < 3; k++){ lineVertArray.push(vertArray[i+j][k]); fillVertArray.push(vertArray[i+j][k]); } } if(doStroke){ line2D(lineVertArray, "LINE_LOOP"); } if(doFill){ fill2D(fillVertArray, "TRIANGLES"); } } } } else if(curShape === p.TRIANGLE_STRIP){ if(vertArray.length > 2){ for(i = 0; (i+2) < vertArray.length; i++){ lineVertArray = []; fillVertArray = []; for(j = 0; j < 3; j++){ for(k = 0; k < 3; k++){ lineVertArray.push(vertArray[i+j][k]); fillVertArray.push(vertArray[i+j][k]); } } if(doFill){ fill2D(fillVertArray); } if(doStroke){ line2D(lineVertArray, "LINE_LOOP"); } } } } else if(curShape === p.TRIANGLE_FAN){ if(vertArray.length > 2){ for(i = 0; i < 3; i++){ for(j = 0; j < 3; j++){ lineVertArray.push(vertArray[i][j]); } } if(doStroke){ line2D(lineVertArray, "LINE_LOOP"); } for(i = 2; (i+1) < vertArray.length; i++){ lineVertArray = []; lineVertArray.push(vertArray[0][0]); lineVertArray.push(vertArray[0][1]); lineVertArray.push(vertArray[0][2]); for(j = 0; j < 2; j++){ for(k = 0; k < 3; k++){ lineVertArray.push(vertArray[i+j][k]); } } if(doStroke){ line2D(lineVertArray, "LINE_STRIP"); } } if(doFill){ fill2D(fillVertArray, "TRIANGLE_FAN"); } } } else if(curShape === p.QUADS){ for(i = 0; (i + 3) < vertArray.length; i+=4){ lineVertArray = []; for(j = 0; j < 4; j++){ for(k = 0; k < 3; k++){ lineVertArray.push(vertArray[i+j][k]); } } if(doStroke){ line2D(lineVertArray, "LINE_LOOP"); } if(doFill){ fillVertArray = []; for(j = 0; j < 3; j++){ fillVertArray.push(vertArray[i][j]); } for(j = 0; j < 3; j++){ fillVertArray.push(vertArray[i+1][j]); } for(j = 0; j < 3; j++){ fillVertArray.push(vertArray[i+3][j]); } for(j = 0; j < 3; j++){ fillVertArray.push(vertArray[i+2][j]); } fill2D(fillVertArray, "TRIANGLE_STRIP"); } } } else if(curShape === p.QUAD_STRIP){ var tempArray = []; if(vertArray.length > 3){ for(i = 0; i < 2; i++){ for(j = 0; j < 3; j++){ lineVertArray.push(vertArray[i][j]); } } line2D(lineVertArray, "LINE_STRIP"); if(vertArray.length > 4 && vertArray.length % 2 > 0){ tempArray = fillVertArray.splice(fillVertArray.length - 6); vertArray.pop(); } for(i = 0; (i+3) < vertArray.length; i+=2){ lineVertArray = []; for(j = 0; j < 3; j++){ lineVertArray.push(vertArray[i+1][j]); } for(j = 0; j < 3; j++){ lineVertArray.push(vertArray[i+3][j]); } for(j = 0; j < 3; j++){ lineVertArray.push(vertArray[i+2][j]); } for(j = 0; j < 3; j++){ lineVertArray.push(vertArray[i+0][j]); } line2D(lineVertArray, "LINE_STRIP"); } if(doFill){ fill2D(fillVertArray); } } } else{ if(vertArray.length === 1){ for(j = 0; j < 3; j++){ lineVertArray.push(vertArray[0][j]); } point2D(lineVertArray); } else{ for(i = 0; i < vertArray.length; i++){ for(j = 0; j < 3; j++){ lineVertArray.push(vertArray[i][j]); } } if(p.CLOSE){ line2D(lineVertArray, "LINE_LOOP"); } else{ line2D(lineVertArray, "LINE_STRIP"); } if(doFill){ fill2D(fillVertArray); } } } } // 2D context else{ if (curShape === p.POINTS){ for(i = 0; i < vertArray.length; i++){ p.point(vertArray[i][0], vertArray[i][1]); } } else if(curShape === p.LINES){ for(i = 0; (i + 1) < vertArray.length; i+=2){ p.line(vertArray[i][0], vertArray[i][1], vertArray[i+1][0], vertArray[i+1][1]); } } else if(curShape === p.TRIANGLES){ for(i = 0; (i + 2) < vertArray.length; i+=3){ curContext.beginPath(); curContext.moveTo(vertArray[i][0], vertArray[i][1]); curContext.lineTo(vertArray[i+1][0], vertArray[i+1][1]); curContext.lineTo(vertArray[i+2][0], vertArray[i+2][1]); curContext.lineTo(vertArray[i][0], vertArray[i][1]); if(doFill){ curContext.fill(); } if(doStroke){ curContext.stroke(); } curContext.closePath(); } } else if(curShape === p.TRIANGLE_STRIP){ if(vertArray.length > 2){ curContext.beginPath(); curContext.moveTo(vertArray[0][0], vertArray[0][1]); curContext.lineTo(vertArray[1][0], vertArray[1][1]); for(i = 2; i < vertArray.length; i++){ curContext.lineTo(vertArray[i][0], vertArray[i][1]); curContext.lineTo(vertArray[i-2][0], vertArray[i-2][1]); if(doFill){ curContext.fill(); } if(doStroke){ curContext.stroke(); } curContext.moveTo(vertArray[i][0],vertArray[i][1]); } } } else if(curShape === p.TRIANGLE_FAN){ if(vertArray.length > 2){ curContext.beginPath(); curContext.moveTo(vertArray[0][0], vertArray[0][1]); curContext.lineTo(vertArray[1][0], vertArray[1][1]); curContext.lineTo(vertArray[2][0], vertArray[2][1]); if(doFill){ curContext.fill(); } if(doStroke){ curContext.stroke(); } for(i = 3; i < vertArray.length; i++){ curContext.moveTo(vertArray[0][0], vertArray[0][1]); curContext.lineTo(vertArray[i-1][0], vertArray[i-1][1]); curContext.lineTo(vertArray[i][0], vertArray[i][1]); if(doFill){ curContext.fill(); } if(doStroke){ curContext.stroke(); } } } } else if(curShape === p.QUADS){ for(i = 0; (i + 3) < vertArray.length; i+=4){ curContext.beginPath(); curContext.moveTo(vertArray[i][0], vertArray[i][1]); for(j = 1; j < 4; j++){ curContext.lineTo(vertArray[i+j][0], vertArray[i+j][1]); } curContext.lineTo(vertArray[i][0], vertArray[i][1]); if(doFill){ curContext.fill(); } if(doStroke){ curContext.stroke(); } curContext.closePath(); } } else if(curShape === p.QUAD_STRIP){ if(vertArray.length > 3){ curContext.beginPath(); curContext.moveTo(vertArray[0][0], vertArray[0][1]); curContext.lineTo(vertArray[1][0], vertArray[1][1]); for(i = 2; (i+1) < vertArray.length; i++){ if((i % 2) === 0){ curContext.moveTo(vertArray[i-2][0], vertArray[i-2][1]); curContext.lineTo(vertArray[i][0], vertArray[i][1]); curContext.lineTo(vertArray[i+1][0], vertArray[i+1][1]); curContext.lineTo(vertArray[i-1][0], vertArray[i-1][1]); if(doFill){ curContext.fill(); } if(doStroke){ curContext.stroke(); } } } } } else{ curContext.beginPath(); curContext.moveTo(vertArray[0][0], vertArray[0][1]); for(i = 1; i < vertArray.length; i++){ curContext.lineTo(vertArray[i][0], vertArray[i][1]); } if(p.CLOSE){ curContext.lineTo(vertArray[0][0], vertArray[0][1]); } if(doFill){ curContext.fill(); } if(doStroke){ curContext.stroke(); } } curContext.closePath(); } } isCurve = false; isBezier = false; }; p.bezierVertex = function(){ isBezier = true; var vert = []; if(firstVert){ throw ("vertex() must be used at least once before calling bezierVertex()"); } else{ if(arguments.length === 6){ for(var i = 0; i < arguments.length; i++){ vert[i] = arguments[i]; } } else{ //for 9 arguments (3d) } vertArray.push(vert); } }; p.curveVertex = function(x, y, z) { isCurve = true; p.vertex(x, y, z); }; p.curveVertexSegment = function(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) { var x0 = x2; var y0 = y2; var z0 = z2; var draw = curveDrawMatrix.array(); var xplot1 = draw[4] * x1 + draw[5] * x2 + draw[6] * x3 + draw[7] * x4; var xplot2 = draw[8] * x1 + draw[9] * x2 + draw[10] * x3 + draw[11] * x4; var xplot3 = draw[12] * x1 + draw[13] * x2 + draw[14] * x3 + draw[15] * x4; var yplot1 = draw[4] * y1 + draw[5] * y2 + draw[6] * y3 + draw[7] * y4; var yplot2 = draw[8] * y1 + draw[9] * y2 + draw[10] * y3 + draw[11] * y4; var yplot3 = draw[12] * y1 + draw[13] * y2 + draw[14] * y3 + draw[15] * y4; var zplot1 = draw[4] * z1 + draw[5] * z2 + draw[6] * z3 + draw[7] * z4; var zplot2 = draw[8] * z1 + draw[9] * z2 + draw[10] * z3 + draw[11] * z4; var zplot3 = draw[12] * z1 + draw[13] * z2 + draw[14] * z3 + draw[15] * z4; p.vertex(x0, y0, z0); for (var j = 0; j < curveDetail; j++) { x0 += xplot1; xplot1 += xplot2; xplot2 += xplot3; y0 += yplot1; yplot1 += yplot2; yplot2 += yplot3; z0 += zplot1; zplot1 += zplot2; zplot2 += zplot3; p.vertex(x0, y0, z0); } }; p.curve = function curve() { if (arguments.length === 8) // curve(x1, y1, x2, y2, x3, y3, x4, y4) { p.beginShape(); p.curveVertex(arguments[0], arguments[1]); p.curveVertex(arguments[2], arguments[3]); p.curveVertex(arguments[4], arguments[5]); p.curveVertex(arguments[6], arguments[7]); p.endShape(); } else { // curve( x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); if (p.use3DContext) { p.beginShape(); p.curveVertex(arguments[0], arguments[1], arguments[2]); p.curveVertex(arguments[3], arguments[4], arguments[5]); p.curveVertex(arguments[6], arguments[7], arguments[8]); p.curveVertex(arguments[9], arguments[10], arguments[11]); p.endShape(); } } }; p.curveTightness = function(tightness) { curTightness = tightness; }; //used by both curveDetail and bezierDetail var splineForward = function(segments, matrix) { var f = 1.0 / segments; var ff = f * f; var fff = ff * f; matrix.set(0, 0, 0, 1, fff, ff, f, 0, 6 * fff, 2 * ff, 0, 0, 6 * fff, 0, 0, 0); }; //internal curveInit //used by curveDetail, curveTightness var curveInit = function() { // allocate only if/when used to save startup time if (!curveDrawMatrix) { curveBasisMatrix = new PMatrix3D(); curveDrawMatrix = new PMatrix3D(); curveInited = true; } var s = curTightness; curveBasisMatrix.set(((s - 1) / 2).toFixed(2), ((s + 3) / 2).toFixed(2), ((-3 - s) / 2).toFixed(2), ((1 - s) / 2).toFixed(2), (1 - s), ((-5 - s) / 2).toFixed(2), (s + 2), ((s - 1) / 2).toFixed(2), ((s - 1) / 2).toFixed(2), 0, ((1 - s) / 2).toFixed(2), 0, 0, 1, 0, 0); splineForward(curveDetail, curveDrawMatrix); if (!bezierBasisInverse) { //bezierBasisInverse = bezierBasisMatrix.get(); //bezierBasisInverse.invert(); curveToBezierMatrix = new PMatrix3D(); } // TODO only needed for PGraphicsJava2D? if so, move it there // actually, it's generally useful for other renderers, so keep it // or hide the implementation elsewhere. curveToBezierMatrix.set(curveBasisMatrix); curveToBezierMatrix.preApply(bezierBasisInverse); // multiply the basis and forward diff matrices together // saves much time since this needn't be done for each curve curveDrawMatrix.apply(curveBasisMatrix); }; p.curveDetail = function curveDetail() { curveDetail = arguments[0]; curveInit(); }; p.rectMode = function rectMode(aRectMode) { curRectMode = aRectMode; }; p.imageMode = function(mode) { switch (mode) { case p.CORNER: imageModeConvert = imageModeCorner; break; case p.CORNERS: imageModeConvert = imageModeCorners; break; case p.CENTER: imageModeConvert = imageModeCenter; break; default: throw "Invalid imageMode"; } }; p.ellipseMode = function ellipseMode(aEllipseMode) { curEllipseMode = aEllipseMode; }; p.arc = function arc(x, y, width, height, start, stop) { if (width <= 0) { return; } if (curEllipseMode === p.CORNER) { x += width / 2; y += height / 2; } curContext.moveTo(x, y); curContext.beginPath(); curContext.arc(x, y, curEllipseMode === p.CENTER_RADIUS ? width : width / 2, start, stop, false); if (doStroke) { curContext.stroke(); } curContext.lineTo(x, y); if (doFill) { curContext.fill(); } curContext.closePath(); }; p.line = function line() { var x1, y1, z1, x2, y2, z2; if (p.use3DContext) { if (arguments.length === 6) { x1 = arguments[0]; y1 = arguments[1]; z1 = arguments[2]; x2 = arguments[3]; y2 = arguments[4]; z2 = arguments[5]; } else if (arguments.length === 4) { x1 = arguments[0]; y1 = arguments[1]; z1 = 0; x2 = arguments[2]; y2 = arguments[3]; z2 = 0; } var lineVerts = [x1, y1, z1, x2, y2, z2]; var model = new PMatrix3D(); //model.scale(w, h, d); var view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); curContext.useProgram(programObject2D); uniformMatrix(programObject2D, "model", true, model.array()); uniformMatrix(programObject2D, "view", true, view.array()); uniformMatrix(programObject2D, "projection", true, projection.array()); if (lineWidth > 0 && doStroke) { curContext.useProgram(programObject2D); uniformf(programObject2D, "color", strokeStyle); curContext.lineWidth(lineWidth); vertexAttribPointer(programObject2D, "Vertex", 3, lineBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, newWebGLArray(lineVerts), curContext.STREAM_DRAW); curContext.drawArrays(curContext.LINES, 0, 2); } } else { x1 = arguments[0]; y1 = arguments[1]; x2 = arguments[2]; y2 = arguments[3]; if (doStroke) { curContext.beginPath(); curContext.moveTo(x1 || 0, y1 || 0); curContext.lineTo(x2 || 0, y2 || 0); curContext.stroke(); curContext.closePath(); } } }; p.bezier = function bezier(x1, y1, x2, y2, x3, y3, x4, y4) { curContext.beginPath(); curContext.moveTo(x1, y1); curContext.bezierCurveTo(x2, y2, x3, y3, x4, y4); curContext.stroke(); curContext.closePath(); }; p.bezierPoint = function bezierPoint(a, b, c, d, t) { return (1 - t) * (1 - t) * (1 - t) * a + 3 * (1 - t) * (1 - t) * t * b + 3 * (1 - t) * t * t * c + t * t * t * d; }; p.bezierTangent = function bezierTangent(a, b, c, d, t) { return (3 * t * t * (-a + 3 * b - 3 * c + d) + 6 * t * (a - 2 * b + c) + 3 * (-a + b)); }; p.curvePoint = function curvePoint(a, b, c, d, t) { return 0.5 * ((2 * b) + (-a + c) * t + (2 * a - 5 * b + 4 * c - d) * t * t + (-a + 3 * b - 3 * c + d) * t * t * t); }; p.curveTangent = function curveTangent(a, b, c, d, t) { return 0.5 * ((-a + c) + 2 * (2 * a - 5 * b + 4 * c - d) * t + 3 * (-a + 3 * b - 3 * c + d) * t * t); }; p.triangle = function triangle(x1, y1, x2, y2, x3, y3) { p.beginShape(p.TRIANGLES); p.vertex(x1, y1, 0); p.vertex(x2, y2, 0); p.vertex(x3, y3, 0); p.endShape(); }; p.quad = function quad(x1, y1, x2, y2, x3, y3, x4, y4) { p.beginShape(p.QUADS); p.vertex(x1, y1, 0); p.vertex(x2, y2, 0); p.vertex(x3, y3, 0); p.vertex(x4, y4, 0); p.endShape(); }; p.rect = function rect(x, y, width, height) { if (!width && !height) { return; } curContext.beginPath(); var offsetStart = 0; var offsetEnd = 0; if (curRectMode === p.CORNERS) { width -= x; height -= y; } if (curRectMode === p.RADIUS) { width *= 2; height *= 2; } if (curRectMode === p.CENTER || curRectMode === p.RADIUS) { x -= width / 2; y -= height / 2; } curContext.rect( Math.round(x) - offsetStart, Math.round(y) - offsetStart, Math.round(width) + offsetEnd, Math.round(height) + offsetEnd); if (doFill) { curContext.fill(); } if (doStroke) { curContext.stroke(); } curContext.closePath(); }; p.ellipse = function ellipse(x, y, width, height) { x = x || 0; y = y || 0; if (width <= 0 && height <= 0) { return; } curContext.beginPath(); if (curEllipseMode === p.RADIUS) { width *= 2; height *= 2; } if (curEllipseMode === p.CORNERS) { width = width - x; height = height - y; } if (curEllipseMode === p.CORNER || curEllipseMode === p.CORNERS) { x += width / 2; y += height / 2; } var offsetStart = 0; // Shortcut for drawing a circle if (width === height) { curContext.arc(x - offsetStart, y - offsetStart, width / 2, 0, p.TWO_PI, false); } else { var w = width / 2, h = height / 2, C = 0.5522847498307933; var c_x = C * w, c_y = C * h; // TODO: Audit curContext.moveTo(x + w, y); curContext.bezierCurveTo(x + w, y - c_y, x + c_x, y - h, x, y - h); curContext.bezierCurveTo(x - c_x, y - h, x - w, y - c_y, x - w, y); curContext.bezierCurveTo(x - w, y + c_y, x - c_x, y + h, x, y + h); curContext.bezierCurveTo(x + c_x, y + h, x + w, y + c_y, x + w, y); } if (doFill) { curContext.fill(); } if (doStroke) { curContext.stroke(); } curContext.closePath(); }; p.normal = function normal(nx, ny, nz) { if (arguments.length !== 3 || !(typeof nx === "number" && typeof ny === "number" && typeof nz === "number")) { throw "normal() requires three numeric arguments."; } normalX = nx; normalY = ny; normalZ = nz; if (curShape !== 0) { if (normalMode === p.NORMAL_MODE_AUTO) { normalMode = p.NORMAL_MODE_SHAPE; } else if (normalMode === p.NORMAL_MODE_SHAPE) { normalMode = p.NORMAL_MODE_VERTEX; } } }; //////////////////////////////////////////////////////////////////////////// // Raster drawing functions //////////////////////////////////////////////////////////////////////////// // TODO: function incomplete p.save = function save(file) {}; var Temporary2DContext = document.createElement('canvas').getContext('2d'); var PImage = function PImage(aWidth, aHeight, aFormat) { this.get = function(x, y, w, h) { if (!arguments.length) { return p.get(this); } else if (arguments.length === 2) { return p.get(x, y, this); } else if (arguments.length === 4) { return p.get(x, y, w, h, this); } }; this.set = function(x, y, c) { p.set(x, y, c, this); }; this.blend = function(srcImg, x, y, width, height, dx, dy, dwidth, dheight, MODE) { if (arguments.length === 9) { p.blend(this, srcImg, x, y, width, height, dx, dy, dwidth, dheight, this); } else if (arguments.length === 10) { p.blend(srcImg, x, y, width, height, dx, dy, dwidth, dheight, MODE, this); } }; this.copy = function(srcImg, sx, sy, swidth, sheight, dx, dy, dwidth, dheight) { if (arguments.length === 8) { p.blend(this, srcImg, sx, sy, swidth, sheight, dx, dy, dwidth, p.REPLACE, this); } else if (arguments.length === 9) { p.blend(srcImg, sx, sy, swidth, sheight, dx, dy, dwidth, dheight, p.REPLACE, this); } }; this.resize = function(w, h) { if (this.width !== 0 || this.height !== 0) { // make aspect ratio if w or h is 0 if (w === 0 && h !== 0) { w = this.width / this.height * h; } else if (h === 0 && w !== 0) { h = w / (this.width / this.height); } // put 'this.imageData' into a new canvas var canvas = document.createElement('canvas'); canvas.width = this.width; canvas.height = this.height; // changed for 0.9 slightly this one line canvas.getContext('2d').putImageData(this.imageData, 0, 0); // pass new canvas to drawimage with w,h var canvasResized = document.createElement('canvas'); canvasResized.width = w; canvasResized.height = h; canvasResized.getContext('2d').drawImage(canvas, 0, 0, w, h); // pull imageData object out of canvas into ImageData object var imageData = canvasResized.getContext('2d').getImageData(0, 0, w, h); // set this as new pimage this.fromImageData(imageData); } }; this.mask = function(mask) { this._mask = undefined; if (mask instanceof PImage) { if (mask.width === this.width && mask.height === this.height) { this._mask = mask; } else { throw "mask must have the same dimensions as PImage."; } } else if (typeof mask === "object" && mask.constructor === Array) { // this is a pixel array // mask pixel array needs to be the same length as this.pixels // how do we update this for 0.9 this.imageData holding pixels ^^ // mask.constructor ? and this.pixels.length = this.imageData.data.length instead ? if (this.pixels.length === mask.length) { this._mask = mask; } else { throw "mask array must be the same length as PImage pixels array."; } } }; // handle the sketch code for pixels[] and pixels.length // parser code converts pixels[] to getPixels() // or setPixels(), .length becomes getLength() this.pixels = { getLength: (function(aImg) { return function() { return aImg.imageData.data.length ? aImg.imageData.data.length/4 : 0; }; }(this)), getPixel: (function(aImg) { return function(i) { var offset = i*4; return p.color.toInt(aImg.imageData.data[offset], aImg.imageData.data[offset+1], aImg.imageData.data[offset+2], aImg.imageData.data[offset+3]); }; }(this)), setPixel: (function(aImg) { return function(i,c) { if(c && typeof c === "number") { var offset = i*4; // split c into array var c2 = p.color.toArray(c); // change pixel to c aImg.imageData.data[offset] = c2[0]; aImg.imageData.data[offset+1] = c2[1]; aImg.imageData.data[offset+2] = c2[2]; aImg.imageData.data[offset+3] = c2[3]; } }; }(this)) }; // These are intentionally left blank for PImages, we work live with pixels and draw as necessary this.loadPixels = function() {}; this.updatePixels = function() {}; this.toImageData = function() { // changed for 0.9 var canvas = document.createElement('canvas'); canvas.height = this.height; canvas.width = this.width; var ctx = canvas.getContext('2d'); ctx.putImageData(this.imageData, 0, 0); return ctx.getImageData(0, 0, this.width, this.height); }; this.toDataURL = function() { var canvas = document.createElement('canvas'); canvas.height = this.height; canvas.width = this.width; var ctx = canvas.getContext('2d'); var imgData = ctx.createImageData(this.width, this.height); // changed for 0.9 ctx.putImageData(this.imageData, 0, 0); return canvas.toDataURL(); }; this.fromImageData = function(canvasImg) { this.width = canvasImg.width; this.height = canvasImg.height; this.imageData = canvasImg; // changed for 0.9 this.format = p.ARGB; // changed for 0.9 }; this.fromHTMLImageData = function(htmlImg) { // convert an <img> to a PImage var canvas = document.createElement("canvas"); canvas.width = htmlImg.width; canvas.height = htmlImg.height; var context = canvas.getContext("2d"); context.drawImage(htmlImg, 0, 0); var imageData = context.getImageData(0, 0, htmlImg.width, htmlImg.height); this.fromImageData(imageData); }; if (arguments.length === 1) { // convert an <img> to a PImage this.fromHTMLImageData(arguments[0]); } else if (arguments.length === 2 || arguments.length === 3) { this.width = aWidth || 1; this.height = aHeight || 1; // changed for 0.9 this.imageData = curContext.createImageData(this.width, this.height); this.format = (aFormat === p.ARGB || aFormat === p.ALPHA) ? aFormat : p.RGB; } }; p.PImage = PImage; try { // Opera createImageData fix if (! ("createImageData" in CanvasRenderingContext2D.prototype)) { CanvasRenderingContext2D.prototype.createImageData = function(sw, sh) { return this.getImageData(0, 0, sw, sh); }; } } catch(e) {} p.createImage = function createImage(w, h, mode) { // changed for 0.9 return new PImage(w,h,mode); }; // Loads an image for display. Type is an extension. Callback is fired on load. p.loadImage = function loadImage(file, type, callback) { // if type is specified add it with a . to file to make the filename if (type) { file = file + "." + type; } // if image is in the preloader cache return a new PImage if (p.pjs.imageCache[file]) { return new PImage(p.pjs.imageCache[file]); } // else aysnc load it else { var pimg = new PImage(0, 0, p.ARGB); var img = document.createElement('img'); pimg.sourceImg = img; img.onload = (function(aImage, aPImage, aCallback) { var image = aImage; var pimg = aPImage; var callback = aCallback; return function() { // change the <img> object into a PImage now that its loaded pimg.fromHTMLImageData(image); pimg.loaded = true; if (callback) { callback(); } }; }(img, pimg, callback)); img.src = file; // needs to be called after the img.onload function is declared or it wont work in opera return pimg; } }; // async loading of large images, same functionality as loadImage above p.requestImage = p.loadImage; // Gets a single pixel or block of pixels from the current Canvas Context or a PImage p.get = function get(x, y, w, h, img) { var c; // for 0 2 and 4 arguments use curContext, otherwise PImage.get was called if (!arguments.length) { //return a PImage of curContext c = new PImage(p.width, p.height, p.RGB); c.fromImageData(curContext.getImageData(0, 0, p.width, p.height)); return c; } else if (arguments.length === 5) { // PImage.get(x,y,w,h) was called, return x,y,w,h PImage of img // changed for 0.9, offset start point needs to be *4 var start = y * img.width * 4 + (x*4); var end = (y + h) * img.width * 4 + ((x + w) * 4); c = new PImage(w, h, p.RGB); for (var i = start, j = 0; i < end; i++, j++) { // changed in 0.9 c.imageData.data[j] = img.imageData.data[i]; if (j*4 + 1 % w === 0) { //completed one line, increment i by offset i += (img.width - w) * 4; } } return c; } else if (arguments.length === 4) { // return a PImage of w and h from cood x,y of curContext c = new PImage(w, h, p.RGB); c.fromImageData(curContext.getImageData(x, y, w, h)); return c; } else if (arguments.length === 3) { // PImage.get(x,y) was called, return the color (int) at x,y of img // changed in 0.9 var offset = y * w.width * 4 + (x * 4); return p.color.toInt(w.imageData.data[offset], w.imageData.data[offset + 1], w.imageData.data[offset + 2], w.imageData.data[offset + 3]); } else if (arguments.length === 2) { // return the color at x,y (int) of curContext // create a PImage object of size 1x1 and return the int of the pixels array element 0 if (x < p.width && x >= 0 && y >= 0 && y < p.height) { // x,y is inside canvas space c = new PImage(1, 1, p.RGB); c.fromImageData(curContext.getImageData(x, y, 1, 1)); // changed for 0.9 return p.color.toInt(c.imageData.data[0], c.imageData.data[1], c.imageData.data[2], c.imageData.data[3]); } else { // x,y is outside image return transparent black return 0; } } else if (arguments.length === 1) { // PImage.get() was called, return the PImage return x; } }; // Creates a new Processing instance and passes it back for... processing p.createGraphics = function createGraphics(w, h) { var canvas = document.createElement("canvas"); var ret = new Processing(canvas); ret.size(w, h); ret.canvas = canvas; return ret; }; // Paints a pixel array into the canvas p.set = function set(x, y, obj, img) { var color, oldFill; // PImage.set(x,y,c) was called, set coordinate x,y color to c of img if (arguments.length === 4) { // changed in 0.9 var c = p.color.toArray(obj); var offset = y * img.width * 4 + (x*4); img.imageData.data[offset] = c[0]; img.imageData.data[offset+1] = c[1]; img.imageData.data[offset+2] = c[2]; img.imageData.data[offset+3] = c[3]; } else if (arguments.length === 3) { // called p.set(), was it with a color or a img ? if (typeof obj === "number") { oldFill = curContext.fillStyle; color = obj; curContext.fillStyle = p.color.toString(color); curContext.fillRect(Math.round(x), Math.round(y), 1, 1); curContext.fillStyle = oldFill; } else if (obj instanceof PImage) { p.image(obj, x, y); } } }; p.imageData = {}; // handle the sketch code for pixels[] // parser code converts pixels[] to getPixels() // or setPixels(), .length becomes getLength() p.pixels = { getLength: function() { return p.imageData.data.length ? p.imageData.data.length/4 : 0; }, getPixel: function(i) { var offset = i*4; return p.color.toInt(p.imageData.data[offset], p.imageData.data[offset+1], p.imageData.data[offset+2], p.imageData.data[offset+3]); }, setPixel: function(i,c) { if(c && typeof c === "number") { var offset = i*4; // split c into array var c2 = p.color.toArray(c); // change pixel to c p.imageData.data[offset] = c2[0]; p.imageData.data[offset+1] = c2[1]; p.imageData.data[offset+2] = c2[2]; p.imageData.data[offset+3] = c2[3]; } } }; // Gets a 1-Dimensional pixel array from Canvas p.loadPixels = function() { // changed in 0.9 p.imageData = p.get(0, 0, p.width, p.height).imageData; }; // Draws a 1-Dimensional pixel array to Canvas p.updatePixels = function() { // changed in 0.9 if (p.imageData) { curContext.putImageData(p.imageData, 0, 0); } }; // Draw an image or a color to the background p.background = function background() { var color, a, img; // background params are either a color or a PImage if (typeof arguments[0] === 'number') { color = p.color.apply(this, arguments); // override alpha value, processing ignores the alpha for background color color = color | p.ALPHA_MASK; } else if (arguments.length === 1 && arguments[0] instanceof PImage) { img = arguments[0]; if (!img.pixels || img.width !== p.width || img.height !== p.height) { throw "Background image must be the same dimensions as the canvas."; } } else { throw "Incorrect background parameters."; } if (p.use3DContext) { if (typeof color !== 'undefined') { var c = p.color.toGLArray(color); refreshBackground = function() { curContext.clearColor(c[0], c[1], c[2], c[3]); curContext.clear(curContext.COLOR_BUFFER_BIT | curContext.DEPTH_BUFFER_BIT); }; } else { // Handle image background for 3d context. not done yet. refreshBackground = function() {}; } } else { // 2d context if (typeof color !== 'undefined') { refreshBackground = function() { var oldFill = curContext.fillStyle; curContext.fillStyle = p.color.toString(color); curContext.fillRect(0, 0, p.width, p.height); curContext.fillStyle = oldFill; }; } else { refreshBackground = function() { p.image(img, 0, 0); }; } } refreshBackground(); }; // Draws an image to the Canvas p.image = function image(img, x, y, w, h) { if (img.width > 0) { var bounds = imageModeConvert(x || 0, y || 0, w || img.width, h || img.height, arguments.length < 4); var obj = img.toImageData(); if (img._mask) { var j, size; if (img._mask instanceof PImage) { var objMask = img._mask.toImageData(); for (j = 2, size = img.width * img.height * 4; j < size; j += 4) { // using it as an alpha channel obj.data[j + 1] = objMask.data[j]; // but only the blue color channel } } else { for (j = 0, size = img._mask.length; j < size; ++j) { obj.data[(j << 2) + 3] = img._mask[j]; } } } // draw the image //curContext.putImageData(obj, x, y); // this causes error if data overflows the canvas dimensions curTint(obj); var c = document.createElement('canvas'); c.width = obj.width; c.height = obj.height; var ctx = c.getContext('2d'); ctx.putImageData(obj, 0, 0); curContext.drawImage(c, 0, 0, img.width, img.height, bounds.x, bounds.y, bounds.w, bounds.h); } }; // Clears a rectangle in the Canvas element or the whole Canvas p.clear = function clear(x, y, width, height) { if (arguments.length === 0) { curContext.clearRect(0, 0, p.width, p.height); } else { curContext.clearRect(x, y, width, height); } }; p.tint = function tint() { var tintColor = p.color.apply(this, arguments); var r = p.red(tintColor) / colorModeX; var g = p.green(tintColor) / colorModeY; var b = p.blue(tintColor) / colorModeZ; var a = p.alpha(tintColor) / colorModeA; curTint = function(obj) { var data = obj.data, length = 4 * obj.width * obj.height; for (var i = 0; i < length;) { data[i++] *= r; data[i++] *= g; data[i++] *= b; data[i++] *= a; } }; }; p.noTint = function noTint() { curTint = function() {}; }; p.copy = function copy(src, sx, sy, sw, sh, dx, dy, dw, dh) { if (arguments.length === 8) { p.copy(p, src, sx, sy, sw, sh, dx, dy, dw); return; } p.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, p.REPLACE); }; p.blend = function blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode, pimgdest) { if (arguments.length === 9) { p.blend(p, src, sx, sy, sw, sh, dx, dy, dw, dh); } else if (arguments.length === 10 || arguments.length === 11) { var sx2 = sx + sw; var sy2 = sy + sh; var dx2 = dx + dw; var dy2 = dy + dh; var dest; // check if pimgdest is there and pixels, if so this was a call from pimg.blend if (arguments.length === 10) { p.loadPixels(); dest = p; } else if (arguments.length === 11 && pimgdest && pimgdest.imageData) { dest = pimgdest; } if (src === p) { if (p.intersect(sx, sy, sx2, sy2, dx, dy, dx2, dy2)) { p.blit_resize(p.get(sx, sy, sx2 - sx, sy2 - sy), 0, 0, sx2 - sx - 1, sy2 - sy - 1, dest.imageData.data, dest.width, dest.height, dx, dy, dx2, dy2, mode); } else { // same as below, except skip the loadPixels() because it'd be redundant p.blit_resize(src, sx, sy, sx2, sy2, dest.imageData.data, dest.width, dest.height, dx, dy, dx2, dy2, mode); } } else { src.loadPixels(); p.blit_resize(src, sx, sy, sx2, sy2, dest.imageData.data, dest.width, dest.height, dx, dy, dx2, dy2, mode); } if (arguments.length === 10) { p.updatePixels(); } } }; // shared variables for blit_resize(), filter_new_scanline(), filter_bilinear() // change this in the future to not be exposed to p p.shared = { fracU: 0, ifU: 0, fracV: 0, ifV: 0, u1: 0, u2: 0, v1: 0, v2: 0, sX: 0, sY: 0, iw: 0, iw1: 0, ih1: 0, ul: 0, ll: 0, ur: 0, lr: 0, cUL: 0, cLL: 0, cUR: 0, cLR: 0, srcXOffset: 0, srcYOffset: 0, r: 0, g: 0, b: 0, a: 0, srcBuffer: null }; p.intersect = function intersect(sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2) { var sw = sx2 - sx1 + 1; var sh = sy2 - sy1 + 1; var dw = dx2 - dx1 + 1; var dh = dy2 - dy1 + 1; if (dx1 < sx1) { dw += dx1 - sx1; if (dw > sw) { dw = sw; } } else { var w = sw + sx1 - dx1; if (dw > w) { dw = w; } } if (dy1 < sy1) { dh += dy1 - sy1; if (dh > sh) { dh = sh; } } else { var h = sh + sy1 - dy1; if (dh > h) { dh = h; } } return ! (dw <= 0 || dh <= 0); }; p.filter_new_scanline = function filter_new_scanline() { p.shared.sX = p.shared.srcXOffset; p.shared.fracV = p.shared.srcYOffset & p.PREC_MAXVAL; p.shared.ifV = p.PREC_MAXVAL - p.shared.fracV; p.shared.v1 = (p.shared.srcYOffset >> p.PRECISIONB) * p.shared.iw; p.shared.v2 = Math.min((p.shared.srcYOffset >> p.PRECISIONB) + 1, p.shared.ih1) * p.shared.iw; }; p.filter_bilinear = function filter_bilinear() { p.shared.fracU = p.shared.sX & p.PREC_MAXVAL; p.shared.ifU = p.PREC_MAXVAL - p.shared.fracU; p.shared.ul = (p.shared.ifU * p.shared.ifV) >> p.PRECISIONB; p.shared.ll = (p.shared.ifU * p.shared.fracV) >> p.PRECISIONB; p.shared.ur = (p.shared.fracU * p.shared.ifV) >> p.PRECISIONB; p.shared.lr = (p.shared.fracU * p.shared.fracV) >> p.PRECISIONB; p.shared.u1 = (p.shared.sX >> p.PRECISIONB); p.shared.u2 = Math.min(p.shared.u1 + 1, p.shared.iw1); // get color values of the 4 neighbouring texels // changed for 0.9 var cULoffset = (p.shared.v1 + p.shared.u1) * 4; var cURoffset = (p.shared.v1 + p.shared.u2) * 4; var cLLoffset = (p.shared.v2 + p.shared.u1) * 4; var cLRoffset = (p.shared.v2 + p.shared.u2) * 4; p.shared.cUL = p.color.toInt(p.shared.srcBuffer[cULoffset], p.shared.srcBuffer[cULoffset+1], p.shared.srcBuffer[cULoffset+2], p.shared.srcBuffer[cULoffset+3]); p.shared.cUR = p.color.toInt(p.shared.srcBuffer[cURoffset], p.shared.srcBuffer[cURoffset+1], p.shared.srcBuffer[cURoffset+2], p.shared.srcBuffer[cURoffset+3]); p.shared.cLL = p.color.toInt(p.shared.srcBuffer[cLLoffset], p.shared.srcBuffer[cLLoffset+1], p.shared.srcBuffer[cLLoffset+2], p.shared.srcBuffer[cLLoffset+3]); p.shared.cLR = p.color.toInt(p.shared.srcBuffer[cLRoffset], p.shared.srcBuffer[cLRoffset+1], p.shared.srcBuffer[cLRoffset+2], p.shared.srcBuffer[cLRoffset+3]); p.shared.r = ((p.shared.ul * ((p.shared.cUL & p.RED_MASK) >> 16) + p.shared.ll * ((p.shared.cLL & p.RED_MASK) >> 16) + p.shared.ur * ((p.shared.cUR & p.RED_MASK) >> 16) + p.shared.lr * ((p.shared.cLR & p.RED_MASK) >> 16)) << p.PREC_RED_SHIFT) & p.RED_MASK; p.shared.g = ((p.shared.ul * (p.shared.cUL & p.GREEN_MASK) + p.shared.ll * (p.shared.cLL & p.GREEN_MASK) + p.shared.ur * (p.shared.cUR & p.GREEN_MASK) + p.shared.lr * (p.shared.cLR & p.GREEN_MASK)) >>> p.PRECISIONB) & p.GREEN_MASK; p.shared.b = (p.shared.ul * (p.shared.cUL & p.BLUE_MASK) + p.shared.ll * (p.shared.cLL & p.BLUE_MASK) + p.shared.ur * (p.shared.cUR & p.BLUE_MASK) + p.shared.lr * (p.shared.cLR & p.BLUE_MASK)) >>> p.PRECISIONB; p.shared.a = ((p.shared.ul * ((p.shared.cUL & p.ALPHA_MASK) >>> 24) + p.shared.ll * ((p.shared.cLL & p.ALPHA_MASK) >>> 24) + p.shared.ur * ((p.shared.cUR & p.ALPHA_MASK) >>> 24) + p.shared.lr * ((p.shared.cLR & p.ALPHA_MASK) >>> 24)) << p.PREC_ALPHA_SHIFT) & p.ALPHA_MASK; return p.shared.a | p.shared.r | p.shared.g | p.shared.b; }; p.blit_resize = function blit_resize(img, srcX1, srcY1, srcX2, srcY2, destPixels, screenW, screenH, destX1, destY1, destX2, destY2, mode) { var x, y; // iterator vars if (srcX1 < 0) { srcX1 = 0; } if (srcY1 < 0) { srcY1 = 0; } if (srcX2 >= img.width) { srcX2 = img.width - 1; } if (srcY2 >= img.height) { srcY2 = img.height - 1; } var srcW = srcX2 - srcX1; var srcH = srcY2 - srcY1; var destW = destX2 - destX1; var destH = destY2 - destY1; var smooth = true; // may as well go with the smoothing these days if (!smooth) { srcW++; srcH++; } if (destW <= 0 || destH <= 0 || srcW <= 0 || srcH <= 0 || destX1 >= screenW || destY1 >= screenH || srcX1 >= img.width || srcY1 >= img.height) { return; } var dx = Math.floor(srcW / destW * p.PRECISIONF); var dy = Math.floor(srcH / destH * p.PRECISIONF); p.shared.srcXOffset = Math.floor(destX1 < 0 ? -destX1 * dx : srcX1 * p.PRECISIONF); p.shared.srcYOffset = Math.floor(destY1 < 0 ? -destY1 * dy : srcY1 * p.PRECISIONF); if (destX1 < 0) { destW += destX1; destX1 = 0; } if (destY1 < 0) { destH += destY1; destY1 = 0; } destW = Math.min(destW, screenW - destX1); destH = Math.min(destH, screenH - destY1); // changed in 0.9, TODO var destOffset = destY1 * screenW + destX1; var destColor; p.shared.srcBuffer = img.imageData.data; if (smooth) { // use bilinear filtering p.shared.iw = img.width; p.shared.iw1 = img.width - 1; p.shared.ih1 = img.height - 1; switch (mode) { case p.BLEND: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.blend(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.blend(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.ADD: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.add(destColor, p.filter_bilinear())); destColor = p.color.toArray(p.modes.add(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.add(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.SUBTRACT: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.subtract(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.subtract(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.LIGHTEST: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.lightest(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.lightest(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.DARKEST: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.darkest(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.darkest(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.REPLACE: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.filter_bilinear()); //destPixels[destOffset + x] = p.filter_bilinear(); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.DIFFERENCE: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.difference(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.difference(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.EXCLUSION: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.exclusion(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.exclusion(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.MULTIPLY: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.multiply(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.multiply(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.SCREEN: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.screen(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.screen(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.OVERLAY: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.overlay(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.overlay(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.HARD_LIGHT: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.hard_light(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.hard_light(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.SOFT_LIGHT: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.soft_light(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.soft_light(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.DODGE: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.dodge(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.dodge(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.BURN: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.burn(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.burn(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; } } }; //////////////////////////////////////////////////////////////////////////// // Font handling //////////////////////////////////////////////////////////////////////////// // Loads a font from an SVG or Canvas API p.loadFont = function loadFont(name) { if (name.indexOf(".svg") === -1) { return { name: name, width: function(str) { if (curContext.mozMeasureText) { return curContext.mozMeasureText( typeof str === "number" ? String.fromCharCode(str) : str) / curTextSize; } else { return 0; } } }; } else { // If the font is a glyph, calculate by SVG table var font = p.loadGlyphs(name); return { name: name, glyph: true, units_per_em: font.units_per_em, horiz_adv_x: 1 / font.units_per_em * font.horiz_adv_x, ascent: font.ascent, descent: font.descent, width: function(str) { var width = 0; var len = str.length; for (var i = 0; i < len; i++) { try { width += parseFloat(p.glyphLook(p.glyphTable[name], str[i]).horiz_adv_x); } catch(e) { Processing.debug(e); } } return width / p.glyphTable[name].units_per_em; } }; } }; p.createFont = function(name, size) {}; // Sets a 'current font' for use p.textFont = function textFont(name, size) { curTextFont = name; p.textSize(size); }; // Sets the font size p.textSize = function textSize(size) { if (size) { curTextSize = size; } }; p.textAlign = function textAlign() {}; // A lookup table for characters that can not be referenced by Object p.glyphLook = function glyphLook(font, chr) { try { switch (chr) { case "1": return font.one; case "2": return font.two; case "3": return font.three; case "4": return font.four; case "5": return font.five; case "6": return font.six; case "7": return font.seven; case "8": return font.eight; case "9": return font.nine; case "0": return font.zero; case " ": return font.space; case "$": return font.dollar; case "!": return font.exclam; case '"': return font.quotedbl; case "#": return font.numbersign; case "%": return font.percent; case "&": return font.ampersand; case "'": return font.quotesingle; case "(": return font.parenleft; case ")": return font.parenright; case "*": return font.asterisk; case "+": return font.plus; case ",": return font.comma; case "-": return font.hyphen; case ".": return font.period; case "/": return font.slash; case "_": return font.underscore; case ":": return font.colon; case ";": return font.semicolon; case "<": return font.less; case "=": return font.equal; case ">": return font.greater; case "?": return font.question; case "@": return font.at; case "[": return font.bracketleft; case "\\": return font.backslash; case "]": return font.bracketright; case "^": return font.asciicircum; case "`": return font.grave; case "{": return font.braceleft; case "|": return font.bar; case "}": return font.braceright; case "~": return font.asciitilde; // If the character is not 'special', access it by object reference default: return font[chr]; } } catch(e) { Processing.debug(e); } }; // Print some text to the Canvas p.text = function text() { if (typeof arguments[0] !== 'undefined') { var str = arguments[0], x, y, z, pos, width, height; if (typeof str === 'number' && (str + "").indexOf('.') >= 0) { // Make sure .15 rounds to .1, but .151 rounds to .2. if ((str * 1000) - Math.floor(str * 1000) === 0.5) { str = str - 0.0001; } str = str.toFixed(3); } str = str.toString(); if (arguments.length === 1) { // for text( str ) p.text(str, lastTextPos[0], lastTextPos[1]); } else if (arguments.length === 3) { // for text( str, x, y) text(str, arguments[1], arguments[2], 0); } else if (arguments.length === 4) { // for text( str, x, y, z) x = arguments[1]; y = arguments[2]; z = arguments[3]; do { pos = str.indexOf("\n"); if (pos !== -1) { if (pos !== 0) { text(str.substring(0, pos)); } y += curTextSize; str = str.substring(pos + 1, str.length); } } while (pos !== -1); // TODO: handle case for 3d text if (p.use3DContext) { } width = 0; // If the font is a standard Canvas font... if (!curTextFont.glyph) { if (str && (curContext.fillText || curContext.mozDrawText)) { curContext.save(); curContext.font = curContext.mozTextStyle = curTextSize + "px " + curTextFont.name; if (curContext.fillText) { curContext.fillText(str, x, y); width = curContext.measureText(str).width; } else if (curContext.mozDrawText) { curContext.translate(x, y); curContext.mozDrawText(str); width = curContext.mozMeasureText(str); } curContext.restore(); } } else { // If the font is a Batik SVG font... var font = p.glyphTable[curTextFont.name]; curContext.save(); curContext.translate(x, y + curTextSize); var upem = font.units_per_em, newScale = 1 / upem * curTextSize; curContext.scale(newScale, newScale); var len = str.length; for (var i = 0; i < len; i++) { // Test character against glyph table try { p.glyphLook(font, str[i]).draw(); } catch(e) { Processing.debug(e); } } curContext.restore(); } // TODO: Handle case for 3d text if (p.use3DContext) { } lastTextPos[0] = x + width; lastTextPos[1] = y; lastTextPos[2] = z; } else if (arguments.length === 5) { // for text( str, x, y , width, height) text(str, arguments[1], arguments[2], arguments[3], arguments[4], 0); } else if (arguments.length === 6) { // for text( stringdata, x, y , width, height, z) x = arguments[1]; y = arguments[2]; width = arguments[3]; height = arguments[4]; z = arguments[5]; if (str.length > 0) { if (curTextSize > height) { return; } var spaceMark = -1; var start = 0; var lineWidth = 0; var letterWidth = 0; var textboxWidth = width; lastTextPos[0] = x; lastTextPos[1] = y - 0.4 * curTextSize; curContext.font = curTextSize + "px " + curTextFont.name; for (var j = 0; j < str.length; j++) { if (curContext.fillText) { letterWidth = curContext.measureText(str[j]).width; } else if (curContext.mozDrawText) { letterWidth = curContext.mozMeasureText(str[j]); } if (str[j] !== "\n" && (str[j] === " " || (str[j - 1] !== " " && str[j + 1] === " ") || lineWidth + 2 * letterWidth < textboxWidth)) { // check a line of text if (str[j] === " ") { spaceMark = j; } lineWidth += letterWidth; } else { // draw a line of text if (start === spaceMark + 1) { // in case a whole line without a space spaceMark = j; } lastTextPos[0] = x; lastTextPos[1] = lastTextPos[1] + curTextSize; if (str[j] === "\n") { text(str.substring(start, j)); start = j + 1; } else { text(str.substring(start, spaceMark + 1)); start = spaceMark + 1; } lineWidth = 0; if (lastTextPos[1] + 2 * curTextSize > y + height + 0.6 * curTextSize) { // stop if no enough space for one more line draw return; } j = start - 1; } } if (start !== str.length) { // draw the last line lastTextPos[0] = x; lastTextPos[1] = lastTextPos[1] + curTextSize; for (; start < str.length; start++) { text(str[start]); } } } // end str != "" } // end arguments.length == 6 } }; // Load Batik SVG Fonts and parse to pre-def objects for quick rendering p.loadGlyphs = function loadGlyph(url) { var x, y, cx, cy, nx, ny, d, a, lastCom, lenC, horiz_adv_x, getXY = '[0-9\\-]+', path; // Return arrays of SVG commands and coords // get this to use p.matchAll() - will need to work around the lack of null return var regex = function regex(needle, hay) { var i = 0, results = [], latest, regexp = new RegExp(needle, "g"); latest = results[i] = regexp.exec(hay); while (latest) { i++; latest = results[i] = regexp.exec(hay); } return results; }; var buildPath = function buildPath(d) { var c = regex("[A-Za-z][0-9\\- ]+|Z", d); // Begin storing path object path = "var path={draw:function(){curContext.beginPath();curContext.save();"; x = 0; y = 0; cx = 0; cy = 0; nx = 0; ny = 0; d = 0; a = 0; lastCom = ""; lenC = c.length - 1; // Loop through SVG commands translating to canvas eqivs functions in path object for (var j = 0; j < lenC; j++) { var com = c[j][0], xy = regex(getXY, com); switch (com[0]) { case "M": //curContext.moveTo(x,-y); x = parseFloat(xy[0][0]); y = parseFloat(xy[1][0]); path += "curContext.moveTo(" + x + "," + (-y) + ");"; break; case "L": //curContext.lineTo(x,-y); x = parseFloat(xy[0][0]); y = parseFloat(xy[1][0]); path += "curContext.lineTo(" + x + "," + (-y) + ");"; break; case "H": //curContext.lineTo(x,-y) x = parseFloat(xy[0][0]); path += "curContext.lineTo(" + x + "," + (-y) + ");"; break; case "V": //curContext.lineTo(x,-y); y = parseFloat(xy[0][0]); path += "curContext.lineTo(" + x + "," + (-y) + ");"; break; case "T": //curContext.quadraticCurveTo(cx,-cy,nx,-ny); nx = parseFloat(xy[0][0]); ny = parseFloat(xy[1][0]); if (lastCom === "Q" || lastCom === "T") { d = Math.sqrt(Math.pow(x - cx, 2) + Math.pow(cy - y, 2)); a = Math.PI + Math.atan2(cx - x, cy - y); cx = x + (Math.sin(a) * (d)); cy = y + (Math.cos(a) * (d)); } else { cx = x; cy = y; } path += "curContext.quadraticCurveTo(" + cx + "," + (-cy) + "," + nx + "," + (-ny) + ");"; x = nx; y = ny; break; case "Q": //curContext.quadraticCurveTo(cx,-cy,nx,-ny); cx = parseFloat(xy[0][0]); cy = parseFloat(xy[1][0]); nx = parseFloat(xy[2][0]); ny = parseFloat(xy[3][0]); path += "curContext.quadraticCurveTo(" + cx + "," + (-cy) + "," + nx + "," + (-ny) + ");"; x = nx; y = ny; break; case "Z": //curContext.closePath(); path += "curContext.closePath();"; break; } lastCom = com[0]; } path += "doStroke?curContext.stroke():0;"; path += "doFill?curContext.fill():0;"; path += "curContext.restore();"; path += "curContext.translate(" + horiz_adv_x + ",0);"; path += "}}"; return path; }; // Parse SVG font-file into block of Canvas commands var parseSVGFont = function parseSVGFontse(svg) { // Store font attributes var font = svg.getElementsByTagName("font"); p.glyphTable[url].horiz_adv_x = font[0].getAttribute("horiz-adv-x"); var font_face = svg.getElementsByTagName("font-face")[0]; p.glyphTable[url].units_per_em = parseFloat(font_face.getAttribute("units-per-em")); p.glyphTable[url].ascent = parseFloat(font_face.getAttribute("ascent")); p.glyphTable[url].descent = parseFloat(font_face.getAttribute("descent")); var glyph = svg.getElementsByTagName("glyph"), len = glyph.length; // Loop through each glyph in the SVG for (var i = 0; i < len; i++) { // Store attributes for this glyph var unicode = glyph[i].getAttribute("unicode"); var name = glyph[i].getAttribute("glyph-name"); horiz_adv_x = glyph[i].getAttribute("horiz-adv-x"); if (horiz_adv_x === null) { horiz_adv_x = p.glyphTable[url].horiz_adv_x; } d = glyph[i].getAttribute("d"); // Split path commands in glpyh if (d !== undefined) { path = buildPath(d); eval(path); // Store glyph data to table object p.glyphTable[url][name] = { name: name, unicode: unicode, horiz_adv_x: horiz_adv_x, draw: path.draw }; } } // finished adding glyphs to table }; // Load and parse Batik SVG font as XML into a Processing Glyph object var loadXML = function loadXML() { var xmlDoc; try { xmlDoc = document.implementation.createDocument("", "", null); } catch(e_fx_op) { Processing.debug(e_fx_op.message); return; } try { xmlDoc.async = false; xmlDoc.load(url); parseSVGFont(xmlDoc.getElementsByTagName("svg")[0]); } catch(e_sf_ch) { // Google Chrome, Safari etc. Processing.debug(e_sf_ch); try { var xmlhttp = new window.XMLHttpRequest(); xmlhttp.open("GET", url, false); xmlhttp.send(null); parseSVGFont(xmlhttp.responseXML.documentElement); } catch(e) { Processing.debug(e_sf_ch); } } }; // Create a new object in glyphTable to store this font p.glyphTable[url] = {}; // Begin loading the Batik SVG font... loadXML(url); // Return the loaded font for attribute grabbing return p.glyphTable[url]; }; //////////////////////////////////////////////////////////////////////////// // Class methods //////////////////////////////////////////////////////////////////////////// p.extendClass = function extendClass(obj, args, fn) { if (arguments.length === 3) { fn.apply(obj, args); } else { args.call(obj); } }; p.addMethod = function addMethod(object, name, fn) { if (object[name]) { var args = fn.length, oldfn = object[name]; object[name] = function() { if (arguments.length === args) { return fn.apply(this, arguments); } else { return oldfn.apply(this, arguments); } }; } else { object[name] = fn; } }; ////////////////////////////////////////////////////////////////////////// // Event handling ////////////////////////////////////////////////////////////////////////// p.pjs.eventHandlers = []; function attach(elem, type, fn) { if (elem.addEventListener) { elem.addEventListener(type, fn, false); } else { elem.attachEvent("on" + type, fn); } p.pjs.eventHandlers.push([elem, type, fn]); } attach(curElement, "mousemove", function(e) { var element = curElement, offsetX = 0, offsetY = 0; p.pmouseX = p.mouseX; p.pmouseY = p.mouseY; if (element.offsetParent) { do { offsetX += element.offsetLeft; offsetY += element.offsetTop; } while (element = element.offsetParent); } // Dropping support for IE clientX and clientY, switching to pageX and pageY so we don't have to calculate scroll offset. // Removed in ticket #184. See rev: 2f106d1c7017fed92d045ba918db47d28e5c16f4 p.mouseX = e.pageX - offsetX; p.mouseY = e.pageY - offsetY; if (p.mouseMoved && !mousePressed) { p.mouseMoved(); } if (mousePressed && p.mouseDragged) { p.mouseDragged(); p.mouseDragging = true; } }); attach(curElement, "mouseout", function(e) { }); attach(curElement, "mousedown", function(e) { mousePressed = true; p.mouseDragging = false; switch (e.which) { case 1: p.mouseButton = p.LEFT; break; case 2: p.mouseButton = p.CENTER; break; case 3: p.mouseButton = p.RIGHT; break; } p.mouseDown = true; if (typeof p.mousePressed === "function") { p.mousePressed(); } else { p.mousePressed = true; } }); attach(curElement, "mouseup", function(e) { mousePressed = false; if (p.mouseClicked && !p.mouseDragging) { p.mouseClicked(); } if (typeof p.mousePressed !== "function") { p.mousePressed = false; } if (p.mouseReleased) { p.mouseReleased(); } }); var mouseWheelHandler = function(e) { var delta = 0; if (e.wheelDelta) { delta = e.wheelDelta / 120; if (window.opera) { delta = -delta; } } else if (e.detail) { delta = -e.detail / 3; } p.mouseScroll = delta; if (delta && typeof p.mouseScrolled === 'function') { p.mouseScrolled(); } }; // Support Gecko and non-Gecko scroll events attach(document, 'DOMMouseScroll', mouseWheelHandler); attach(document, 'mousewheel', mouseWheelHandler); attach(document, "keydown", function(e) { keyPressed = true; p.keyCode = null; p.key = e.keyCode; // Letters if (e.keyCode >= 65 && e.keyCode <= 90) { // A-Z // Keys return ASCII for upcased letters. // Convert to downcase if shiftKey is not pressed. if (!e.shiftKey) { p.key += 32; } } // Numbers and their shift-symbols else if (e.keyCode >= 48 && e.keyCode <= 57) { // 0-9 if (e.shiftKey) { switch (e.keyCode) { case 49: p.key = 33; break; // ! case 50: p.key = 64; break; // @ case 51: p.key = 35; break; // # case 52: p.key = 36; break; // $ case 53: p.key = 37; break; // % case 54: p.key = 94; break; // ^ case 55: p.key = 38; break; // & case 56: p.key = 42; break; // * case 57: p.key = 40; break; // ( case 48: p.key = 41; break; // ) } } } // Coded keys else if (codedKeys.indexOf(e.keyCode) >= 0) { // SHIFT, CONTROL, ALT, LEFT, RIGHT, UP, DOWN p.key = p.CODED; p.keyCode = e.keyCode; } // Symbols and their shift-symbols else { if (e.shiftKey) { switch (e.keyCode) { case 107: p.key = 43; break; // + case 219: p.key = 123; break; // { case 221: p.key = 125; break; // } case 222: p.key = 34; break; // " } } else { switch (e.keyCode) { case 188: p.key = 44; break; // , case 109: p.key = 45; break; // - case 190: p.key = 46; break; // . case 191: p.key = 47; break; // / case 192: p.key = 96; break; // ~ case 219: p.key = 91; break; // [ case 220: p.key = 92; break; // \ case 221: p.key = 93; break; // ] case 222: p.key = 39; break; // ' } } } if (typeof p.keyPressed === "function") { p.keyPressed(); } else { p.keyPressed = true; } }); attach(document, "keyup", function(e) { keyPressed = false; if (typeof p.keyPressed !== "function") { p.keyPressed = false; } if (p.keyReleased) { p.keyReleased(); } }); attach(document, "keypress", function (e) { if (p.keyTyped) { p.keyTyped(); } }); // Place-holder for debugging function p.debug = function(e) {}; // Get the DOM element if string was passed if (typeof curElement === "string") { curElement = document.getElementById(curElement); } // Send aCode Processing syntax to be converted to JavaScript if (aCode) { var parsedCode = typeof aCode === "function" ? undefined : Processing.parse(aCode, p); if (!this.use3DContext) { // Setup default 2d canvas context. curContext = curElement.getContext('2d'); modelView = new PMatrix2D(); // Canvas has trouble rendering single pixel stuff on whole-pixel // counts, so we slightly offset it (this is super lame). curContext.translate(0.5, 0.5); curContext.lineCap = 'round'; // Set default stroke and fill color p.stroke(0); p.fill(255); p.noSmooth(); p.disableContextMenu(); } // Step through the libraries that were attached at doc load... for (var i in Processing.lib) { if (Processing.lib) { // Init the libraries in the context of this p_instance Processing.lib[i].call(this); } } var localizedProperties = ""; for (var propertyName in p) { localizedProperties += "var " + propertyName + "=__p__." + propertyName + ";"; if (typeof p[propertyName] !== "function" || typeof p[propertyName] !== "object") { localizedProperties += "__p__.__defineGetter__('" + propertyName + "',function(){return " + propertyName + ";});" + "__p__.__defineSetter__('" + propertyName + "',function(v){" + propertyName + "=v;});"; } } var executeSketch = function() { // Don't start until all specified images in the cache are preloaded if (!p.pjs.imageCache.pending) { if(typeof aCode === "function") { aCode(p); } else { eval (" (function(__p__) { " + localizedProperties + parsedCode + " if (setup) {" + " __p__.setup = setup;" + " setup();" + " }" + " if (draw) {" + " __p__.draw = draw;" + " if (!doLoop) {" + " redraw();" + " } else {" + " loop();" + " }" + " }" + " })(p);" ); } } else { window.setTimeout(executeSketch, 10); } }; // The parser adds custom methods to the processing context executeSketch(); } }; // Share lib space Processing.lib = {}; // Parse Processing (Java-like) syntax to JavaScript syntax with Regex Processing.parse = function parse(aCode, p) { // Function to grab all code in the opening and closing of two characters var nextBrace = function(right, openChar, closeChar) { var rest = right, position = 0, leftCount = 1, rightCount = 0; while (leftCount !== rightCount) { var nextLeft = rest.indexOf(openChar), nextRight = rest.indexOf(closeChar); if (nextLeft < nextRight && nextLeft !== -1) { leftCount++; rest = rest.slice(nextLeft + 1); position += nextLeft + 1; } else { rightCount++; rest = rest.slice(nextRight + 1); position += nextRight + 1; } } return right.slice(0, position - 1); }; // Force characters-as-bytes to work. //aCode = aCode.replace(/('(.){1}')/g, "$1.charCodeAt(0)"); aCode = aCode.replace(/'.{1}'/g, function(all) { return "(new Char(" + all + "))"; }); // Parse out @pjs directive, if any. var dm = /\/\*\s*@pjs\s+((?:[^\*]|\*+[^\*\/])*)\*\//g.exec(aCode); if (dm && dm.length === 2) { var directives = dm.splice(1, 2)[0].replace('\n', '').replace('\r', '').split(';'); // We'll L/RTrim, and also remove any surrounding double quotes (e.g., just take string contents) var clean = function(s) { return s.replace(/^\s*\"?/, '').replace(/\"?\s*$/, ''); }; for (var i = 0, dl = directives.length; i < dl; i++) { var pair = directives[i].split('='); if (pair && pair.length === 2) { var key = clean(pair[0]); var value = clean(pair[1]); // A few directives require work beyond storying key/value pairings if (key === "preload") { var list = value.split(','); // All pre-loaded images will get put in imageCache, keyed on filename for (var j = 0, ll = list.length; j < ll; j++) { var imageName = clean(list[j]); var img = new Image(); img.onload = (function() { return function() { p.pjs.imageCache.pending--; }; }()); p.pjs.imageCache.pending++; p.pjs.imageCache[imageName] = img; img.src = imageName; } } else if (key === "opaque") { p.canvas.mozOpaque = value === "true"; } else { p.pjs[key] = value; } } } aCode = aCode.replace(dm[0], ''); } // Saves all strings into an array // masks all strings into <STRING n> // to be replaced with the array strings after parsing is finished var strings = []; aCode = aCode.replace(/(["'])(\\\1|.)*?(\1)/g, function(all) { strings.push(all); return "<STRING " + (strings.length - 1) + ">"; }); // Windows newlines cause problems: aCode = aCode.replace(/\r\n?/g, "\n"); // Remove multi-line comments aCode = aCode.replace(/\/\*[\s\S]*?\*\//g, ""); // Remove end-of-line comments aCode = aCode.replace(/\/\/.*\n/g, "\n"); // Weird parsing errors with % aCode = aCode.replace(/([^\s])%([^\s])/g, "$1 % $2"); // Since frameRate() and frameRate are different things, // we need to differentiate them somehow. So when we parse // the Processing.js source, replace frameRate so it isn't // confused with frameRate(). aCode = aCode.replace(/frameRate\s*([^\(])/g, "FRAME_RATE$1"); // Simple convert a function-like thing to function aCode = aCode.replace(/(?:static )?(\w+(?:\[\])*\s+)(\w+)\s*(\([^\)]*\)\s*\{)/g, function(all, type, name, args) { if (name === "if" || name === "for" || name === "while" || type === "public ") { return all; } else { return "PROCESSING." + name + " = function " + name + args; } }); var matchMethod = /PROCESSING\.(\w+ = function \w+\([^\)]*\)\s*\{)/, mc; while ((mc = aCode.match(matchMethod))) { var prev = RegExp.leftContext, allNext = RegExp.rightContext, next = nextBrace(allNext, "{", "}"); aCode = prev + "processing." + mc[1] + next + "};" + allNext.slice(next.length + 1); } // Delete import statements, ie. import processing.video.*; // https://processing-js.lighthouseapp.com/projects/41284/tickets/235-fix-parsing-of-java-import-statement aCode = aCode.replace(/import\s+(.+);/g, ""); //replace catch (IOException e) to catch (e) aCode = aCode.replace(/catch\s*\(\W*\w*\s+(\w*)\W*\)/g, "catch ($1)"); //delete the multiple catch block var catchBlock = /(catch[^\}]*\})\W*catch[^\}]*\}/; while (catchBlock.test(aCode)) { aCode = aCode.replace(new RegExp(catchBlock), "$1"); } Error.prototype.printStackTrace = function() { this.toString(); }; // changes pixels[n] into pixels.getPixels(n) // and pixels[n] = n2 into pixels.setPixels(n, n2) var matchPixels = /pixels\s*\[/, mp; while ((mp = aCode.match(matchPixels))) { var left = RegExp.leftContext, allRest = RegExp.rightContext, rest = nextBrace(allRest, "[", "]"), getOrSet = "getPixel"; allRest = allRest.slice(rest.length + 1); allRest = (function(){ return allRest.replace(/^\s*=([^;]*)([;])/, function(all, middle, end){ rest += ", " + middle; getOrSet = "setPixel"; return end; }); }()); aCode = left + "pixels." + getOrSet + "(" + rest + ")" + allRest; } // changes pixel.length to pixels.getLength() aCode = aCode.replace(/pixels.length/g, "pixels.getLength()"); // Force .length() to be .length aCode = aCode.replace(/\.length\(\)/g, ".length"); // foo( int foo, float bar ) aCode = aCode.replace(/([\(,]\s*)(\w+)((?:\[\])+|\s+)\s*(\w+\s*[\),])/g, "$1$4"); aCode = aCode.replace(/([\(,]\s*)(\w+)((?:\[\])+|\s+)\s*(\w+\s*[\),])/g, "$1$4"); // float[] foo = new float[5]; aCode = aCode.replace(/new\s+(\w+)\s*((?:\[(?:[^\]]*)\])+)\s*(\{[^;]*\}\s*;)*/g, function(all, name, args, initVars) { if (initVars) { return initVars.replace(/\{/g, "[").replace(/\}/g, "]"); } else { return "new ArrayList(" + args.replace(/\[\]/g, "[0]").slice(1, -1).split("][").join(", ") + ");"; } }); // What does this do? This does the same thing as "Fix Array[] foo = {...} to [...]" below aCode = aCode.replace(/(?:static\s+)?\w+\[\]\s*(\w+)\[?\]?\s*=\s*\{.*?\};/g, function(all) { return all.replace(/\{/g, "[").replace(/\}/g, "]"); }); // int|float foo; var intFloat = /(\s*(?:int|float)\s+(?!\[\])*(?:\s*|[^\(;]*?,\s*))([a-zA-Z]\w*)\s*(,|;)/i; while (intFloat.test(aCode)) { aCode = (function() { return aCode.replace(new RegExp(intFloat), function(all, type, name, sep) { return type + " " + name + " = 0" + sep; }); }()); } // float foo = 5; aCode = aCode.replace(/(?:final\s+)?(\w+)((?:\[\s*\])+|\s)\s*(\w+)\[?\]?(\s*[=,;])/g, function(all, type, arr, name, sep) { if (type === "return" || type === "else") { return all; } else { return "var " + name + sep; } }); // Fix Array[] foo = {...} to [...] aCode = aCode.replace(/\=\s*\{((.|\s)*?\};)/g, function(all, data) { return "= [" + data.replace(/\{/g, "[").replace(/\}/g, "]"); }); // super() is a reserved word aCode = aCode.replace(/super\(/g, "superMethod("); // Stores the variables and mathods of a single class var SuperClass = function(name){ return { className: name, classVariables: "", classFunctions: [] }; }; var arrayOfSuperClasses = []; // implements Int1, Int2 aCode = aCode.replace(/implements\s+(\w+\s*(,\s*\w+\s*)*)\s*\{/g, function(all, interfaces) { var names = interfaces.replace(/\s+/g, "").split(","); return "{ var __psj_interfaces = new ArrayList([\"" + names.join("\", \"") + "\"]);"; }); // Simply turns an interface into a class aCode = aCode.replace(/interface/g, "class"); var classes = ["int", "float", "boolean", "String", "byte", "double", "long", "ArrayList"]; var classReplace = function(all, name, extend) { classes.push(name); // Move arguments up from constructor return "function " + name + "() {\n " + (extend ? "var __self=this;function superMethod(){extendClass(__self,arguments," + extend + ");}\n" : "") + (extend ? "extendClass(this, " + extend + ");\n" : "") + "<CLASS " + name + " " + extend + ">"; }; var matchClasses = /(?:public\s+|abstract\s+|static\s+)*class\s+?(\w+)\s*(?:extends\s*(\w+)\s*)?\{/g; aCode = aCode.replace(matchClasses, classReplace); var matchClass = /<CLASS (\w+) (\w+)?>/, m; while ((m = aCode.match(matchClass))) { var left = RegExp.leftContext, allRest = RegExp.rightContext, rest = nextBrace(allRest, "{", "}"), className = m[1], thisSuperClass = new SuperClass(className), extendingClass = m[2]; allRest = allRest.slice(rest.length + 1); // Fix class method names // this.collide = function() { ... } rest = (function() { return rest.replace(/(?:public\s+)?processing.\w+ = function (\w+)\(([^\)]*?)\)/g, function(all, name, args) { thisSuperClass.classFunctions.push(name + "|"); return "ADDMETHOD(this, '" + name + "', (function(public) { return function(" + args + ")"; }); }()); var matchMethod = /ADDMETHOD([^,]+, \s*?')([^']*)('[\s\S]*?\{[^\{]*?\{)/, mc, methods = "", publicVars = "", methodsArray = []; while ((mc = rest.match(matchMethod))) { var prev = RegExp.leftContext, allNext = RegExp.rightContext, next = nextBrace(allNext, "{", "}"); methodsArray.push("addMethod" + mc[1] + mc[2] + mc[3] + next + "};})(this));\n"); publicVars += mc[2] + "|"; if (extendingClass){ for (var i = 0, aLength = arrayOfSuperClasses.length; i < aLength; i++){ if (extendingClass === arrayOfSuperClasses[i].className){ publicVars += arrayOfSuperClasses[i].classVariables; for (var x = 0, fLength = arrayOfSuperClasses[i].classFunctions.length; x < fLength; x++){ publicVars += arrayOfSuperClasses[i].classFunctions[x]; } } } } rest = prev + allNext.slice(next.length + 1); } var matchConstructor = new RegExp("\\b" + className + "\\s*\\(([^\\)]*?)\\)\\s*{"), c, constructor = "", constructorsArray = []; // Extract all constructors and put them into the variable "constructors" while ((c = rest.match(matchConstructor))) { var prev = RegExp.leftContext, allNext = RegExp.rightContext, next = nextBrace(allNext, "{", "}"), args = c[1]; args = args.split(/,\s*?/); if (args[0].match(/^\s*$/)) { args.shift(); } constructor = "if ( arguments.length === " + args.length + " ) {\n"; for (var i = 0, aLength = args.length; i < aLength; i++) { constructor += " var " + args[i] + " = arguments[" + i + "];\n"; } constructor += next + "}\n"; constructorsArray.push(constructor); rest = prev + allNext.slice(next.length + 1); } var vars = "", staticVars = "", localStaticVars = []; // Put all member variables into "vars" // and keep a list of all public variables rest = (function(){ rest.replace(/(?:final|private|public)?\s*?(?:(static)\s+)?var\s+([^;]*?;)/g, function(all, staticVar, variable) { variable = "this." + variable.replace(/,\s*/g, ";\nthis.") .replace(/this.(\w+);/g, "this.$1 = null;") + '\n'; publicVars += variable.replace(/\s*this\.(\w+)\s*(;|=).*\s?/g, "$1|"); thisSuperClass.classVariables += variable.replace(/\s*this\.(\w+)\s*(;|=).*\s?/g, "$1|"); if (staticVar === "static"){ // Fix static methods variable = variable.replace(/this\.(\w+)\s*=\s*([^;]*?;)/g, function(all, sVariable, value){ localStaticVars.push(sVariable); value = value.replace(new RegExp("(" + localStaticVars.join("|") + ")", "g"), className + ".$1"); staticVars += className + "." + sVariable + " = " + value; return "if (typeof " + className + "." + sVariable + " === 'undefined'){ " + className + "." + sVariable + " = " + value + " }\n" + "this.__defineGetter__('" + sVariable + "', function(){ return "+ className + "." + sVariable + "; });\n" + "this.__defineSetter__('" + sVariable + "', function(val){ " + className + "." + sVariable + " = val; });\n"; }); } vars += variable; return ""; }); }()); // add this. to public variables used inside member functions, and constructors if (publicVars) { // Search functions for public variables for (var i = 0, aLength = methodsArray.length; i < aLength; i++){ methodsArray[i] = (function(){ return methodsArray[i].replace(/(addMethod.*?\{ return function\((.*?)\)\s*\{)([\s\S]*?)(\};\}\)\(this\)\);)/g, function(all, header, localParams, body, footer) { body = body.replace(/this\./g, "public."); localParams = localParams.replace(/\s*,\s*/g, "|"); return header + body.replace(new RegExp("(var\\s+?|\\.)?\\b(" + publicVars.substr(0, publicVars.length-1) + ")\\b", "g"), function (all, first, variable) { if (first === ".") { return all; } else if (/var\s*?$/.test(first)) { localParams += "|" + variable; return all; } else if (localParams && new RegExp("\\b(" + localParams + ")\\b").test(variable)){ return all; } else { return "public." + variable; } }) + footer; }); }()); } // Search constructors for public variables for (var i = 0, localParameters = "", aLength = constructorsArray.length; i < aLength; i++){ localParameters = ""; (function(){ constructorsArray[i].replace(/var\s+(\w+) = arguments\[[^\]]\];/g, function(all, localParam){ localParameters += localParam + "|"; }); }()); (function(){ constructorsArray[i] = constructorsArray[i].replace(new RegExp("(var\\s+?|\\.)?\\b(" + publicVars.substr(0, publicVars.length-1) + ")\\b", "g"), function (all, first, variable) { if (first === ".") { return all; } else if (/var\s*?$/.test(first)) { localParameters += variable + "|"; return all; } else if (localParameters && new RegExp("\\b(" + localParameters.substr(0, localParameters.length-1) + ")\\b").test(variable)){ return all; } else { return "this." + variable; } }); }()); } } var constructors = ""; for (var i = 0, aLength = methodsArray.length; i < aLength; i++){ methods += methodsArray[i]; } for (var i = 0, aLength = constructorsArray.length; i < aLength; i++){ constructors += constructorsArray[i]; } arrayOfSuperClasses.push(thisSuperClass); rest = vars + "\n" + methods + "\n" + constructors; aCode = left + rest + "\n}" + staticVars + allRest; } // Do some tidying up, where necessary aCode = aCode.replace(/processing.\w+ = function addMethod/g, "addMethod"); // Remove processing. from leftover functions aCode = aCode.replace(/processing\.((\w+) = function)/g, "$1"); // Check if 3D context is invoked -- this is not the best way to do this. if (aCode.match(/size\((?:.+),(?:.+),\s*(OPENGL|P3D)\s*\);/)) { p.use3DContext = true; } // Handle (int) Casting aCode = aCode.replace(/\(int\)/g, "0|"); // Remove Casting aCode = aCode.replace(new RegExp("\\((" + classes.join("|") + ")(\\[\\])*\\)", "g"), ""); // Force numbers to exist // //aCode = aCode.replace(/([^.])(\w+)\s*\+=/g, "$1$2 = ($2||0) +"); var toNumbers = function(str) { var ret = []; str.replace(/(..)/g, function(str) { ret.push(parseInt(str, 16)); }); return ret; }; // Convert #aaaaaa into color aCode = aCode.replace(/#([a-f0-9]{6})/ig, function(m, hex) { var num = toNumbers(hex); return "defaultColor(" + num[0] + "," + num[1] + "," + num[2] + ")"; }); // Convert 3.0f to just 3.0 aCode = aCode.replace(/(\d+)f/g, "$1"); // replaces all masked strings from <STRING n> to the appropriate string contained in the strings array for (var n = 0, sl = strings.length; n < sl; n++) { aCode = (function() { return aCode.replace(new RegExp("(.*)(<STRING " + n + ">)(.*)", "g"), function(all, quoteStart, match, quoteEnd) { var returnString = all, notString = true, quoteType = "", escape = false; for (var x = 0, ql = quoteStart.length; x < ql; x++) { if (notString) { if (quoteStart.charAt(x) === "\"" || quoteStart.charAt(x) === "'") { quoteType = quoteStart.charAt(x); notString = false; } } else { if (!escape) { if (quoteStart.charAt(x) === "\\") { escape = true; } else if (quoteStart.charAt(x) === quoteType) { notString = true; quoteType = ""; } } else { escape = false; } } } if (notString) { // Match is not inside a string returnString = quoteStart + strings[n] + quoteEnd; } return returnString; }); }()); } return aCode; }; // IE Unfriendly AJAX Method var ajax = function(url) { var AJAX = new window.XMLHttpRequest(); if (AJAX) { AJAX.open("GET", url + "?t=" + new Date().getTime(), false); AJAX.send(null); return AJAX.responseText; } else { return false; } }; // Automatic Initialization Method var init = function() { var canvas = document.getElementsByTagName('canvas'); for (var i = 0, l = canvas.length; i < l; i++) { // datasrc and data-src are deprecated. var processingSources = canvas[i].getAttribute('data-processing-sources'); if (processingSources === null) { // Temporary fallback for datasrc and data-src processingSources = canvas[i].getAttribute('data-src'); if (processingSources === null) { processingSources = canvas[i].getAttribute('datasrc'); } } if (processingSources) { // The problem: if the HTML canvas dimensions differ from the // dimensions specified in the size() call in the sketch, for // 3D sketches, browsers will either not render or render the // scene incorrectly. To fix this, we need to adjust the attributes // of the canvas width and height. // Get the source, we'll need to find what the user has used in size() var filenames = processingSources.split(' '); var code = ""; for (var j=0, fl=filenames.length; j<fl; j++) { if (filenames[j]) { code += ajax(filenames[j]) + ";\n"; // deal with files that don't end with newline } } new Processing(canvas[i], code); } } }; document.addEventListener('DOMContentLoaded', function() { init(); }, false); }());
processing.js
/* P R O C E S S I N G . J S - @VERSION@ a port of the Processing visualization language License : MIT Developer : John Resig: http://ejohn.org Web Site : http://processingjs.org Java Version : http://processing.org Github Repo. : http://github.com/jeresig/processing-js Bug Tracking : http://processing-js.lighthouseapp.com Mozilla POW! : http://wiki.Mozilla.org/Education/Projects/ProcessingForTheWeb Maintained by : Seneca: http://zenit.senecac.on.ca/wiki/index.php/Processing.js Hyper-Metrix: http://hyper-metrix.com/#Processing BuildingSky: http://weare.buildingsky.net/pages/processing-js */ (function() { var Processing = this.Processing = function Processing(curElement, aCode) { var p = this; p.pjs = { imageCache: { pending: 0 } }; // by default we have an empty imageCache, no more. p.name = 'Processing.js Instance'; // Set Processing defaults / environment variables p.use3DContext = false; // default '2d' canvas context p.canvas = curElement; // Glyph path storage for textFonts p.glyphTable = {}; // Global vars for tracking mouse position p.pmouseX = 0; p.pmouseY = 0; p.mouseX = 0; p.mouseY = 0; p.mouseButton = 0; p.mouseDown = false; p.mouseScroll = 0; // Undefined event handlers to be replaced by user when needed p.mouseClicked = undefined; p.mouseDragged = undefined; p.mouseMoved = undefined; p.mousePressed = undefined; p.mouseReleased = undefined; p.mouseScrolled = undefined; p.key = undefined; p.keyPressed = undefined; p.keyReleased = undefined; p.keyTyped = undefined; p.draw = undefined; p.setup = undefined; // The height/width of the canvas p.width = curElement.width - 0; p.height = curElement.height - 0; // The current animation frame p.frameCount = 0; // Color modes p.RGB = 1; p.ARGB = 2; p.HSB = 3; p.ALPHA = 4; p.CMYK = 5; // Renderers p.P2D = 1; p.JAVA2D = 1; p.WEBGL = 2; p.P3D = 2; p.OPENGL = 2; p.EPSILON = 0.0001; p.MAX_FLOAT = 3.4028235e+38; p.MIN_FLOAT = -3.4028235e+38; p.MAX_INT = 2147483647; p.MIN_INT = -2147483648; p.PI = Math.PI; p.TWO_PI = 2 * p.PI; p.HALF_PI = p.PI / 2; p.THIRD_PI = p.PI / 3; p.QUARTER_PI = p.PI / 4; p.DEG_TO_RAD = p.PI / 180; p.RAD_TO_DEG = 180 / p.PI; p.WHITESPACE = " \t\n\r\f\u00A0"; // Filter/convert types p.BLUR = 11; p.GRAY = 12; p.INVERT = 13; p.OPAQUE = 14; p.POSTERIZE = 15; p.THRESHOLD = 16; p.ERODE = 17; p.DILATE = 18; // Blend modes p.REPLACE = 0; p.BLEND = 1 << 0; p.ADD = 1 << 1; p.SUBTRACT = 1 << 2; p.LIGHTEST = 1 << 3; p.DARKEST = 1 << 4; p.DIFFERENCE = 1 << 5; p.EXCLUSION = 1 << 6; p.MULTIPLY = 1 << 7; p.SCREEN = 1 << 8; p.OVERLAY = 1 << 9; p.HARD_LIGHT = 1 << 10; p.SOFT_LIGHT = 1 << 11; p.DODGE = 1 << 12; p.BURN = 1 << 13; // Color component bit masks p.ALPHA_MASK = 0xff000000; p.RED_MASK = 0x00ff0000; p.GREEN_MASK = 0x0000ff00; p.BLUE_MASK = 0x000000ff; // Projection matrices p.CUSTOM = 0; p.ORTHOGRAPHIC = 2; p.PERSPECTIVE = 3; // Shapes p.POINT = 2; p.POINTS = 2; p.LINE = 4; p.LINES = 4; p.TRIANGLE = 8; p.TRIANGLES = 9; p.TRIANGLE_STRIP = 10; p.TRIANGLE_FAN = 11; p.QUAD = 16; p.QUADS = 16; p.QUAD_STRIP = 17; p.POLYGON = 20; p.PATH = 21; p.RECT = 30; p.ELLIPSE = 31; p.ARC = 32; p.SPHERE = 40; p.BOX = 41; // Shape closing modes p.OPEN = 1; p.CLOSE = 2; // Shape drawing modes p.CORNER = 0; // Draw mode convention to use (x, y) to (width, height) p.CORNERS = 1; // Draw mode convention to use (x1, y1) to (x2, y2) coordinates p.RADIUS = 2; // Draw mode from the center, and using the radius p.CENTER_RADIUS = 2; // Deprecated! Use RADIUS instead p.CENTER = 3; // Draw from the center, using second pair of values as the diameter p.DIAMETER = 3; // Synonym for the CENTER constant. Draw from the center p.CENTER_DIAMETER = 3; // Deprecated! Use DIAMETER instead // Text vertical alignment modes p.BASELINE = 0; // Default vertical alignment for text placement p.TOP = 101; // Align text to the top p.BOTTOM = 102; // Align text from the bottom, using the baseline // UV Texture coordinate modes p.NORMAL = 1; p.NORMALIZE = 1; p.IMAGE = 2; // Text placement modes p.MODEL = 4; p.SHAPE = 5; // Stroke modes p.SQUARE = 'butt'; p.ROUND = 'round'; p.PROJECT = 'square'; p.MITER = 'miter'; p.BEVEL = 'bevel'; // Lighting modes p.AMBIENT = 0; p.DIRECTIONAL = 1; //POINT = 2; Shared with Shape constant p.SPOT = 3; // Key constants // Both key and keyCode will be equal to these values p.BACKSPACE = 8; p.TAB = 9; p.ENTER = 10; p.RETURN = 13; p.ESC = 27; p.DELETE = 127; p.CODED = 0xffff; // p.key will be CODED and p.keyCode will be this value p.SHIFT = 16; p.CONTROL = 17; p.ALT = 18; p.UP = 38; p.RIGHT = 39; p.DOWN = 40; p.LEFT = 37; var codedKeys = [p.SHIFT, p.CONTROL, p.ALT, p.UP, p.RIGHT, p.DOWN, p.LEFT]; // Cursor types p.ARROW = 'default'; p.CROSS = 'crosshair'; p.HAND = 'pointer'; p.MOVE = 'move'; p.TEXT = 'text'; p.WAIT = 'wait'; p.NOCURSOR = "url('data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='), auto"; // Hints p.DISABLE_OPENGL_2X_SMOOTH = 1; p.ENABLE_OPENGL_2X_SMOOTH = -1; p.ENABLE_OPENGL_4X_SMOOTH = 2; p.ENABLE_NATIVE_FONTS = 3; p.DISABLE_DEPTH_TEST = 4; p.ENABLE_DEPTH_TEST = -4; p.ENABLE_DEPTH_SORT = 5; p.DISABLE_DEPTH_SORT = -5; p.DISABLE_OPENGL_ERROR_REPORT = 6; p.ENABLE_OPENGL_ERROR_REPORT = -6; p.ENABLE_ACCURATE_TEXTURES = 7; p.DISABLE_ACCURATE_TEXTURES = -7; p.HINT_COUNT = 10; // PJS defined constants p.SINCOS_LENGTH = parseInt(360 / 0.5, 10); p.FRAME_RATE = 0; p.focused = true; p.PRECISIONB = 15; // fixed point precision is limited to 15 bits!! p.PRECISIONF = 1 << p.PRECISIONB; p.PREC_MAXVAL = p.PRECISIONF - 1; p.PREC_ALPHA_SHIFT = 24 - p.PRECISIONB; p.PREC_RED_SHIFT = 16 - p.PRECISIONB; p.NORMAL_MODE_AUTO = 0; p.NORMAL_MODE_SHAPE = 1; p.NORMAL_MODE_VERTEX = 2; p.MAX_LIGHTS = 8; // "Private" variables used to maintain state var curContext, online = true, doFill = true, fillStyle = "rgba( 255, 255, 255, 1 )", doStroke = true, strokeStyle = "rgba( 204, 204, 204, 1 )", lineWidth = 1, loopStarted = false, refreshBackground = function() {}, doLoop = true, looping = 0, curRectMode = p.CORNER, curEllipseMode = p.CENTER, normalX = 0, normalY = 0, normalZ = 0, normalMode = p.NORMAL_MODE_AUTO, inDraw = false, curBackground = "rgba( 204, 204, 204, 1 )", curFrameRate = 60, curCursor = p.ARROW, oldCursor = curElement.style.cursor, curMsPerFrame = 1, curShape = p.POLYGON, curShapeCount = 0, curvePoints = [], curTightness = 0, curveDetail = 20, curveInited = false, colorModeA = 255, colorModeX = 255, colorModeY = 255, colorModeZ = 255, pathOpen = false, mousePressed = false, mouseDragging = false, keyPressed = false, curColorMode = p.RGB, curTint = function() {}, curTextSize = 12, curTextFont = "Arial", getLoaded = false, start = new Date().getTime(), timeSinceLastFPS = start, framesSinceLastFPS = 0, lastTextPos = [0, 0, 0], curveBasisMatrix, curveToBezierMatrix, curveDrawMatrix, bezierBasisInverse, bezierBasisMatrix, programObject3D, programObject2D, boxBuffer, boxNormBuffer, boxOutlineBuffer, sphereBuffer, lineBuffer, fillBuffer, pointBuffer; // User can only have MAX_LIGHTS lights var lightCount = 0; //sphere stuff var sphereDetailV = 0, sphereDetailU = 0, sphereX = [], sphereY = [], sphereZ = [], sinLUT = new Array(p.SINCOS_LENGTH), cosLUT = new Array(p.SINCOS_LENGTH), sphereVerts, sphereNorms; // Camera defaults and settings var cam, cameraInv, forwardTransform, reverseTransform, modelView, modelViewInv, userMatrixStack, inverseCopy, projection, manipulatingCamera = false, frustumMode = false, cameraFOV = 60 * (Math.PI / 180), cameraX = curElement.width / 2, cameraY = curElement.height / 2, cameraZ = cameraY / Math.tan(cameraFOV / 2), cameraNear = cameraZ / 10, cameraFar = cameraZ * 10, cameraAspect = curElement.width / curElement.height; var vertArray = [], isCurve = false, isBezier = false, firstVert = true; // Stores states for pushStyle() and popStyle(). var styleArray = new Array(0); // Vertices are specified in a counter-clockwise order // triangles are in this order: back, front, right, bottom, left, top var boxVerts = [0.5, 0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5]; var boxNorms = [0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0]; var boxOutlineVerts = [0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, -0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5]; // Vertex shader for points and lines var vertexShaderSource2D = "attribute vec3 Vertex;" + "uniform vec4 color;" + "uniform mat4 model;" + "uniform mat4 view;" + "uniform mat4 projection;" + "void main(void) {" + " gl_FrontColor = color;" + " gl_Position = projection * view * model * vec4(Vertex, 1.0);" + "}"; var fragmentShaderSource2D = "void main(void){" + " gl_FragColor = gl_Color;" + "}"; // Vertex shader for boxes and spheres var vertexShaderSource3D = "attribute vec3 Vertex;" + "attribute vec3 Normal;" + "uniform vec4 color;" + "uniform bool usingMat;" + "uniform vec3 specular;" + "uniform vec3 mat_emissive;" + "uniform vec3 mat_ambient;" + "uniform vec3 mat_specular;" + "uniform float shininess;" + "uniform mat4 model;" + "uniform mat4 view;" + "uniform mat4 projection;" + "uniform mat4 normalTransform;" + "uniform int lightCount;" + "uniform vec3 falloff;" + "struct Light {" + " bool dummy;" + " int type;" + " vec3 color;" + " vec3 position;" + " vec3 direction;" + " float angle;" + " vec3 halfVector;" + " float concentration;" + "};" + "uniform Light lights[8];" + "void AmbientLight( inout vec3 totalAmbient, in vec3 ecPos, in Light light ) {" + // Get the vector from the light to the vertex // Get the distance from the current vector to the light position " float d = length( light.position - ecPos );" + " float attenuation = 1.0 / ( falloff[0] + ( falloff[1] * d ) + ( falloff[2] * d * d ));" + " totalAmbient += light.color * attenuation;" + "}" + "void DirectionalLight( inout vec3 col, in vec3 ecPos, inout vec3 spec, in vec3 vertNormal, in Light light ) {" + " float powerfactor = 0.0;" + " float nDotVP = max(0.0, dot( vertNormal, light.position ));" + " float nDotVH = max(0.0, dot( vertNormal, normalize( light.position-ecPos )));" + " if( nDotVP != 0.0 ){" + " powerfactor = pow( nDotVH, shininess );" + " }" + " col += light.color * nDotVP;" + " spec += specular * powerfactor;" + "}" + "void PointLight( inout vec3 col, inout vec3 spec, in vec3 vertNormal, in vec3 ecPos, in vec3 eye, in Light light ) {" + " float powerfactor;" + // Get the vector from the light to the vertex " vec3 VP = light.position - ecPos;" + // Get the distance from the current vector to the light position " float d = length( VP ); " + // Normalize the light ray so it can be used in the dot product operation. " VP = normalize( VP );" + " float attenuation = 1.0 / ( falloff[0] + ( falloff[1] * d ) + ( falloff[2] * d * d ));" + " float nDotVP = max( 0.0, dot( vertNormal, VP ));" + " vec3 halfVector = normalize( VP + eye );" + " float nDotHV = max( 0.0, dot( vertNormal, halfVector ));" + " if( nDotVP == 0.0) {" + " powerfactor = 0.0;" + " }" + " else{" + " powerfactor = pow( nDotHV, shininess );" + " }" + " spec += specular * powerfactor * attenuation;" + " col += light.color * nDotVP * attenuation;" + "}" + /* */ "void SpotLight( inout vec3 col, inout vec3 spec, in vec3 vertNormal, in vec3 ecPos, in vec3 eye, in Light light ) {" + " float spotAttenuation;" + " float powerfactor;" + // calculate the vector from the current vertex to the light. " vec3 VP = light.position - ecPos; " + " vec3 ldir = normalize( light.direction );" + // get the distance from the spotlight and the vertex " float d = length( VP );" + " VP = normalize( VP );" + " float attenuation = 1.0 / ( falloff[0] + ( falloff[1] * d ) + ( falloff[2] * d * d ) );" + // dot product of the vector from vertex to light and light direction. " float spotDot = dot( VP, ldir );" + // if the vertex falls inside the cone " if( spotDot < cos( light.angle ) ) {" + " spotAttenuation = pow( spotDot, light.concentration );" + " }" + " else{" + " spotAttenuation = 1.0;" + " }" + " attenuation *= spotAttenuation;" + " float nDotVP = max( 0.0, dot( vertNormal, VP ));" + " vec3 halfVector = normalize( VP + eye );" + " float nDotHV = max( 0.0, dot( vertNormal, halfVector ));" + " if( nDotVP == 0.0 ) {" + " powerfactor = 0.0;" + " }" + " else {" + " powerfactor = pow( nDotHV, shininess );" + " }" + " spec += specular * powerfactor * attenuation;" + " col += light.color * nDotVP * attenuation;" + "}" + "void main(void) {" + " vec3 finalAmbient = vec3( 0.0, 0.0, 0.0 );" + " vec3 finalDiffuse = vec3( 0.0, 0.0, 0.0 );" + " vec3 finalSpecular = vec3( 0.0, 0.0, 0.0 );" + " vec3 norm = vec3( normalTransform * vec4( Normal, 0.0 ) );" + " vec4 ecPos4 = view * model * vec4(Vertex,1.0);" + " vec3 ecPos = (vec3(ecPos4))/ecPos4.w;" + " vec3 eye = vec3( 0.0, 0.0, 1.0 );" + // If there were no lights this draw call, just use the // assigned fill color of the shape and the specular value " if( lightCount == 0 ) {" + " gl_FrontColor = color + vec4(mat_specular,1.0);" + " }" + " else {" + " for( int i = 0; i < lightCount; i++ ) {" + " if( lights[i].type == 0 ) {" + " AmbientLight( finalAmbient, ecPos, lights[i] );" + " }" + " else if( lights[i].type == 1 ) {" + " DirectionalLight( finalDiffuse,ecPos, finalSpecular, norm, lights[i] );" + " }" + " else if( lights[i].type == 2 ) {" + " PointLight( finalDiffuse, finalSpecular, norm, ecPos, eye, lights[i] );" + " }" + " else if( lights[i].type == 3 ) {" + " SpotLight( finalDiffuse, finalSpecular, norm, ecPos, eye, lights[i] );" + " }" + " }" + " if( usingMat == false ) {" + " gl_FrontColor = vec4( " + " vec3(color) * finalAmbient +" + " vec3(color) * finalDiffuse +" + " vec3(color) * finalSpecular," + " color[3] );" + " }" + " else{" + " gl_FrontColor = vec4( " + " mat_emissive + " + " (vec3(color) * mat_ambient * finalAmbient) + " + " (vec3(color) * finalDiffuse) + " + " (mat_specular * finalSpecular), " + " color[3] );" + " }" + " }" + " gl_Position = projection * view * model * vec4( Vertex, 1.0 );" + "}"; var fragmentShaderSource3D = "void main(void){" + " gl_FragColor = gl_Color;" + "}"; // Wrapper to easily deal with array names changes. var newWebGLArray = function(data) { return new WebGLFloatArray(data); }; var imageModeCorner = function imageModeCorner(x, y, w, h, whAreSizes) { return { x: x, y: y, w: w, h: h }; }; var imageModeConvert = imageModeCorner; var imageModeCorners = function imageModeCorners(x, y, w, h, whAreSizes) { return { x: x, y: y, w: whAreSizes ? w : w - x, h: whAreSizes ? h : h - y }; }; var imageModeCenter = function imageModeCenter(x, y, w, h, whAreSizes) { return { x: x - w / 2, y: y - h / 2, w: w, h: h }; }; var createProgramObject = function(curContext, vetexShaderSource, fragmentShaderSource) { var vertexShaderObject = curContext.createShader(curContext.VERTEX_SHADER); curContext.shaderSource(vertexShaderObject, vetexShaderSource); curContext.compileShader(vertexShaderObject); if (!curContext.getShaderParameter(vertexShaderObject, curContext.COMPILE_STATUS)) { throw curContext.getShaderInfoLog(vertexShaderObject); } var fragmentShaderObject = curContext.createShader(curContext.FRAGMENT_SHADER); curContext.shaderSource(fragmentShaderObject, fragmentShaderSource); curContext.compileShader(fragmentShaderObject); if (!curContext.getShaderParameter(fragmentShaderObject, curContext.COMPILE_STATUS)) { throw curContext.getShaderInfoLog(fragmentShaderObject); } var programObject = curContext.createProgram(); curContext.attachShader(programObject, vertexShaderObject); curContext.attachShader(programObject, fragmentShaderObject); curContext.linkProgram(programObject); if (!curContext.getProgramParameter(programObject, curContext.LINK_STATUS)) { throw "Error linking shaders."; } return programObject; }; //////////////////////////////////////////////////////////////////////////// // Char handling //////////////////////////////////////////////////////////////////////////// var charMap = {}; var Char = function Char(chr) { if (typeof chr === 'string' && chr.length === 1) { this.code = chr.charCodeAt(0); } else { this.code = NaN; } return (typeof charMap[this.code] === 'undefined') ? charMap[this.code] = this : charMap[this.code]; }; Char.prototype.toString = function() { return String.fromCharCode(this.code); }; Char.prototype.valueOf = function() { return this.code; }; //////////////////////////////////////////////////////////////////////////// // PVector //////////////////////////////////////////////////////////////////////////// var PVector = function(x, y, z) { this.x = x || 0; this.y = y || 0; this.z = z || 0; }, createPVectorMethod = function(method) { return function(v1, v2) { var v = v1.get(); v[method](v2); return v; }; }, createSimplePVectorMethod = function(method) { return function(v1, v2) { return v1[method](v2); }; }, simplePVMethods = "dist dot cross".split(" "), method = simplePVMethods.length; PVector.angleBetween = function(v1, v2) { return Math.acos(v1.dot(v2) / (v1.mag() * v2.mag())); }; // Common vector operations for PVector PVector.prototype = { set: function(v, y, z) { if (arguments.length === 1) { this.set(v.x || v[0], v.y || v[1], v.z || v[2]); } else { this.x = v; this.y = y; this.z = z; } }, get: function() { return new PVector(this.x, this.y, this.z); }, mag: function() { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); }, add: function(v, y, z) { if (arguments.length === 3) { this.x += v; this.y += y; this.z += z; } else if (arguments.length === 1) { this.x += v.x; this.y += v.y; this.z += v.z; } }, sub: function(v, y, z) { if (arguments.length === 3) { this.x -= v; this.y -= y; this.z -= z; } else if (arguments.length === 1) { this.x -= v.x; this.y -= v.y; this.z -= v.z; } }, mult: function(v) { if (typeof v === 'number') { this.x *= v; this.y *= v; this.z *= v; } else if (typeof v === 'object') { this.x *= v.x; this.y *= v.y; this.z *= v.z; } }, div: function(v) { if (typeof v === 'number') { this.x /= v; this.y /= v; this.z /= v; } else if (typeof v === 'object') { this.x /= v.x; this.y /= v.y; this.z /= v.z; } }, dist: function(v) { var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; return Math.sqrt(dx * dx + dy * dy + dz * dz); }, dot: function(v, y, z) { var num; if (arguments.length === 3) { num = this.x * v + this.y * y + this.z * z; } else if (arguments.length === 1) { num = this.x * v.x + this.y * v.y + this.z * v.z; } return num; }, cross: function(v) { var crossX = this.y * v.z - v.y * this.z, crossY = this.z * v.x - v.z * this.x, crossZ = this.x * v.y - v.x * this.y; return new PVector(crossX, crossY, crossZ); }, normalize: function() { var m = this.mag(); if (m > 0) { this.div(m); } }, limit: function(high) { if (this.mag() > high) { this.normalize(); this.mult(high); } }, heading2D: function() { var angle = Math.atan2(-this.y, this.x); return -angle; }, toString: function() { return "[" + this.x + ", " + this.y + ", " + this.z + "]"; }, array: function() { return [this.x, this.y, this.z]; } }; while (method--) { PVector[simplePVMethods[method]] = createSimplePVectorMethod(simplePVMethods[method]); } for (method in PVector.prototype) { if (PVector.prototype.hasOwnProperty(method) && !PVector.hasOwnProperty(method)) { PVector[method] = createPVectorMethod(method); } } p.PVector = PVector; //////////////////////////////////////////////////////////////////////////// // 2D Matrix //////////////////////////////////////////////////////////////////////////// /* Helper function for printMatrix(). Finds the largest scalar in the matrix, then number of digits left of the decimal. Call from PMatrix2D and PMatrix3D's print() function. */ var printMatrixHelper = function printMatrixHelper(elements) { var big = 0; for (var i = 0; i < elements.length; i++) { if (i !== 0) { big = Math.max(big, Math.abs(elements[i])); } else { big = Math.abs(elements[i]); } } var digits = (big + "").indexOf("."); if (digits === 0) { digits = 1; } else if (digits === -1) { digits = (big + "").length; } return digits; }; var PMatrix2D = function() { if (arguments.length === 0) { this.reset(); } else if (arguments.length === 1 && arguments[0] instanceof PMatrix2D) { this.set(arguments[0].array()); } else if (arguments.length === 6) { this.set(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]); } }; PMatrix2D.prototype = { set: function() { if (arguments.length === 6) { var a = arguments; this.set([a[0], a[1], a[2], a[3], a[4], a[5]]); } else if (arguments.length === 1 && arguments[0] instanceof PMatrix2D) { this.elements = arguments[0].array(); } else if (arguments.length === 1 && arguments[0] instanceof Array) { this.elements = arguments[0].slice(); } }, get: function() { var outgoing = new PMatrix2D(); outgoing.set(this.elements); return outgoing; }, reset: function() { this.set([1, 0, 0, 0, 1, 0]); }, // Returns a copy of the element values. array: function array() { return this.elements.slice(); }, translate: function(tx, ty) { this.elements[2] = tx * this.elements[0] + ty * this.elements[1] + this.elements[2]; this.elements[5] = tx * this.elements[3] + ty * this.elements[4] + this.elements[5]; }, // Does nothing in Processing. transpose: function() { }, mult: function(source, target) { var x, y; if (source instanceof PVector) { x = source.x; y = source.y; if (!target) { target = new PVector(); } } else if (source instanceof Array) { x = source[0]; y = source[1]; if (!target) { target = []; } } if (target instanceof Array) { target[0] = this.elements[0] * x + this.elements[1] * y + this.elements[2]; target[1] = this.elements[3] * x + this.elements[4] * y + this.elements[5]; } else if (target instanceof PVector) { target.x = this.elements[0] * x + this.elements[1] * y + this.elements[2]; target.y = this.elements[3] * x + this.elements[4] * y + this.elements[5]; target.z = 0; } return target; }, multX: function(x, y) { return x * this.elements[0] + y * this.elements[1] + this.elements[2]; }, multY: function(x, y) { return x * this.elements[3] + y * this.elements[4] + this.elements[5]; }, skewX: function(angle) { this.apply(1, 0, 1, angle, 0, 0); }, skewY: function(angle) { this.apply(1, 0, 1, 0, angle, 0); }, determinant: function() { return this.elements[0] * this.elements[4] - this.elements[1] * this.elements[3]; }, invert: function() { var d = this.determinant(); if ( Math.abs( d ) > p.FLOAT_MIN ) { var old00 = this.elements[0]; var old01 = this.elements[1]; var old02 = this.elements[2]; var old10 = this.elements[3]; var old11 = this.elements[4]; var old12 = this.elements[5]; this.elements[0] = old11 / d; this.elements[3] = -old10 / d; this.elements[1] = -old01 / d; this.elements[1] = old00 / d; this.elements[2] = (old01 * old12 - old11 * old02) / d; this.elements[5] = (old10 * old02 - old00 * old12) / d; return true; } return false; }, scale: function(sx, sy) { if (sx && !sy) { sy = sx; } if (sx && sy) { this.elements[0] *= sx; this.elements[1] *= sy; this.elements[3] *= sx; this.elements[4] *= sy; } }, apply: function() { if (arguments.length === 1 && arguments[0] instanceof PMatrix2D) { this.apply(arguments[0].array()); } else if (arguments.length === 6) { var a = arguments; this.apply([a[0], a[1], a[2], a[3], a[4], a[5]]); } else if (arguments.length === 1 && arguments[0] instanceof Array) { var source = arguments[0]; var result = [0, 0, this.elements[2], 0, 0, this.elements[5]]; var e = 0; for (var row = 0; row < 2; row++) { for (var col = 0; col < 3; col++, e++) { result[e] += this.elements[row * 3 + 0] * source[col + 0] + this.elements[row * 3 + 1] * source[col + 3]; } } this.elements = result.slice(); } }, preApply: function() { if (arguments.length === 1 && arguments[0] instanceof PMatrix2D) { this.preApply(arguments[0].array()); } else if (arguments.length === 6) { var a = arguments; this.preApply([a[0], a[1], a[2], a[3], a[4], a[5]]); } else if (arguments.length === 1 && arguments[0] instanceof Array) { var source = arguments[0]; var result = [0, 0, source[2], 0, 0, source[5]]; result[2]= source[2] + this.elements[2] * source[0] + this.elements[5] * source[1]; result[5]= source[5] + this.elements[2] * source[3] + this.elements[5] * source[4]; result[0] = this.elements[0] * source[0] + this.elements[3] * source[1]; result[3] = this.elements[0] * source[3] + this.elements[3] * source[4]; result[1] = this.elements[1] * source[0] + this.elements[4] * source[1]; result[4] = this.elements[1] * source[3] + this.elements[4] * source[4]; this.elements = result.slice(); } }, rotate: function(angle) { var c = Math.cos(angle); var s = Math.sin(angle); var temp1 = this.elements[0]; var temp2 = this.elements[1]; this.elements[0] = c * temp1 + s * temp2; this.elements[1] = -s * temp1 + c * temp2; temp1 = this.elements[3]; temp2 = this.elements[4]; this.elements[3] = c * temp1 + s * temp2; this.elements[4] = -s * temp1 + c * temp2; }, rotateZ: function(angle) { this.rotate(angle); }, print: function() { var digits = printMatrixHelper(this.elements); var output = ""; output += p.nfs(this.elements[0], digits, 4) + " " + p.nfs(this.elements[1], digits, 4) + " " + p.nfs(this.elements[2], digits, 4) + "\n"; output += p.nfs(this.elements[3], digits, 4) + " " + p.nfs(this.elements[4], digits, 4) + " " + p.nfs(this.elements[5], digits, 4) + "\n\n"; p.println(output); } }; //////////////////////////////////////////////////////////////////////////// // PMatrix3D //////////////////////////////////////////////////////////////////////////// var PMatrix3D = function PMatrix3D() { //When a matrix is created, it is set to an identity matrix this.reset(); }; PMatrix3D.prototype = { set: function() { if (arguments.length === 16) { var a = arguments; this.set([a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]]); } else if (arguments.length === 1 && arguments[0] instanceof PMatrix3D) { this.elements = arguments[0].array(); } else if (arguments.length === 1 && arguments[0] instanceof Array) { this.elements = arguments[0].slice(); } }, get: function() { var outgoing = new PMatrix3D(); outgoing.set(this.elements); return outgoing; }, reset: function() { this.set([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); }, // Returns a copy of the element values. array: function array() { return this.elements.slice(); }, translate: function(tx, ty, tz) { if (typeof tz === 'undefined') { tx = 0; } this.elements[3] += tx * this.elements[0] + ty * this.elements[1] + tz * this.elements[2]; this.elements[7] += tx * this.elements[4] + ty * this.elements[5] + tz * this.elements[6]; this.elements[11] += tx * this.elements[8] + ty * this.elements[9] + tz * this.elements[10]; this.elements[15] += tx * this.elements[12] + ty * this.elements[13] + tz * this.elements[14]; }, transpose: function() { var temp = this.elements.slice(); this.elements[0] = temp[0]; this.elements[1] = temp[4]; this.elements[2] = temp[8]; this.elements[3] = temp[12]; this.elements[4] = temp[1]; this.elements[5] = temp[5]; this.elements[6] = temp[9]; this.elements[7] = temp[13]; this.elements[8] = temp[2]; this.elements[9] = temp[6]; this.elements[10] = temp[10]; this.elements[11] = temp[14]; this.elements[12] = temp[3]; this.elements[13] = temp[7]; this.elements[14] = temp[11]; this.elements[15] = temp[15]; }, /* You must either pass in two PVectors or two arrays, don't mix between types. You may also omit a second argument and simply read the result from the return. */ mult: function(source, target) { var x, y, z, w; if (source instanceof PVector) { x = source.x; y = source.y; z = source.z; w = 1; if (!target) { target = new PVector(); } } else if (source instanceof Array) { x = source[0]; y = source[1]; z = source[2]; w = source[3] || 1; if (!target || target.length !== 3 && target.length !== 4) { target = [0, 0, 0]; } } if (target instanceof Array) { if (target.length === 3) { target[0] = this.elements[0] * x + this.elements[1] * y + this.elements[2] * z + this.elements[3]; target[1] = this.elements[4] * x + this.elements[5] * y + this.elements[6] * z + this.elements[7]; target[2] = this.elements[8] * x + this.elements[9] * y + this.elements[10] * z + this.elements[11]; } else if (target.length === 4) { target[0] = this.elements[0] * x + this.elements[1] * y + this.elements[2] * z + this.elements[3] * w; target[1] = this.elements[4] * x + this.elements[5] * y + this.elements[6] * z + this.elements[7] * w; target[2] = this.elements[8] * x + this.elements[9] * y + this.elements[10] * z + this.elements[11] * w; target[3] = this.elements[12] * x + this.elements[13] * y + this.elements[14] * z + this.elements[15] * w; } } if (target instanceof PVector) { target.x = this.elements[0] * x + this.elements[1] * y + this.elements[2] * z + this.elements[3]; target.y = this.elements[4] * x + this.elements[5] * y + this.elements[6] * z + this.elements[7]; target.z = this.elements[8] * x + this.elements[9] * y + this.elements[10] * z + this.elements[11]; } return target; }, preApply: function() { if (arguments.length === 1 && arguments[0] instanceof PMatrix3D) { this.preApply(arguments[0].array()); } else if (arguments.length === 16) { var a = arguments; this.preApply([a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]]); } else if (arguments.length === 1 && arguments[0] instanceof Array) { var source = arguments[0]; var result = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; var e = 0; for (var row = 0; row < 4; row++) { for (var col = 0; col < 4; col++, e++) { result[e] += this.elements[col + 0] * source[row * 4 + 0] + this.elements[col + 4] * source[row * 4 + 1] + this.elements[col + 8] * source[row * 4 + 2] + this.elements[col + 12] * source[row * 4 + 3]; } } this.elements = result.slice(); } }, apply: function() { if (arguments.length === 1 && arguments[0] instanceof PMatrix3D) { this.apply(arguments[0].array()); } else if (arguments.length === 16) { var a = arguments; this.apply([a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]]); } else if (arguments.length === 1 && arguments[0] instanceof Array) { var source = arguments[0]; var result = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; var e = 0; for (var row = 0; row < 4; row++) { for (var col = 0; col < 4; col++, e++) { result[e] += this.elements[row * 4 + 0] * source[col + 0] + this.elements[row * 4 + 1] * source[col + 4] + this.elements[row * 4 + 2] * source[col + 8] + this.elements[row * 4 + 3] * source[col + 12]; } } this.elements = result.slice(); } }, rotate: function(angle, v0, v1, v2) { if (!v1) { this.rotateZ(angle); } else { // TODO should make sure this vector is normalized var c = p.cos(angle); var s = p.sin(angle); var t = 1.0 - c; this.apply((t * v0 * v0) + c, (t * v0 * v1) - (s * v2), (t * v0 * v2) + (s * v1), 0, (t * v0 * v1) + (s * v2), (t * v1 * v1) + c, (t * v1 * v2) - (s * v0), 0, (t * v0 * v2) - (s * v1), (t * v1 * v2) + (s * v0), (t * v2 * v2) + c, 0, 0, 0, 0, 1); } }, invApply: function() { if (typeof inverseCopy === "undefined") { inverseCopy = new PMatrix3D(); } var a = arguments; inverseCopy.set(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]); if (!inverseCopy.invert()) { return false; } this.preApply(inverseCopy); return true; }, rotateX: function(angle) { var c = p.cos(angle); var s = p.sin(angle); this.apply([1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1]); }, rotateY: function(angle) { var c = p.cos(angle); var s = p.sin(angle); this.apply([c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1]); }, rotateZ: function(angle) { var c = Math.cos(angle); var s = Math.sin(angle); this.apply([c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); }, // Uniform scaling if only one value passed in scale: function(sx, sy, sz) { if (sx && !sy && !sz) { sy = sz = sx; } else if (sx && sy && !sz) { sz = 1; } if (sx && sy && sz) { this.elements[0] *= sx; this.elements[1] *= sy; this.elements[2] *= sz; this.elements[4] *= sx; this.elements[5] *= sy; this.elements[6] *= sz; this.elements[8] *= sx; this.elements[9] *= sy; this.elements[10] *= sz; this.elements[12] *= sx; this.elements[13] *= sy; this.elements[14] *= sz; } }, skewX: function(angle) { var t = p.tan(angle); this.apply(1, t, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); }, skewY: function(angle) { var t = Math.tan(angle); this.apply(1, 0, 0, 0, t, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); }, multX: function(x, y, z, w) { if (!z) { return this.elements[0] * x + this.elements[1] * y + this.elements[3]; } else if (!w) { return this.elements[0] * x + this.elements[1] * y + this.elements[2] * z + this.elements[3]; } else { return this.elements[0] * x + this.elements[1] * y + this.elements[2] * z + this.elements[3] * w; } }, multY: function(x, y, z, w) { if (!z) { return this.elements[4] * x + this.elements[5] * y + this.elements[7]; } else if (!w) { return this.elements[4] * x + this.elements[5] * y + this.elements[6] * z + this.elements[7]; } else { return this.elements[4] * x + this.elements[5] * y + this.elements[6] * z + this.elements[7] * w; } }, multZ: function(x, y, z, w) { if (!w) { return this.elements[8] * x + this.elements[9] * y + this.elements[10] * z + this.elements[11]; } else { return this.elements[8] * x + this.elements[9] * y + this.elements[10] * z + this.elements[11] * w; } }, multW: function(x, y, z, w) { if (!w) { return this.elements[12] * x + this.elements[13] * y + this.elements[14] * z + this.elements[15]; } else { return this.elements[12] * x + this.elements[13] * y + this.elements[14] * z + this.elements[15] * w; } }, invert: function() { var kInv = []; var fA0 = this.elements[0] * this.elements[5] - this.elements[1] * this.elements[4]; var fA1 = this.elements[0] * this.elements[6] - this.elements[2] * this.elements[4]; var fA2 = this.elements[0] * this.elements[7] - this.elements[3] * this.elements[4]; var fA3 = this.elements[1] * this.elements[6] - this.elements[2] * this.elements[5]; var fA4 = this.elements[1] * this.elements[7] - this.elements[3] * this.elements[5]; var fA5 = this.elements[2] * this.elements[7] - this.elements[3] * this.elements[6]; var fB0 = this.elements[8] * this.elements[13] - this.elements[9] * this.elements[12]; var fB1 = this.elements[8] * this.elements[14] - this.elements[10] * this.elements[12]; var fB2 = this.elements[8] * this.elements[15] - this.elements[11] * this.elements[12]; var fB3 = this.elements[9] * this.elements[14] - this.elements[10] * this.elements[13]; var fB4 = this.elements[9] * this.elements[15] - this.elements[11] * this.elements[13]; var fB5 = this.elements[10] * this.elements[15] - this.elements[11] * this.elements[14]; // Determinant var fDet = fA0 * fB5 - fA1 * fB4 + fA2 * fB3 + fA3 * fB2 - fA4 * fB1 + fA5 * fB0; // Account for a very small value // return false if not successful. if (Math.abs(fDet) <= 1e-9) { return false; } kInv[0] = +this.elements[5] * fB5 - this.elements[6] * fB4 + this.elements[7] * fB3; kInv[4] = -this.elements[4] * fB5 + this.elements[6] * fB2 - this.elements[7] * fB1; kInv[8] = +this.elements[4] * fB4 - this.elements[5] * fB2 + this.elements[7] * fB0; kInv[12] = -this.elements[4] * fB3 + this.elements[5] * fB1 - this.elements[6] * fB0; kInv[1] = -this.elements[1] * fB5 + this.elements[2] * fB4 - this.elements[3] * fB3; kInv[5] = +this.elements[0] * fB5 - this.elements[2] * fB2 + this.elements[3] * fB1; kInv[9] = -this.elements[0] * fB4 + this.elements[1] * fB2 - this.elements[3] * fB0; kInv[13] = +this.elements[0] * fB3 - this.elements[1] * fB1 + this.elements[2] * fB0; kInv[2] = +this.elements[13] * fA5 - this.elements[14] * fA4 + this.elements[15] * fA3; kInv[6] = -this.elements[12] * fA5 + this.elements[14] * fA2 - this.elements[15] * fA1; kInv[10] = +this.elements[12] * fA4 - this.elements[13] * fA2 + this.elements[15] * fA0; kInv[14] = -this.elements[12] * fA3 + this.elements[13] * fA1 - this.elements[14] * fA0; kInv[3] = -this.elements[9] * fA5 + this.elements[10] * fA4 - this.elements[11] * fA3; kInv[7] = +this.elements[8] * fA5 - this.elements[10] * fA2 + this.elements[11] * fA1; kInv[11] = -this.elements[8] * fA4 + this.elements[9] * fA2 - this.elements[11] * fA0; kInv[15] = +this.elements[8] * fA3 - this.elements[9] * fA1 + this.elements[10] * fA0; // Inverse using Determinant var fInvDet = 1.0 / fDet; kInv[0] *= fInvDet; kInv[1] *= fInvDet; kInv[2] *= fInvDet; kInv[3] *= fInvDet; kInv[4] *= fInvDet; kInv[5] *= fInvDet; kInv[6] *= fInvDet; kInv[7] *= fInvDet; kInv[8] *= fInvDet; kInv[9] *= fInvDet; kInv[10] *= fInvDet; kInv[11] *= fInvDet; kInv[12] *= fInvDet; kInv[13] *= fInvDet; kInv[14] *= fInvDet; kInv[15] *= fInvDet; this.elements = kInv.slice(); return true; }, toString: function() { var str = ""; for (var i = 0; i < 15; i++) { str += this.elements[i] + ", "; } str += this.elements[15]; return str; }, print: function() { var digits = printMatrixHelper(this.elements); var output = ""; output += p.nfs(this.elements[0], digits, 4) + " " + p.nfs(this.elements[1], digits, 4) + " " + p.nfs(this.elements[2], digits, 4) + " " + p.nfs(this.elements[3], digits, 4) + "\n"; output += p.nfs(this.elements[4], digits, 4) + " " + p.nfs(this.elements[5], digits, 4) + " " + p.nfs(this.elements[6], digits, 4) + " " + p.nfs(this.elements[7], digits, 4) + "\n"; output += p.nfs(this.elements[8], digits, 4) + " " + p.nfs(this.elements[9], digits, 4) + " " + p.nfs(this.elements[10], digits, 4) + " " + p.nfs(this.elements[11], digits, 4) + "\n"; output += p.nfs(this.elements[12], digits, 4) + " " + p.nfs(this.elements[13], digits, 4) + " " + p.nfs(this.elements[14], digits, 4) + " " + p.nfs(this.elements[15], digits, 4) + "\n\n"; p.println(output); }, invTranslate: function(tx, ty, tz) { this.preApply(1, 0, 0, -tx, 0, 1, 0, -ty, 0, 0, 1, -tz, 0, 0, 0, 1); }, invRotateX: function(angle) { var c = p.cos(-angle); var s = p.sin(-angle); this.preApply([1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1]); }, invRotateY: function(angle) { var c = p.cos(-angle); var s = p.sin(-angle); this.preApply([c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1]); }, invRotateZ: function(angle) { var c = p.cos(-angle); var s = p.sin(-angle); this.preApply([c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); }, invScale: function(x, y, z) { this.preApply([1 / x, 0, 0, 0, 0, 1 / y, 0, 0, 0, 0, 1 / z, 0, 0, 0, 0, 1]); } }; //////////////////////////////////////////////////////////////////////////// // Matrix Stack //////////////////////////////////////////////////////////////////////////// var PMatrixStack = function PMatrixStack() { this.matrixStack = []; }; PMatrixStack.prototype.load = function load() { var tmpMatrix; if (p.use3DContext) { tmpMatrix = new PMatrix3D(); } else { tmpMatrix = new PMatrix2D(); } if (arguments.length === 1) { tmpMatrix.set(arguments[0]); } else { tmpMatrix.set(arguments); } this.matrixStack.push(tmpMatrix); }; PMatrixStack.prototype.push = function push() { this.matrixStack.push(this.peek()); }; PMatrixStack.prototype.pop = function pop() { return this.matrixStack.pop(); }; PMatrixStack.prototype.peek = function peek() { var tmpMatrix; if (p.use3DContext) { tmpMatrix = new PMatrix3D(); } else { tmpMatrix = new PMatrix2D(); } tmpMatrix.set(this.matrixStack[this.matrixStack.length - 1]); return tmpMatrix; }; PMatrixStack.prototype.mult = function mult(matrix) { this.matrixStack[this.matrixStack.length - 1].apply(matrix); }; //////////////////////////////////////////////////////////////////////////// // Array handling //////////////////////////////////////////////////////////////////////////// p.split = function(str, delim) { return str.split(delim); }; p.splitTokens = function(str, tokens) { if (arguments.length === 1) { tokens = "\n\t\r\f "; } tokens = "[" + tokens + "]"; var ary = new Array(0); var index = 0; var pos = str.search(tokens); while (pos >= 0) { if (pos === 0) { str = str.substring(1); } else { ary[index] = str.substring(0, pos); index++; str = str.substring(pos); } pos = str.search(tokens); } if (str.length > 0) { ary[index] = str; } if (ary.length === 0) { ary = undefined; } return ary; }; p.append = function(array, element) { array[array.length] = element; return array; }; p.concat = function(array1, array2) { return array1.concat(array2); }; p.sort = function(array, numElem) { var ret = []; // depending on the type used (int, float) or string // we'll need to use a different compare function if (array.length > 0) { // copy since we need to return another array var elemsToCopy = numElem > 0 ? numElem : array.length; for (var i = 0; i < elemsToCopy; i++) { ret.push(array[i]); } if (typeof array[0] === "string") { ret.sort(); } // int or float else { ret.sort(function(a, b) { return a - b; }); } // copy on the rest of the elements that were not sorted in case the user // only wanted a subset of an array to be sorted. if (numElem > 0) { for (var j = ret.length; j < array.length; j++) { ret.push(array[j]); } } } return ret; }; p.splice = function(array, value, index) { if (array.length === 0 && value.length === 0) { return array; } if (value instanceof Array) { for (var i = 0, j = index; i < value.length; j++, i++) { array.splice(j, 0, value[i]); } } else { array.splice(index, 0, value); } return array; }; p.subset = function(array, offset, length) { if (arguments.length === 2) { return p.subset(array, offset, array.length - offset); } else if (arguments.length === 3) { return array.slice(offset, offset + length); } }; p.join = function(array, seperator) { return array.join(seperator); }; p.shorten = function(ary) { var newary = new Array(0); // copy array into new array var len = ary.length; for (var i = 0; i < len; i++) { newary[i] = ary[i]; } newary.pop(); return newary; }; p.expand = function(ary, newSize) { var newary = new Array(0); var len = ary.length; for (var i = 0; i < len; i++) { newary[i] = ary[i]; } if (arguments.length === 1) { // double size of array newary.length *= 2; } else if (arguments.length === 2) { // size is newSize newary.length = newSize; } return newary; }; p.arrayCopy = function(src, srcPos, dest, destPos, length) { if (arguments.length === 2) { // recall itself and copy src to dest from start index 0 to 0 of src.length p.arrayCopy(src, 0, srcPos, 0, src.length); } else if (arguments.length === 3) { // recall itself and copy src to dest from start index 0 to 0 of length p.arrayCopy(src, 0, srcPos, 0, dest); } else if (arguments.length === 5) { // copy src to dest from index srcPos to index destPos of length recursivly on objects for (var i = srcPos, j = destPos; i < length + srcPos; i++, j++) { if (src[i] && typeof src[i] === "object") { // src[i] is not null and is another object or array. go recursive p.arrayCopy(src[i], 0, dest[j], 0, src[i].length); } else { // standard type, just copy dest[j] = src[i]; } } } }; p.ArrayList = function() { var createArrayList = function(args){ var array = []; for (var i = 0; i < args[0]; i++){ array[i] = (args.length > 1 ? createArrayList(args.slice(1)) : 0 ); } array.get = function(i) { return this[i]; }; array.contains = function(item) { return this.indexOf(item) !== -1; }; array.add = function(item) { return this.push(item); }; array.size = function() { return this.length; }; array.clear = function() { this.length = 0; }; array.remove = function(i) { return this.splice(i, 1)[0]; }; array.isEmpty = function() { return !this.length; }; array.clone = function() { var size = this.length; var a = new p.ArrayList(size); for (var i = 0; i < size; i++) { a[i] = this[i]; } return a; }; return array; }; return createArrayList(Array.prototype.slice.call(arguments)); }; p.reverse = function(array) { return array.reverse(); }; //////////////////////////////////////////////////////////////////////////// // HashMap //////////////////////////////////////////////////////////////////////////// var virtHashCode = function virtHashCode(obj) { if (obj.constructor === String) { var hash = 0; for (var i = 0; i < obj.length; ++i) { hash = (hash * 31 + obj.charCodeAt(i)) & 0xFFFFFFFF; } return hash; } else if (typeof(obj) !== "object") { return obj & 0xFFFFFFFF; } else if ("hashCode" in obj) { return obj.hashCode.call(obj); } else { if (obj.$id === undefined) { obj.$id = ((Math.floor(Math.random() * 0x10000) - 0x8000) << 16) | Math.floor(Math.random() * 0x10000); } return obj.$id; } }; var virtEquals = function virtEquals(obj, other) { if (obj === null || other === null) { return (obj === null) && (other === null); } else if (obj.constructor === String) { return obj === other; } else if (typeof(obj) !== "object") { return obj === other; } else if ("equals" in obj) { return obj.equals.call(obj, other); } else { return obj === other; } }; p.HashMap = function HashMap() { if (arguments.length === 1 && arguments[0].constructor === HashMap) { return arguments[0].clone(); } var initialCapacity = arguments.length > 0 ? arguments[0] : 16; var loadFactor = arguments.length > 1 ? arguments[1] : 0.75; var buckets = new Array(initialCapacity); var count = 0; var hashMap = this; function ensureLoad() { if (count <= loadFactor * buckets.length) { return; } var allEntries = []; for (var i = 0; i < buckets.length; ++i) { if (buckets[i] !== undefined) { allEntries = allEntries.concat(buckets[i]); } } buckets = new Array(buckets.length * 2); for (var j = 0; j < allEntries.length; ++j) { var index = virtHashCode(allEntries[j].key) % buckets.length; var bucket = buckets[index]; if (bucket === undefined) { buckets[index] = bucket = []; } bucket.push(allEntries[j]); } } function Iterator(conversion, removeItem) { var bucketIndex = 0; var itemIndex = -1; var endOfBuckets = false; function findNext() { while (!endOfBuckets) { ++itemIndex; if (bucketIndex >= buckets.length) { endOfBuckets = true; } else if (typeof(buckets[bucketIndex]) === 'undefined' || itemIndex >= buckets[bucketIndex].length) { itemIndex = -1; ++bucketIndex; } else { return; } } } this.hasNext = function() { return !endOfBuckets; }; this.next = function() { var result = conversion(buckets[bucketIndex][itemIndex]); findNext(); return result; }; this.remove = function() { removeItem(this.next()); --itemIndex; }; findNext(); } function Set(conversion, isIn, removeItem) { this.clear = function() { hashMap.clear(); }; this.contains = function(o) { return isIn(o); }; this.containsAll = function(o) { var it = o.iterator(); while (it.hasNext()) { if (!this.contains(it.next())) { return false; } } return true; }; this.isEmpty = function() { return hashMap.isEmpty(); }; this.iterator = function() { return new Iterator(conversion, removeItem); }; this.remove = function(o) { if (this.contains(o)) { removeItem(o); return true; } return false; }; this.removeAll = function(c) { var it = c.iterator(); var changed = false; while (it.hasNext()) { var item = it.next(); if (this.contains(item)) { removeItem(item); changed = true; } } return true; }; this.retainAll = function(c) { var it = this.iterator(); var toRemove = []; while (it.hasNext()) { var entry = it.next(); if (!c.contains(entry)) { toRemove.push(entry); } } for (var i = 0; i < toRemove.length; ++i) { removeItem(toRemove[i]); } return toRemove.length > 0; }; this.size = function() { return hashMap.size(); }; this.toArray = function() { var result = new p.ArrayList(0); var it = this.iterator(); while (it.hasNext()) { result.push(it.next()); } return result; }; } function Entry(pair) { this._isIn = function(map) { return map === hashMap && (typeof(pair.removed) === 'undefined'); }; this.equals = function(o) { return virtEquals(pair.key, o.getKey()); }; this.getKey = function() { return pair.key; }; this.getValue = function() { return pair.value; }; this.hashCode = function(o) { return virtHashCode(pair.key); }; this.setValue = function(value) { var old = pair.value; pair.value = value; return old; }; } this.clear = function() { count = 0; buckets = new Array(initialCapacity); }; this.clone = function() { var map = new p.HashMap(); map.putAll(this); return map; }; this.containsKey = function(key) { var index = virtHashCode(key) % buckets.length; var bucket = buckets[index]; if (bucket === undefined) { return false; } for (var i = 0; i < bucket.length; ++i) { if (virtEquals(bucket[i].key, key)) { return true; } } return false; }; this.containsValue = function(value) { for (var i = 0; i < buckets.length; ++i) { var bucket = buckets[i]; if (bucket === undefined) { continue; } for (var j = 0; j < bucket.length; ++j) { if (virtEquals(bucket[j].value, value)) { return true; } } } return false; }; this.entrySet = function() { return new Set( function(pair) { return new Entry(pair); }, function(pair) { return pair.constructor === Entry && pair._isIn(hashMap); }, function(pair) { return hashMap.remove(pair.getKey()); }); }; this.get = function(key) { var index = virtHashCode(key) % buckets.length; var bucket = buckets[index]; if (bucket === undefined) { return null; } for (var i = 0; i < bucket.length; ++i) { if (virtEquals(bucket[i].key, key)) { return bucket[i].value; } } return null; }; this.isEmpty = function() { return count === 0; }; this.keySet = function() { return new Set( function(pair) { return pair.key; }, function(key) { return hashMap.containsKey(key); }, function(key) { return hashMap.remove(key); }); }; this.put = function(key, value) { var index = virtHashCode(key) % buckets.length; var bucket = buckets[index]; if (bucket === undefined) { ++count; buckets[index] = [{ key: key, value: value }]; ensureLoad(); return null; } for (var i = 0; i < bucket.length; ++i) { if (virtEquals(bucket[i].key, key)) { var previous = bucket[i].value; bucket[i].value = value; return previous; } }++count; bucket.push({ key: key, value: value }); ensureLoad(); return null; }; this.putAll = function(m) { var it = m.entrySet().iterator(); while (it.hasNext()) { var entry = it.next(); this.put(entry.getKey(), entry.getValue()); } }; this.remove = function(key) { var index = virtHashCode(key) % buckets.length; var bucket = buckets[index]; if (bucket === undefined) { return null; } for (var i = 0; i < bucket.length; ++i) { if (virtEquals(bucket[i].key, key)) { --count; var previous = bucket[i].value; bucket[i].removed = true; if (bucket.length > 1) { bucket.splice(i, 1); } else { buckets[index] = undefined; } return previous; } } return null; }; this.size = function() { return count; }; this.values = function() { var result = new p.ArrayList(0); var it = this.entrySet().iterator(); while (it.hasNext()) { var entry = it.next(); result.push(entry.getValue()); } return result; }; }; //////////////////////////////////////////////////////////////////////////// // Color functions //////////////////////////////////////////////////////////////////////////// // helper functions for internal blending modes p.mix = function(a, b, f) { return a + (((b - a) * f) >> 8); }; p.peg = function(n) { return (n < 0) ? 0 : ((n > 255) ? 255 : n); }; // blending modes p.modes = { replace: function(c1, c2) { return c2; }, blend: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | p.mix(c1 & p.RED_MASK, c2 & p.RED_MASK, f) & p.RED_MASK | p.mix(c1 & p.GREEN_MASK, c2 & p.GREEN_MASK, f) & p.GREEN_MASK | p.mix(c1 & p.BLUE_MASK, c2 & p.BLUE_MASK, f)); }, add: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | Math.min(((c1 & p.RED_MASK) + ((c2 & p.RED_MASK) >> 8) * f), p.RED_MASK) & p.RED_MASK | Math.min(((c1 & p.GREEN_MASK) + ((c2 & p.GREEN_MASK) >> 8) * f), p.GREEN_MASK) & p.GREEN_MASK | Math.min((c1 & p.BLUE_MASK) + (((c2 & p.BLUE_MASK) * f) >> 8), p.BLUE_MASK)); }, subtract: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | Math.max(((c1 & p.RED_MASK) - ((c2 & p.RED_MASK) >> 8) * f), p.GREEN_MASK) & p.RED_MASK | Math.max(((c1 & p.GREEN_MASK) - ((c2 & p.GREEN_MASK) >> 8) * f), p.BLUE_MASK) & p.GREEN_MASK | Math.max((c1 & p.BLUE_MASK) - (((c2 & p.BLUE_MASK) * f) >> 8), 0)); }, lightest: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | Math.max(c1 & p.RED_MASK, ((c2 & p.RED_MASK) >> 8) * f) & p.RED_MASK | Math.max(c1 & p.GREEN_MASK, ((c2 & p.GREEN_MASK) >> 8) * f) & p.GREEN_MASK | Math.max(c1 & p.BLUE_MASK, ((c2 & p.BLUE_MASK) * f) >> 8)); }, darkest: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | p.mix(c1 & p.RED_MASK, Math.min(c1 & p.RED_MASK, ((c2 & p.RED_MASK) >> 8) * f), f) & p.RED_MASK | p.mix(c1 & p.GREEN_MASK, Math.min(c1 & p.GREEN_MASK, ((c2 & p.GREEN_MASK) >> 8) * f), f) & p.GREEN_MASK | p.mix(c1 & p.BLUE_MASK, Math.min(c1 & p.BLUE_MASK, ((c2 & p.BLUE_MASK) * f) >> 8), f)); }, difference: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; var ar = (c1 & p.RED_MASK) >> 16; var ag = (c1 & p.GREEN_MASK) >> 8; var ab = (c1 & p.BLUE_MASK); var br = (c2 & p.RED_MASK) >> 16; var bg = (c2 & p.GREEN_MASK) >> 8; var bb = (c2 & p.BLUE_MASK); // formula: var cr = (ar > br) ? (ar - br) : (br - ar); var cg = (ag > bg) ? (ag - bg) : (bg - ag); var cb = (ab > bb) ? (ab - bb) : (bb - ab); // alpha blend (this portion will always be the same) return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (p.peg(ar + (((cr - ar) * f) >> 8)) << 16) | (p.peg(ag + (((cg - ag) * f) >> 8)) << 8) | (p.peg(ab + (((cb - ab) * f) >> 8)))); }, exclusion: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; var ar = (c1 & p.RED_MASK) >> 16; var ag = (c1 & p.GREEN_MASK) >> 8; var ab = (c1 & p.BLUE_MASK); var br = (c2 & p.RED_MASK) >> 16; var bg = (c2 & p.GREEN_MASK) >> 8; var bb = (c2 & p.BLUE_MASK); // formula: var cr = ar + br - ((ar * br) >> 7); var cg = ag + bg - ((ag * bg) >> 7); var cb = ab + bb - ((ab * bb) >> 7); // alpha blend (this portion will always be the same) return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (p.peg(ar + (((cr - ar) * f) >> 8)) << 16) | (p.peg(ag + (((cg - ag) * f) >> 8)) << 8) | (p.peg(ab + (((cb - ab) * f) >> 8)))); }, multiply: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; var ar = (c1 & p.RED_MASK) >> 16; var ag = (c1 & p.GREEN_MASK) >> 8; var ab = (c1 & p.BLUE_MASK); var br = (c2 & p.RED_MASK) >> 16; var bg = (c2 & p.GREEN_MASK) >> 8; var bb = (c2 & p.BLUE_MASK); // formula: var cr = (ar * br) >> 8; var cg = (ag * bg) >> 8; var cb = (ab * bb) >> 8; // alpha blend (this portion will always be the same) return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (p.peg(ar + (((cr - ar) * f) >> 8)) << 16) | (p.peg(ag + (((cg - ag) * f) >> 8)) << 8) | (p.peg(ab + (((cb - ab) * f) >> 8)))); }, screen: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; var ar = (c1 & p.RED_MASK) >> 16; var ag = (c1 & p.GREEN_MASK) >> 8; var ab = (c1 & p.BLUE_MASK); var br = (c2 & p.RED_MASK) >> 16; var bg = (c2 & p.GREEN_MASK) >> 8; var bb = (c2 & p.BLUE_MASK); // formula: var cr = 255 - (((255 - ar) * (255 - br)) >> 8); var cg = 255 - (((255 - ag) * (255 - bg)) >> 8); var cb = 255 - (((255 - ab) * (255 - bb)) >> 8); // alpha blend (this portion will always be the same) return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (p.peg(ar + (((cr - ar) * f) >> 8)) << 16) | (p.peg(ag + (((cg - ag) * f) >> 8)) << 8) | (p.peg(ab + (((cb - ab) * f) >> 8)))); }, hard_light: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; var ar = (c1 & p.RED_MASK) >> 16; var ag = (c1 & p.GREEN_MASK) >> 8; var ab = (c1 & p.BLUE_MASK); var br = (c2 & p.RED_MASK) >> 16; var bg = (c2 & p.GREEN_MASK) >> 8; var bb = (c2 & p.BLUE_MASK); // formula: var cr = (br < 128) ? ((ar * br) >> 7) : (255 - (((255 - ar) * (255 - br)) >> 7)); var cg = (bg < 128) ? ((ag * bg) >> 7) : (255 - (((255 - ag) * (255 - bg)) >> 7)); var cb = (bb < 128) ? ((ab * bb) >> 7) : (255 - (((255 - ab) * (255 - bb)) >> 7)); // alpha blend (this portion will always be the same) return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (p.peg(ar + (((cr - ar) * f) >> 8)) << 16) | (p.peg(ag + (((cg - ag) * f) >> 8)) << 8) | (p.peg(ab + (((cb - ab) * f) >> 8)))); }, soft_light: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; var ar = (c1 & p.RED_MASK) >> 16; var ag = (c1 & p.GREEN_MASK) >> 8; var ab = (c1 & p.BLUE_MASK); var br = (c2 & p.RED_MASK) >> 16; var bg = (c2 & p.GREEN_MASK) >> 8; var bb = (c2 & p.BLUE_MASK); // formula: var cr = ((ar * br) >> 7) + ((ar * ar) >> 8) - ((ar * ar * br) >> 15); var cg = ((ag * bg) >> 7) + ((ag * ag) >> 8) - ((ag * ag * bg) >> 15); var cb = ((ab * bb) >> 7) + ((ab * ab) >> 8) - ((ab * ab * bb) >> 15); // alpha blend (this portion will always be the same) return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (p.peg(ar + (((cr - ar) * f) >> 8)) << 16) | (p.peg(ag + (((cg - ag) * f) >> 8)) << 8) | (p.peg(ab + (((cb - ab) * f) >> 8)))); }, overlay: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; var ar = (c1 & p.RED_MASK) >> 16; var ag = (c1 & p.GREEN_MASK) >> 8; var ab = (c1 & p.BLUE_MASK); var br = (c2 & p.RED_MASK) >> 16; var bg = (c2 & p.GREEN_MASK) >> 8; var bb = (c2 & p.BLUE_MASK); // formula: var cr = (ar < 128) ? ((ar * br) >> 7) : (255 - (((255 - ar) * (255 - br)) >> 7)); var cg = (ag < 128) ? ((ag * bg) >> 7) : (255 - (((255 - ag) * (255 - bg)) >> 7)); var cb = (ab < 128) ? ((ab * bb) >> 7) : (255 - (((255 - ab) * (255 - bb)) >> 7)); // alpha blend (this portion will always be the same) return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (p.peg(ar + (((cr - ar) * f) >> 8)) << 16) | (p.peg(ag + (((cg - ag) * f) >> 8)) << 8) | (p.peg(ab + (((cb - ab) * f) >> 8)))); }, dodge: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; var ar = (c1 & p.RED_MASK) >> 16; var ag = (c1 & p.GREEN_MASK) >> 8; var ab = (c1 & p.BLUE_MASK); var br = (c2 & p.RED_MASK) >> 16; var bg = (c2 & p.GREEN_MASK) >> 8; var bb = (c2 & p.BLUE_MASK); // formula: var cr = (br === 255) ? 255 : p.peg((ar << 8) / (255 - br)); // division requires pre-peg()-ing var cg = (bg === 255) ? 255 : p.peg((ag << 8) / (255 - bg)); // " var cb = (bb === 255) ? 255 : p.peg((ab << 8) / (255 - bb)); // " // alpha blend (this portion will always be the same) return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (p.peg(ar + (((cr - ar) * f) >> 8)) << 16) | (p.peg(ag + (((cg - ag) * f) >> 8)) << 8) | (p.peg(ab + (((cb - ab) * f) >> 8)))); }, burn: function(c1, c2) { var f = (c2 & p.ALPHA_MASK) >>> 24; var ar = (c1 & p.RED_MASK) >> 16; var ag = (c1 & p.GREEN_MASK) >> 8; var ab = (c1 & p.BLUE_MASK); var br = (c2 & p.RED_MASK) >> 16; var bg = (c2 & p.GREEN_MASK) >> 8; var bb = (c2 & p.BLUE_MASK); // formula: var cr = (br === 0) ? 0 : 255 - p.peg(((255 - ar) << 8) / br); // division requires pre-peg()-ing var cg = (bg === 0) ? 0 : 255 - p.peg(((255 - ag) << 8) / bg); // " var cb = (bb === 0) ? 0 : 255 - p.peg(((255 - ab) << 8) / bb); // " // alpha blend (this portion will always be the same) return (Math.min(((c1 & p.ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (p.peg(ar + (((cr - ar) * f) >> 8)) << 16) | (p.peg(ag + (((cg - ag) * f) >> 8)) << 8) | (p.peg(ab + (((cb - ab) * f) >> 8)))); } }; p.color = function color(aValue1, aValue2, aValue3, aValue4) { var r, g, b, a, rgb, aColor; // 4 arguments: (R, G, B, A) or (H, S, B, A) if (aValue1 != null && aValue2 != null && aValue3 != null && aValue4 != null) { if (curColorMode === p.HSB) { rgb = p.color.toRGB(aValue1, aValue2, aValue3); r = rgb[0]; g = rgb[1]; b = rgb[2]; } else { r = Math.round(255 * (aValue1 / colorModeX)); g = Math.round(255 * (aValue2 / colorModeY)); b = Math.round(255 * (aValue3 / colorModeZ)); } a = Math.round(255 * (aValue4 / colorModeA)); // Limit values greater than 255 r = (r > 255) ? 255 : r; g = (g > 255) ? 255 : g; b = (b > 255) ? 255 : b; a = (a > 255) ? 255 : a; // Create color int aColor = (a << 24) & p.ALPHA_MASK | (r << 16) & p.RED_MASK | (g << 8) & p.GREEN_MASK | b & p.BLUE_MASK; } // 3 arguments: (R, G, B) or (H, S, B) else if (aValue1 != null && aValue2 != null && aValue3 != null) { aColor = p.color(aValue1, aValue2, aValue3, colorModeA); } // 2 arguments: (Color, A) or (Grayscale, A) else if (aValue1 != null && aValue2 != null) { // Color int and alpha if (aValue1 & p.ALPHA_MASK) { a = Math.round(255 * (aValue2 / colorModeA)); a = (a > 255) ? 255 : a; aColor = aValue1 - (aValue1 & p.ALPHA_MASK) + ((a << 24) & p.ALPHA_MASK); } // Grayscale and alpha else { switch(curColorMode) { case p.RGB: aColor = p.color(aValue1, aValue1, aValue1, aValue2); break; case p.HSB: aColor = p.color(0, 0, (aValue1 / colorModeX) * colorModeZ, aValue2); break; } } } // 1 argument: (Grayscale) or (Color) else if (typeof aValue1 === "number") { // Grayscale if (aValue1 <= colorModeX && aValue1 >= 0) { switch(curColorMode) { case p.RGB: aColor = p.color(aValue1, aValue1, aValue1, colorModeA); break; case p.HSB: aColor = p.color(0, 0, (aValue1 / colorModeX) * colorModeZ, colorModeA); break; } } // Color int else if (aValue1) { aColor = aValue1; } } // Default else { aColor = p.color(colorModeX, colorModeY, colorModeZ, colorModeA); } return aColor; }; // Ease of use function to extract the colour bits into a string p.color.toString = function(colorInt) { return "rgba(" + ((colorInt & p.RED_MASK) >>> 16) + "," + ((colorInt & p.GREEN_MASK) >>> 8) + "," + ((colorInt & p.BLUE_MASK)) + "," + ((colorInt & p.ALPHA_MASK) >>> 24) / 255 + ")"; }; // Easy of use function to pack rgba values into a single bit-shifted color int. p.color.toInt = function(r, g, b, a) { return (a << 24) & p.ALPHA_MASK | (r << 16) & p.RED_MASK | (g << 8) & p.GREEN_MASK | b & p.BLUE_MASK; }; // Creates a simple array in [R, G, B, A] format, [255, 255, 255, 255] p.color.toArray = function(colorInt) { return [(colorInt & p.RED_MASK) >>> 16, (colorInt & p.GREEN_MASK) >>> 8, colorInt & p.BLUE_MASK, (colorInt & p.ALPHA_MASK) >>> 24]; }; // Creates a WebGL color array in [R, G, B, A] format. WebGL wants the color ranges between 0 and 1, [1, 1, 1, 1] p.color.toGLArray = function(colorInt) { return [((colorInt & p.RED_MASK) >>> 16) / 255, ((colorInt & p.GREEN_MASK) >>> 8) / 255, (colorInt & p.BLUE_MASK) / 255, ((colorInt & p.ALPHA_MASK) >>> 24) / 255]; }; // HSB conversion function from Mootools, MIT Licensed p.color.toRGB = function(h, s, b) { // Limit values greater than range h = (h > colorModeX) ? colorModeX : h; s = (s > colorModeY) ? colorModeY : s; b = (b > colorModeZ) ? colorModeZ : b; h = (h / colorModeX) * 360; s = (s / colorModeY) * 100; b = (b / colorModeZ) * 100; var br = Math.round(b / 100 * 255); if (s === 0) { // Grayscale return [br, br, br]; } else { var hue = h % 360; var f = hue % 60; var p = Math.round((b * (100 - s)) / 10000 * 255); var q = Math.round((b * (6000 - s * f)) / 600000 * 255); var t = Math.round((b * (6000 - s * (60 - f))) / 600000 * 255); switch (Math.floor(hue / 60)) { case 0: return [br, t, p]; case 1: return [q, br, p]; case 2: return [p, br, t]; case 3: return [p, q, br]; case 4: return [t, p, br]; case 5: return [br, p, q]; } } }; p.color.toHSB = function( colorInt ) { var red, green, blue; red = ((colorInt & p.RED_MASK) >>> 16) / 255; green = ((colorInt & p.GREEN_MASK) >>> 8) / 255; blue = (colorInt & p.BLUE_MASK) / 255; var max = p.max(p.max(red,green), blue), min = p.min(p.min(red,green), blue), hue, saturation; if (min === max) { return [0, 0, max]; } else { saturation = (max - min) / max; if (red === max) { hue = (green - blue) / (max - min); } else if (green === max) { hue = 2 + ((blue - red) / (max - min)); } else { hue = 4 + ((red - green) / (max - min)); } hue /= 6; if (hue < 0) { hue += 1; } else if (hue > 1) { hue -= 1; } } return [hue*colorModeX, saturation*colorModeY, max*colorModeZ]; }; p.brightness = function(colInt){ return p.color.toHSB(colInt)[2]; }; p.saturation = function(colInt){ return p.color.toHSB(colInt)[1]; }; p.hue = function(colInt){ return p.color.toHSB(colInt)[0]; }; var verifyChannel = function verifyChannel(aColor) { if (aColor.constructor === Array) { return aColor; } else { return p.color(aColor); } }; p.red = function(aColor) { return ((aColor & p.RED_MASK) >>> 16) / 255 * colorModeX; }; p.green = function(aColor) { return ((aColor & p.GREEN_MASK) >>> 8) / 255 * colorModeY; }; p.blue = function(aColor) { return (aColor & p.BLUE_MASK) / 255 * colorModeZ; }; p.alpha = function(aColor) { return ((aColor & p.ALPHA_MASK) >>> 24) / 255 * colorModeA; }; p.lerpColor = function lerpColor(c1, c2, amt) { // Get RGBA values for Color 1 to floats var colorBits1 = p.color(c1); var r1 = (colorBits1 & p.RED_MASK) >>> 16; var g1 = (colorBits1 & p.GREEN_MASK) >>> 8; var b1 = (colorBits1 & p.BLUE_MASK); var a1 = ((colorBits1 & p.ALPHA_MASK) >>> 24) / colorModeA; // Get RGBA values for Color 2 to floats var colorBits2 = p.color(c2); var r2 = (colorBits2 & p.RED_MASK) >>> 16; var g2 = (colorBits2 & p.GREEN_MASK) >>> 8; var b2 = (colorBits2 & p.BLUE_MASK); var a2 = ((colorBits2 & p.ALPHA_MASK) >>> 24) / colorModeA; // Return lerp value for each channel, INT for color, Float for Alpha-range var r = parseInt(p.lerp(r1, r2, amt), 10); var g = parseInt(p.lerp(g1, g2, amt), 10); var b = parseInt(p.lerp(b1, b2, amt), 10); var a = parseFloat(p.lerp(a1, a2, amt) * colorModeA, 10); return p.color.toInt(r, g, b, a); }; // Forced default color mode for #aaaaaa style p.defaultColor = function(aValue1, aValue2, aValue3) { var tmpColorMode = curColorMode; curColorMode = p.RGB; var c = p.color(aValue1 / 255 * colorModeX, aValue2 / 255 * colorModeY, aValue3 / 255 * colorModeZ); curColorMode = tmpColorMode; return c; }; p.colorMode = function colorMode(mode, range1, range2, range3, range4) { curColorMode = mode; if (arguments.length >= 4) { colorModeX = range1; colorModeY = range2; colorModeZ = range3; } if (arguments.length === 5) { colorModeA = range4; } if (arguments.length === 2) { p.colorMode(mode, range1, range1, range1, range1); } }; p.blendColor = function(c1, c2, mode) { var color = 0; switch (mode) { case p.REPLACE: color = p.modes.replace(c1, c2); break; case p.BLEND: color = p.modes.blend(c1, c2); break; case p.ADD: color = p.modes.add(c1, c2); break; case p.SUBTRACT: color = p.modes.subtract(c1, c2); break; case p.LIGHTEST: color = p.modes.lightest(c1, c2); break; case p.DARKEST: color = p.modes.darkest(c1, c2); break; case p.DIFFERENCE: color = p.modes.difference(c1, c2); break; case p.EXCLUSION: color = p.modes.exclusion(c1, c2); break; case p.MULTIPLY: color = p.modes.multiply(c1, c2); break; case p.SCREEN: color = p.modes.screen(c1, c2); break; case p.HARD_LIGHT: color = p.modes.hard_light(c1, c2); break; case p.SOFT_LIGHT: color = p.modes.soft_light(c1, c2); break; case p.OVERLAY: color = p.modes.overlay(c1, c2); break; case p.DODGE: color = p.modes.dodge(c1, c2); break; case p.BURN: color = p.modes.burn(c1, c2); break; } return color; }; //////////////////////////////////////////////////////////////////////////// // Canvas-Matrix manipulation //////////////////////////////////////////////////////////////////////////// p.printMatrix = function printMatrix() { modelView.print(); }; p.translate = function translate(x, y, z) { if (p.use3DContext) { forwardTransform.translate(x, y, z); reverseTransform.invTranslate(x, y, z); } else { curContext.translate(x, y); } }; p.scale = function scale(x, y, z) { if (p.use3DContext) { forwardTransform.scale(x, y, z); reverseTransform.invScale(x, y, z); } else { curContext.scale(x, y || x); } }; p.pushMatrix = function pushMatrix() { if (p.use3DContext) { userMatrixStack.load(modelView); } else { curContext.save(); } }; p.popMatrix = function popMatrix() { if (p.use3DContext) { modelView.set(userMatrixStack.pop()); } else { curContext.restore(); } }; p.resetMatrix = function resetMatrix() { forwardTransform.reset(); reverseTransform.reset(); }; p.applyMatrix = function applyMatrix() { var a = arguments; if (!p.use3DContext) { for (var cnt = a.length; cnt < 16; cnt++) { a[cnt] = 0; } a[10] = a[15] = 1; } forwardTransform.apply(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]); reverseTransform.invApply(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]); }; p.rotateX = function(angleInRadians) { forwardTransform.rotateX(angleInRadians); reverseTransform.invRotateX(angleInRadians); }; p.rotateZ = function(angleInRadians) { forwardTransform.rotateZ(angleInRadians); reverseTransform.invRotateZ(angleInRadians); }; p.rotateY = function(angleInRadians) { forwardTransform.rotateY(angleInRadians); reverseTransform.invRotateY(angleInRadians); }; p.rotate = function rotate(angleInRadians) { if (p.use3DContext) { forwardTransform.rotateZ(angleInRadians); reverseTransform.invRotateZ(angleInRadians); } else { curContext.rotate(angleInRadians); } }; p.pushStyle = function pushStyle() { // Save the canvas state. curContext.save(); p.pushMatrix(); var newState = { 'doFill': doFill, 'doStroke': doStroke, 'curTint': curTint, 'curRectMode': curRectMode, 'curColorMode': curColorMode, 'colorModeX': colorModeX, 'colorModeZ': colorModeZ, 'colorModeY': colorModeY, 'colorModeA': colorModeA, 'curTextFont': curTextFont, 'curTextSize': curTextSize }; styleArray.push(newState); }; p.popStyle = function popStyle() { var oldState = styleArray.pop(); if (oldState) { curContext.restore(); p.popMatrix(); doFill = oldState.doFill; doStroke = oldState.doStroke; curTint = oldState.curTint; curRectMode = oldState.curRectmode; curColorMode = oldState.curColorMode; colorModeX = oldState.colorModeX; colorModeZ = oldState.colorModeZ; colorModeY = oldState.colorModeY; colorModeA = oldState.colorModeA; curTextFont = oldState.curTextFont; curTextSize = oldState.curTextSize; } else { throw "Too many popStyle() without enough pushStyle()"; } }; //////////////////////////////////////////////////////////////////////////// // Time based functions //////////////////////////////////////////////////////////////////////////// p.year = function year() { return new Date().getFullYear(); }; p.month = function month() { return new Date().getMonth() + 1; }; p.day = function day() { return new Date().getDate(); }; p.hour = function hour() { return new Date().getHours(); }; p.minute = function minute() { return new Date().getMinutes(); }; p.second = function second() { return new Date().getSeconds(); }; p.millis = function millis() { return new Date().getTime() - start; }; p.noLoop = function noLoop() { doLoop = false; loopStarted = false; clearInterval(looping); }; p.redraw = function redraw() { var sec = (new Date().getTime() - timeSinceLastFPS) / 1000; framesSinceLastFPS++; var fps = framesSinceLastFPS / sec; // recalculate FPS every half second for better accuracy. if (sec > 0.5) { timeSinceLastFPS = new Date().getTime(); framesSinceLastFPS = 0; p.FRAME_RATE = fps; } p.frameCount++; inDraw = true; if (p.use3DContext) { // Delete all the lighting states and the materials the // user set in the last draw() call. p.noLights(); p.lightFalloff(1, 0, 0); p.shininess(1); p.ambient(255, 255, 255); p.specular(0, 0, 0); p.camera(); p.draw(); } else { curContext.save(); p.draw(); curContext.restore(); } inDraw = false; }; p.loop = function loop() { if (loopStarted) { return; } looping = window.setInterval(function() { try { try { p.focused = document.hasFocus(); } catch(e) {} p.redraw(); } catch(e_loop) { window.clearInterval(looping); throw e_loop; } }, curMsPerFrame); doLoop = true; loopStarted = true; }; p.frameRate = function frameRate(aRate) { curFrameRate = aRate; curMsPerFrame = 1000 / curFrameRate; }; p.exit = function exit() { window.clearInterval(looping); for (var i=0, ehl=p.pjs.eventHandlers.length; i<ehl; i++) { var elem = p.pjs.eventHandlers[i][0], type = p.pjs.eventHandlers[i][1], fn = p.pjs.eventHandlers[i][2]; if (elem.removeEventListener) { elem.removeEventListener(type, fn, false); } else if (elem.detachEvent) { elem.detachEvent("on" + type, fn); } } }; //////////////////////////////////////////////////////////////////////////// // MISC functions //////////////////////////////////////////////////////////////////////////// p.cursor = function cursor() { if (arguments.length > 1 || (arguments.length === 1 && arguments[0] instanceof p.PImage)) { var image = arguments[0], x, y; if (arguments.length >= 3) { x = arguments[1]; y = arguments[2]; if (x < 0 || y < 0 || y >= image.height || x >= image.width) { throw "x and y must be non-negative and less than the dimensions of the image"; } } else { x = image.width >>> 1; y = image.height >>> 1; } // see https://developer.mozilla.org/en/Using_URL_values_for_the_cursor_property var imageDataURL = image.toDataURL(); var style = "url(\"" + imageDataURL + "\") " + x + " " + y + ", default"; curCursor = curElement.style.cursor = style; } else if (arguments.length === 1) { var mode = arguments[0]; curCursor = curElement.style.cursor = mode; } else { curCursor = curElement.style.cursor = oldCursor; } }; p.noCursor = function noCursor() { curCursor = curElement.style.cursor = p.NOCURSOR; }; p.link = function(href, target) { if (typeof target !== 'undefined') { window.open(href, target); } else { window.location = href; } }; // PGraphics methods // TODO: These functions are suppose to be called before any operations are called on the // PGraphics object. They currently do nothing. p.beginDraw = function beginDraw() {}; p.endDraw = function endDraw() {}; // Imports an external Processing.js library p.Import = function Import(lib) { // Replace evil-eval method with a DOM <script> tag insert method that // binds new lib code to the Processing.lib names-space and the current // p context. -F1LT3R }; var contextMenu = function(e) { e.preventDefault(); e.stopPropagation(); }; p.disableContextMenu = function disableContextMenu() { curElement.addEventListener('contextmenu', contextMenu, false); }; p.enableContextMenu = function enableContextMenu() { curElement.removeEventListener('contextmenu', contextMenu, false); }; //////////////////////////////////////////////////////////////////////////// // Binary Functions //////////////////////////////////////////////////////////////////////////// function decToBin(value, numBitsInValue) { var mask = 1; mask = mask << (numBitsInValue - 1); var str = ""; for (var i = 0; i < numBitsInValue; i++) { str += (mask & value) ? "1" : "0"; mask = mask >>> 1; } return str; } p.binary = function(num, numBits) { var numBitsInValue = 32; // color if (typeof num === "string" && num.length > 1) { var c = num.slice(5, -1).split(","); // if all components are zero, a single "0" is returned for some reason // [0] alpha is normalized, [1] r, [2] g, [3] b var sbin = [ decToBin(c[3] * 255, 8), decToBin(c[0], 8), decToBin(c[1], 8), decToBin(c[2], 8) ]; var s = sbin[0] + sbin[1] + sbin[2] + sbin[3]; if (numBits) { s = s.substr(-numBits); } // if the user didn't specify number of bits, // trim leading zeros. else { s = s.replace(/^0+$/g, "0"); s = s.replace(/^0{1,}1/g, "1"); } return s; } // char if (typeof num === "string" || num instanceof Char) { if (num instanceof Char) { num = num.toString().charCodeAt(0); } else { num = num.charCodeAt(0); } if (numBits) { numBitsInValue = 32; } else { numBitsInValue = 16; } } var str = decToBin(num, numBitsInValue); // trim string if user wanted less chars if (numBits) { str = str.substr(-numBits); } return str; }; p.unbinary = function unbinary(binaryString) { var binaryPattern = new RegExp("^[0|1]{8}$"); var addUp = 0; if (isNaN(binaryString)) { throw "NaN_Err"; } else { if (arguments.length === 1 || binaryString.length === 8) { if (binaryPattern.test(binaryString)) { for (var i = 0; i < 8; i++) { addUp += (Math.pow(2, i) * parseInt(binaryString.charAt(7 - i), 10)); } return addUp + ""; } else { throw "notBinary: the value passed into unbinary was not an 8 bit binary number"; } } else { throw "longErr"; } } }; p.nfs = function(num, left, right) { var str, len, formatLength, rounded; // array handling if (typeof num === "object" && num.constructor === Array) { str = new Array(0); len = num.length; for (var i = 0; i < len; i++) { str[i] = p.nfs(num[i], left, right); } } else if (arguments.length === 3) { var negative = num < 0 ? true : false; // Make it work exactly like p5 for right = 0 if (right === 0) { right = 1; } if (right < 0) { rounded = Math.round(num); } else { // round to 'right' decimal places rounded = Math.round(num * Math.pow(10, right)) / Math.pow(10, right); } // split number into whole and fractional components var splitNum = Math.abs(rounded).toString().split("."); // [0] whole number, [1] fractional number // format whole part formatLength = left - splitNum[0].length; for (; formatLength > 0; formatLength--) { splitNum[0] = "0" + splitNum[0]; } // format fractional part if (splitNum.length === 2 || right > 0) { splitNum[1] = splitNum.length === 2 ? splitNum[1] : ""; formatLength = right - splitNum[1].length; for (; formatLength > 0; formatLength--) { splitNum[1] += "0"; } str = splitNum.join("."); } else { str = splitNum[0]; } str = (negative ? "-" : " ") + str; } else if (arguments.length === 2) { str = p.nfs(num, left, -1); } return str; }; p.nfp = function(num, left, right) { var str, len, formatLength, rounded; // array handling if (typeof num === "object" && num.constructor === Array) { str = new Array(0); len = num.length; for (var i = 0; i < len; i++) { str[i] = p.nfp(num[i], left, right); } } else if (arguments.length === 3) { var negative = num < 0 ? true : false; // Make it work exactly like p5 for right = 0 if (right === 0) { right = 1; } if (right < 0) { rounded = Math.round(num); } else { // round to 'right' decimal places rounded = Math.round(num * Math.pow(10, right)) / Math.pow(10, right); } // split number into whole and fractional components var splitNum = Math.abs(rounded).toString().split("."); // [0] whole number, [1] fractional number // format whole part formatLength = left - splitNum[0].length; for (; formatLength > 0; formatLength--) { splitNum[0] = "0" + splitNum[0]; } // format fractional part if (splitNum.length === 2 || right > 0) { splitNum[1] = splitNum.length === 2 ? splitNum[1] : ""; formatLength = right - splitNum[1].length; for (; formatLength > 0; formatLength--) { splitNum[1] += "0"; } str = splitNum.join("."); } else { str = splitNum[0]; } str = (negative ? "-" : "+") + str; } else if (arguments.length === 2) { str = p.nfp(num, left, -1); } return str; }; p.nfc = function(num, right) { var str; var decimals = right >= 0 ? right : 0; if (typeof num === "object") { str = new Array(0); for (var i = 0; i < num.length; i++) { str[i] = p.nfc(num[i], decimals); } } else if (arguments.length === 2) { var rawStr = p.nfs(num, 0, decimals); var ary = new Array(0); ary = rawStr.split('.'); // ary[0] contains left of decimal, ary[1] contains decimal places if they exist // insert commas now, then append ary[1] if it exists var leftStr = ary[0]; var rightStr = ary.length > 1 ? '.' + ary[1] : ''; var commas = /(\d+)(\d{3})/; while (commas.test(leftStr)) { leftStr = leftStr.replace(commas, '$1' + ',' + '$2'); } str = leftStr + rightStr; } else if (arguments.length === 1) { str = p.nfc(num, 0); } return str; }; var decimalToHex = function decimalToHex(d, padding) { //if there is no padding value added, default padding to 8 else go into while statement. padding = typeof(padding) === "undefined" || padding === null ? padding = 8 : padding; if (d < 0) { d = 0xFFFFFFFF + d + 1; } var hex = Number(d).toString(16).toUpperCase(); while (hex.length < padding) { hex = "0" + hex; } if (hex.length >= padding) { hex = hex.substring(hex.length - padding, hex.length); } return hex; }; // note: since we cannot keep track of byte, int types by default the returned string is 8 chars long // if no 2nd argument is passed. closest compromise we can use to match java implementation Feb 5 2010 // also the char parser has issues with chars that are not digits or letters IE: !@#$%^&* p.hex = function hex(value, len) { var hexstring = ""; if (arguments.length === 1) { if (value instanceof Char) { hexstring = hex(value, 4); } else { // int or byte, indistinguishable at the moment, default to 8 hexstring = hex(value, 8); } } else { // pad to specified length hexstring = decimalToHex(value, len); } return hexstring; }; p.unhex = function(str) { var value = 0, multiplier = 1, num = 0; var len = str.length - 1; for (var i = len; i >= 0; i--) { try { switch (str[i]) { case "0": num = 0; break; case "1": num = 1; break; case "2": num = 2; break; case "3": num = 3; break; case "4": num = 4; break; case "5": num = 5; break; case "6": num = 6; break; case "7": num = 7; break; case "8": num = 8; break; case "9": num = 9; break; case "A": case "a": num = 10; break; case "B": case "b": num = 11; break; case "C": case "c": num = 12; break; case "D": case "d": num = 13; break; case "E": case "e": num = 14; break; case "F": case "f": num = 15; break; default: return 0; } value += num * multiplier; multiplier *= 16; } catch(e) { Processing.debug(e); } // correct for int overflow java expectation if (value > 2147483647) { value -= 4294967296; } } return value; }; // Load a file or URL into strings p.loadStrings = function loadStrings(url) { return ajax(url).split("\n"); }; p.loadBytes = function loadBytes(url) { var string = ajax(url); var ret = new Array(string.length); for (var i = 0; i < string.length; i++) { ret[i] = string.charCodeAt(i); } return ret; }; // nf() should return an array when being called on an array, at the moment it only returns strings. -F1LT3R // This breaks the join() ref-test. The Processing.org documentation says String or String[]. SHOULD BE FIXED NOW p.nf = function() { var str, num, pad, arr, left, right, isNegative, test, i; if (arguments.length === 2 && typeof arguments[0] === 'number' && typeof arguments[1] === 'number' && (arguments[0] + "").indexOf('.') === -1) { num = arguments[0]; pad = arguments[1]; isNegative = num < 0; if (isNegative) { num = Math.abs(num); } str = "" + num; for (i = pad - str.length; i > 0; i--) { str = "0" + str; } if (isNegative) { str = "-" + str; } } else if (arguments.length === 2 && typeof arguments[0] === 'object' && arguments[0].constructor === Array && typeof arguments[1] === 'number') { arr = arguments[0]; pad = arguments[1]; str = new Array(arr.length); for (i = 0; i < arr.length && str !== undefined; i++) { test = p.nf(arr[i], pad); if (test === undefined) { str = undefined; } else { str[i] = test; } } } else if (arguments.length === 3 && typeof arguments[0] === 'number' && typeof arguments[1] === 'number' && typeof arguments[2] === 'number' && (arguments[0] + "").indexOf('.') >= 0) { num = arguments[0]; left = arguments[1]; right = arguments[2]; isNegative = num < 0; if (isNegative) { num = Math.abs(num); } // Change the way the number is 'floored' based on whether it is odd or even. if (right < 0 && Math.floor(num) % 2 === 1) { // Make sure 1.49 rounds to 1, but 1.5 rounds to 2. if ((num) - Math.floor(num) >= 0.5) { num = num + 1; } } str = "" + num; for (i = left - str.indexOf('.'); i > 0; i--) { str = "0" + str; } var numDec = str.length - str.indexOf('.') - 1; if (numDec <= right) { for (i = right - (str.length - str.indexOf('.') - 1); i > 0; i--) { str = str + "0"; } } else if (right > 0) { str = str.substring(0, str.length - (numDec - right)); } else if (right < 0) { str = str.substring(0, str.indexOf('.')); } if (isNegative) { str = "-" + str; } } else if (arguments.length === 3 && typeof arguments[0] === 'object' && arguments[0].constructor === Array && typeof arguments[1] === 'number' && typeof arguments[2] === 'number') { arr = arguments[0]; left = arguments[1]; right = arguments[2]; str = new Array(arr.length); for (i = 0; i < arr.length && str !== undefined; i++) { test = p.nf(arr[i], left, right); if (test === undefined) { str = undefined; } else { str[i] = test; } } } return str; }; //////////////////////////////////////////////////////////////////////////// // String Functions //////////////////////////////////////////////////////////////////////////// p.matchAll = function matchAll(aString, aRegExp) { var results = [], latest; var regexp = new RegExp(aRegExp, "g"); while ((latest = regexp.exec(aString)) !== null) { results.push(latest); if (latest[0].length === 0) { ++regexp.lastIndex; } } return results.length > 0 ? results : null; }; String.prototype.replaceAll = function(re, replace) { return this.replace(new RegExp(re, "g"), replace); }; String.prototype.equals = function equals(str) { return this.valueOf() === str.valueOf(); }; String.prototype.toCharArray = function() { var chars = this.split(""); for (var i = chars.length - 1; i >= 0; i--) { chars[i] = new Char(chars[i]); } return chars; }; p.match = function(str, regexp) { return str.match(regexp); }; // tinylog lite JavaScript library /*global tinylog,print*/ var tinylogLite = (function() { "use strict"; var tinylogLite = {}, undef = "undefined", func = "function", False = !1, True = !0, log = "log"; if (typeof tinylog !== undef && typeof tinylog[log] === func) { // pre-existing tinylog present tinylogLite[log] = tinylog[log]; } else if (typeof document !== undef && !document.fake) { (function() { // DOM document var doc = document, $div = "div", $style = "style", $title = "title", containerStyles = { zIndex: 10000, position: "fixed", bottom: "0px", width: "100%", height: "15%", fontFamily: "sans-serif", color: "#ccc", backgroundColor: "black" }, outputStyles = { position: "relative", fontFamily: "monospace", overflow: "auto", height: "100%", paddingTop: "5px" }, resizerStyles = { height: "5px", marginTop: "-5px", cursor: "n-resize", backgroundColor: "darkgrey" }, closeButtonStyles = { position: "absolute", top: "5px", right: "20px", color: "#111", MozBorderRadius: "4px", webkitBorderRadius: "4px", borderRadius: "4px", cursor: "pointer", fontWeight: "normal", textAlign: "center", padding: "3px 5px", backgroundColor: "#333", fontSize: "12px" }, entryStyles = { //borderBottom: "1px solid #d3d3d3", minHeight: "16px" }, entryTextStyles = { fontSize: "12px", margin: "0 8px 0 8px", maxWidth: "100%", whiteSpace: "pre-wrap", overflow: "auto" }, view = doc.defaultView, docElem = doc.documentElement, docElemStyle = docElem[$style], setStyles = function() { var i = arguments.length, elemStyle, styles, style; while (i--) { styles = arguments[i--]; elemStyle = arguments[i][$style]; for (style in styles) { if (styles.hasOwnProperty(style)) { elemStyle[style] = styles[style]; } } } }, observer = function(obj, event, handler) { if (obj.addEventListener) { obj.addEventListener(event, handler, False); } else if (obj.attachEvent) { obj.attachEvent("on" + event, handler); } return [obj, event, handler]; }, unobserve = function(obj, event, handler) { if (obj.removeEventListener) { obj.removeEventListener(event, handler, False); } else if (obj.detachEvent) { obj.detachEvent("on" + event, handler); } }, clearChildren = function(node) { var children = node.childNodes, child = children.length; while (child--) { node.removeChild(children.item(0)); } }, append = function(to, elem) { return to.appendChild(elem); }, createElement = function(localName) { return doc.createElement(localName); }, createTextNode = function(text) { return doc.createTextNode(text); }, createLog = tinylogLite[log] = function(message) { // don't show output log until called once var uninit, originalPadding = docElemStyle.paddingBottom, container = createElement($div), containerStyle = container[$style], resizer = append(container, createElement($div)), output = append(container, createElement($div)), closeButton = append(container, createElement($div)), resizingLog = False, previousHeight = False, previousScrollTop = False, updateSafetyMargin = function() { // have a blank space large enough to fit the output box at the page bottom docElemStyle.paddingBottom = container.clientHeight + "px"; }, setContainerHeight = function(height) { var viewHeight = view.innerHeight, resizerHeight = resizer.clientHeight; // constrain the container inside the viewport's dimensions if (height < 0) { height = 0; } else if (height + resizerHeight > viewHeight) { height = viewHeight - resizerHeight; } containerStyle.height = height / viewHeight * 100 + "%"; updateSafetyMargin(); }, observers = [ observer(doc, "mousemove", function(evt) { if (resizingLog) { setContainerHeight(view.innerHeight - evt.clientY); output.scrollTop = previousScrollTop; } }), observer(doc, "mouseup", function() { if (resizingLog) { resizingLog = previousScrollTop = False; } }), observer(resizer, "dblclick", function(evt) { evt.preventDefault(); if (previousHeight) { setContainerHeight(previousHeight); previousHeight = False; } else { previousHeight = container.clientHeight; containerStyle.height = "0px"; } }), observer(resizer, "mousedown", function(evt) { evt.preventDefault(); resizingLog = True; previousScrollTop = output.scrollTop; }), observer(resizer, "contextmenu", function() { resizingLog = False; }), observer(closeButton, "click", function() { uninit(); }) ]; uninit = function() { // remove observers var i = observers.length; while (i--) { unobserve.apply(tinylogLite, observers[i]); } // remove tinylog lite from the DOM docElem.removeChild(container); docElemStyle.paddingBottom = originalPadding; clearChildren(output); clearChildren(container); tinylogLite[log] = createLog; }; setStyles( container, containerStyles, output, outputStyles, resizer, resizerStyles, closeButton, closeButtonStyles); closeButton[$title] = "Close Log"; append(closeButton, createTextNode("\u2716")); resizer[$title] = "Double-click to toggle log minimization"; docElem.insertBefore(container, docElem.firstChild); tinylogLite[log] = function(message) { var entry = append(output, createElement($div)), entryText = append(entry, createElement($div)); entry[$title] = (new Date()).toLocaleTimeString(); setStyles( entry, entryStyles, entryText, entryTextStyles); append(entryText, createTextNode(message)); output.scrollTop = output.scrollHeight; }; tinylogLite[log](message); }; }()); } else if (typeof print === func) { // JS shell tinylogLite[log] = print; } return tinylogLite; }()), logBuffer = []; p.console = window.console || tinylogLite; p.println = function println(message) { var bufferLen = logBuffer.length; if (bufferLen) { tinylogLite.log(logBuffer.join("")); logBuffer.length = 0; // clear log buffer } if (arguments.length === 0 && bufferLen === 0) { tinylogLite.log(""); } else if (arguments.length !== 0) { tinylogLite.log(message); } }; p.print = function print(message) { logBuffer.push(message); }; // Alphanumeric chars arguments automatically converted to numbers when // passed in, and will come out as numbers. p.str = function str(val) { var ret; if (arguments.length === 1) { if (typeof val === "string" && val.length === 1) { // No strings allowed. ret = val; } else if (typeof val === "object" && val.constructor === Array) { ret = new Array(0); for (var i = 0; i < val.length; i++) { ret[i] = str(val[i]); } } else { ret = val + ""; } } return ret; }; p.trim = function(str) { var newstr; if (typeof str === "object" && str.constructor === Array) { newstr = new Array(0); for (var i = 0; i < str.length; i++) { newstr[i] = p.trim(str[i]); } } else { // if str is not an array then remove all whitespace, tabs, and returns newstr = str.replace(/^\s*/, '').replace(/\s*$/, '').replace(/\r*$/, ''); } return newstr; }; // Conversion p['boolean'] = function(val) { if (typeof val === 'number') { return val !== 0; } else if (typeof val === 'boolean') { return val; } else if (typeof val === 'string') { return val.toLowerCase() === 'true'; } else if (val instanceof Char) { // 1, T or t return val.code === 49 || val.code === 84 || val.code === 116; } else if (typeof val === 'object' && val.constructor === Array) { var ret = new Array(val.length); for (var i = 0; i < val.length; i++) { ret[i] = p['boolean'](val[i]); } return ret; } }; // a byte is a number between -128 and 127 p['byte'] = function(aNumber) { if (typeof aNumber === 'object' && aNumber.constructor === Array) { var bytes = []; for (var i = 0; i < aNumber.length; i++) { bytes[i] = p['byte'](aNumber[i]); } return bytes; } else { return (0 - (aNumber & 0x80)) | (aNumber & 0x7F); } }; p['char'] = function(key) { if (arguments.length === 1 && typeof key === "number") { return new Char(String.fromCharCode(key & 0xFFFF)); } else if (arguments.length === 1 && typeof key === "object" && key.constructor === Array) { var ret = new Array(key.length); for (var i = 0; i < key.length; i++) { ret[i] = p['char'](key[i]); } return ret; } else { throw "char() may receive only one argument of type int, byte, int[], or byte[]."; } }; // Processing doc claims good argument types are: int, char, byte, boolean, // String, int[], char[], byte[], boolean[], String[]. // floats should not work. However, floats with only zeroes right of the // decimal will work because JS converts those to int. p['float'] = function(val) { if (arguments.length === 1) { if (typeof val === 'number') { return val; } else if (typeof val === 'boolean') { return val ? 1 : 0; } else if (typeof val === 'string') { return parseFloat(val); } else if (val instanceof Char) { return val.code; } else if (typeof val === 'object' && val.constructor === Array) { var ret = new Array(val.length); for (var i = 0; i < val.length; i++) { ret[i] = p['float'](val[i]); } return ret; } } }; p['int'] = function(val) { if (typeof val === 'number') { return val & 0xFFFFFFFF; } else if (typeof val === 'boolean') { return val ? 1 : 0; } else if (typeof val === 'string') { var number = parseInt(val, 10); // Force decimal radix. Don't convert hex or octal (just like p5) return number & 0xFFFFFFFF; } else if (val instanceof Char) { return val.code; } else if (typeof val === 'object' && val.constructor === Array) { var ret = new Array(val.length); for (var i = 0; i < val.length; i++) { if (typeof val[i] === 'string' && !/^\s*[+\-]?\d+\s*$/.test(val[i])) { ret[i] = 0; } else { ret[i] = p['int'](val[i]); } } return ret; } }; //////////////////////////////////////////////////////////////////////////// // Math functions //////////////////////////////////////////////////////////////////////////// // Calculation p.abs = Math.abs; p.ceil = Math.ceil; p.constrain = function(aNumber, aMin, aMax) { return aNumber > aMax ? aMax : aNumber < aMin ? aMin : aNumber; }; p.dist = function() { var dx, dy, dz; if (arguments.length === 4) { dx = arguments[0] - arguments[2]; dy = arguments[1] - arguments[3]; return Math.sqrt(dx * dx + dy * dy); } else if (arguments.length === 6) { dx = arguments[0] - arguments[3]; dy = arguments[1] - arguments[4]; dz = arguments[2] - arguments[5]; return Math.sqrt(dx * dx + dy * dy + dz * dz); } }; p.exp = Math.exp; p.floor = Math.floor; p.lerp = function(value1, value2, amt) { return ((value2 - value1) * amt) + value1; }; p.log = Math.log; p.mag = function(a, b, c) { if (arguments.length === 2) { return Math.sqrt(a * a + b * b); } else if (arguments.length === 3) { return Math.sqrt(a * a + b * b + c * c); } }; p.map = function(value, istart, istop, ostart, ostop) { return ostart + (ostop - ostart) * ((value - istart) / (istop - istart)); }; p.max = function() { if (arguments.length === 2) { return arguments[0] < arguments[1] ? arguments[1] : arguments[0]; } else { var numbers = arguments.length === 1 ? arguments[0] : arguments; // if single argument, array is used if (! ("length" in numbers && numbers.length > 0)) { throw "Non-empty array is expected"; } var max = numbers[0], count = numbers.length; for (var i = 1; i < count; ++i) { if (max < numbers[i]) { max = numbers[i]; } } return max; } }; p.min = function() { if (arguments.length === 2) { return arguments[0] < arguments[1] ? arguments[0] : arguments[1]; } else { var numbers = arguments.length === 1 ? arguments[0] : arguments; // if single argument, array is used if (! ("length" in numbers && numbers.length > 0)) { throw "Non-empty array is expected"; } var min = numbers[0], count = numbers.length; for (var i = 1; i < count; ++i) { if (min > numbers[i]) { min = numbers[i]; } } return min; } }; p.norm = function(aNumber, low, high) { return (aNumber - low) / (high - low); }; p.pow = Math.pow; p.round = Math.round; p.sq = function(aNumber) { return aNumber * aNumber; }; p.sqrt = Math.sqrt; // Trigonometry p.acos = Math.acos; p.asin = Math.asin; p.atan = Math.atan; p.atan2 = Math.atan2; p.cos = Math.cos; p.degrees = function(aAngle) { return (aAngle * 180) / Math.PI; }; p.radians = function(aAngle) { return (aAngle / 180) * Math.PI; }; p.sin = Math.sin; p.tan = Math.tan; var currentRandom = Math.random; p.random = function random() { if(arguments.length === 0) { return currentRandom(); } else if(arguments.length === 1) { return currentRandom() * arguments[0]; } else { var aMin = arguments[0], aMax = arguments[1]; return currentRandom() * (aMax - aMin) + aMin; } }; // Pseudo-random generator function Marsaglia(i1, i2) { // from http://www.math.uni-bielefeld.de/~sillke/ALGORITHMS/random/marsaglia-c var z=i1 || 362436069, w= i2 || 521288629; var nextInt = function() { z=(36969*(z&65535)+(z>>>16)) & 0xFFFFFFFF; w=(18000*(w&65535)+(w>>>16)) & 0xFFFFFFFF; return (((z&0xFFFF)<<16) | (w&0xFFFF)) & 0xFFFFFFFF; }; this.nextDouble = function() { var i = nextInt() / 4294967296; return i < 0 ? 1 + i : i; }; this.nextInt = nextInt; } Marsaglia.createRandomized = function() { var now = new Date(); return new Marsaglia((now / 60000) & 0xFFFFFFFF, now & 0xFFFFFFFF); }; p.randomSeed = function(seed) { currentRandom = (new Marsaglia(seed)).nextDouble; }; // Random p.Random = function(seed) { var haveNextNextGaussian = false, nextNextGaussian, random; this.nextGaussian = function() { if (haveNextNextGaussian) { haveNextNextGaussian = false; return nextNextGaussian; } else { var v1, v2, s; do { v1 = 2 * random() - 1; // between -1.0 and 1.0 v2 = 2 * random() - 1; // between -1.0 and 1.0 s = v1 * v1 + v2 * v2; } while (s >= 1 || s === 0); var multiplier = Math.sqrt(-2 * Math.log(s) / s); nextNextGaussian = v2 * multiplier; haveNextNextGaussian = true; return v1 * multiplier; } }; // by default use standard random, otherwise seeded random = seed === undefined ? Math.random : (new Marsaglia(seed)).nextDouble; }; // Noise functions and helpers function PerlinNoise(seed) { var rnd = seed !== undefined ? new Marsaglia(seed) : Marsaglia.createRandomized(); var i, j; // http://www.noisemachine.com/talk1/17b.html // http://mrl.nyu.edu/~perlin/noise/ // generate permutation var p = new Array(512); for(i=0;i<256;++i) { p[i] = i; } for(i=0;i<256;++i) { var t = p[j = rnd.nextInt() & 0xFF]; p[j] = p[i]; p[i] = t; } // copy to avoid taking mod in p[0]; for(i=0;i<256;++i) { p[i + 256] = p[i]; } function grad3d(i,x,y,z) { var h = i & 15; // convert into 12 gradient directions var u = h<8 ? x : y, v = h<4 ? y : h===12||h===14 ? x : z; return ((h&1) === 0 ? u : -u) + ((h&2) === 0 ? v : -v); } function grad2d(i,x,y) { var v = (i & 1) === 0 ? x : y; return (i&2) === 0 ? -v : v; } function grad1d(i,x) { return (i&1) === 0 ? -x : x; } function lerp(t,a,b) { return a + t * (b - a); } this.noise3d = function(x, y, z) { var X = Math.floor(x)&255, Y = Math.floor(y)&255, Z = Math.floor(z)&255; x -= Math.floor(x); y -= Math.floor(y); z -= Math.floor(z); var fx = (3-2*x)*x*x, fy = (3-2*y)*y*y, fz = (3-2*z)*z*z; var p0 = p[X]+Y, p00 = p[p0] + Z, p01 = p[p0 + 1] + Z, p1 = p[X + 1] + Y, p10 = p[p1] + Z, p11 = p[p1 + 1] + Z; return lerp(fz, lerp(fy, lerp(fx, grad3d(p[p00], x, y, z), grad3d(p[p10], x-1, y, z)), lerp(fx, grad3d(p[p01], x, y-1, z), grad3d(p[p11], x-1, y-1,z))), lerp(fy, lerp(fx, grad3d(p[p00 + 1], x, y, z-1), grad3d(p[p10 + 1], x-1, y, z-1)), lerp(fx, grad3d(p[p01 + 1], x, y-1, z-1), grad3d(p[p11 + 1], x-1, y-1,z-1)))); }; this.noise2d = function(x, y) { var X = Math.floor(x)&255, Y = Math.floor(y)&255; x -= Math.floor(x); y -= Math.floor(y); var fx = (3-2*x)*x*x, fy = (3-2*y)*y*y; var p0 = p[X]+Y, p1 = p[X + 1] + Y; return lerp(fy, lerp(fx, grad2d(p[p0], x, y), grad2d(p[p1], x-1, y)), lerp(fx, grad2d(p[p0 + 1], x, y-1), grad2d(p[p1 + 1], x-1, y-1))); }; this.noise1d = function(x) { var X = Math.floor(x)&255; x -= Math.floor(x); var fx = (3-2*x)*x*x; return lerp(fx, grad1d(p[X], x), grad1d(p[X+1], x-1)); }; } // processing defaults var noiseProfile = { generator: undefined, octaves: 4, fallout: 0.5, seed: undefined}; p.noise = function(x, y, z) { if(noiseProfile.generator === undefined) { // caching noiseProfile.generator = new PerlinNoise(noiseProfile.seed); } var generator = noiseProfile.generator; var effect = 1, k = 1, sum = 0; for(var i=0; i<noiseProfile.octaves; ++i) { effect *= noiseProfile.fallout; switch (arguments.length) { case 1: sum += effect * (1 + generator.noise1d(k*x))/2; break; case 2: sum += effect * (1 + generator.noise2d(k*x, k*y))/2; break; case 3: sum += effect * (1 + generator.noise3d(k*x, k*y, k*z))/2; break; } k *= 2; } return sum; }; p.noiseDetail = function(octaves, fallout) { noiseProfile.octaves = octaves; if(fallout !== undefined) { noiseProfile.fallout = fallout; } }; p.noiseSeed = function(seed) { noiseProfile.seed = seed; noiseProfile.generator = undefined; }; // Changes the size of the Canvas ( this resets context properties like 'lineCap', etc. p.size = function size(aWidth, aHeight, aMode) { if (aMode && (aMode === p.WEBGL)) { // get the 3D rendering context try { // If the HTML <canvas> dimensions differ from the // dimensions specified in the size() call in the sketch, for // 3D sketches, browsers will either not render or render the // scene incorrectly. To fix this, we need to adjust the // width and height attributes of the canvas. if (curElement.width !== aWidth || curElement.height !== aHeight) { curElement.setAttribute("width", aWidth); curElement.setAttribute("height", aHeight); } curContext = curElement.getContext("experimental-webgl"); } catch(e_size) { p.debug(e_size); } if (!curContext) { throw "OPENGL 3D context is not supported on this browser."; } else { for (var i = 0; i < p.SINCOS_LENGTH; i++) { sinLUT[i] = p.sin(i * (p.PI / 180) * 0.5); cosLUT[i] = p.cos(i * (p.PI / 180) * 0.5); } // Set defaults curContext.viewport(0, 0, curElement.width, curElement.height); curContext.clearColor(204 / 255, 204 / 255, 204 / 255, 1.0); curContext.clear(curContext.COLOR_BUFFER_BIT); curContext.enable(curContext.DEPTH_TEST); curContext.enable(curContext.BLEND); curContext.blendFunc(curContext.SRC_ALPHA, curContext.ONE_MINUS_SRC_ALPHA); // Create the program objects to render 2D (points, lines) and // 3D (spheres, boxes) shapes. Because 2D shapes are not lit, // lighting calculations could be ommitted from that program object. programObject2D = createProgramObject(curContext, vertexShaderSource2D, fragmentShaderSource2D); programObject3D = createProgramObject(curContext, vertexShaderSource3D, fragmentShaderSource3D); // Now that the programs have been compiled, we can set the default // states for the lights. curContext.useProgram(programObject3D); p.lightFalloff(1, 0, 0); p.shininess(1); p.ambient(255, 255, 255); p.specular(0, 0, 0); // Create buffers for 3D primitives boxBuffer = curContext.createBuffer(); curContext.bindBuffer(curContext.ARRAY_BUFFER, boxBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, newWebGLArray(boxVerts), curContext.STATIC_DRAW); boxNormBuffer = curContext.createBuffer(); curContext.bindBuffer(curContext.ARRAY_BUFFER, boxNormBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, newWebGLArray(boxNorms), curContext.STATIC_DRAW); boxOutlineBuffer = curContext.createBuffer(); curContext.bindBuffer(curContext.ARRAY_BUFFER, boxOutlineBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, newWebGLArray(boxOutlineVerts), curContext.STATIC_DRAW); // The sphere vertices are specified dynamically since the user // can change the level of detail. Everytime the user does that // using sphereDetail(), the new vertices are calculated. sphereBuffer = curContext.createBuffer(); lineBuffer = curContext.createBuffer(); curContext.bindBuffer(curContext.ARRAY_BUFFER, lineBuffer); fillBuffer = curContext.createBuffer(); curContext.bindBuffer(curContext.ARRAY_BUFFER, fillBuffer); pointBuffer = curContext.createBuffer(); curContext.bindBuffer(curContext.ARRAY_BUFFER, pointBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, newWebGLArray([0, 0, 0]), curContext.STATIC_DRAW); cam = new PMatrix3D(); cameraInv = new PMatrix3D(); forwardTransform = new PMatrix3D(); reverseTransform = new PMatrix3D(); modelView = new PMatrix3D(); modelViewInv = new PMatrix3D(); projection = new PMatrix3D(); p.camera(); p.perspective(); forwardTransform = modelView; reverseTransform = modelViewInv; userMatrixStack = new PMatrixStack(); // used by both curve and bezier, so just init here curveBasisMatrix = new PMatrix3D(); curveToBezierMatrix = new PMatrix3D(); curveDrawMatrix = new PMatrix3D(); bezierBasisInverse = new PMatrix3D(); bezierBasisMatrix = new PMatrix3D(); bezierBasisMatrix.set(-1, 3, -3, 1, 3, -6, 3, 0, -3, 3, 0, 0, 1, 0, 0, 0); } p.stroke(0); p.fill(255); } else { if (typeof curContext === "undefined") { // size() was called without p.init() default context, ie. p.createGraphics() curContext = curElement.getContext("2d"); userMatrixStack = new PMatrixStack(); modelView = new PMatrix2D(); } } // The default 2d context has already been created in the p.init() stage if // a 3d context was not specified. This is so that a 2d context will be // available if size() was not called. var props = { fillStyle: curContext.fillStyle, strokeStyle: curContext.strokeStyle, lineCap: curContext.lineCap, lineJoin: curContext.lineJoin }; curElement.width = p.width = aWidth; curElement.height = p.height = aHeight; for (var j in props) { if (props) { curContext[j] = props[j]; } } // redraw the background if background was called before size refreshBackground(); p.context = curContext; // added for createGraphics p.toImageData = function() { return curContext.getImageData(0, 0, this.width, this.height); }; }; //////////////////////////////////////////////////////////////////////////// // 3D Functions //////////////////////////////////////////////////////////////////////////// /* Sets the uniform variable 'varName' to the value specified by 'value'. Before calling this function, make sure the correct program object has been installed as part of the current rendering state. On some systems, if the variable exists in the shader but isn't used, the compiler will optimize it out and this function will fail. */ function uniformf(programObj, varName, varValue) { var varLocation = curContext.getUniformLocation(programObj, varName); // the variable won't be found if it was optimized out. if (varLocation !== -1) { if (varValue.length === 4) { curContext.uniform4fv(varLocation, varValue); } else if (varValue.length === 3) { curContext.uniform3fv(varLocation, varValue); } else if (varValue.length === 2) { curContext.uniform2fv(varLocation, varValue); } else { curContext.uniform1f(varLocation, varValue); } } } function uniformi(programObj, varName, varValue) { var varLocation = curContext.getUniformLocation(programObj, varName); // the variable won't be found if it was optimized out. if (varLocation !== -1) { if (varValue.length === 4) { curContext.uniform4iv(varLocation, varValue); } else if (varValue.length === 3) { curContext.uniform3iv(varLocation, varValue); } else if (varValue.length === 2) { curContext.uniform2iv(varLocation, varValue); } else { curContext.uniform1i(varLocation, varValue); } } } function vertexAttribPointer(programObj, varName, size, VBO) { var varLocation = curContext.getAttribLocation(programObj, varName); if (varLocation !== -1) { curContext.bindBuffer(curContext.ARRAY_BUFFER, VBO); curContext.vertexAttribPointer(varLocation, size, curContext.FLOAT, false, 0, 0); curContext.enableVertexAttribArray(varLocation); } } function uniformMatrix(programObj, varName, transpose, matrix) { var varLocation = curContext.getUniformLocation(programObj, varName); // the variable won't be found if it was optimized out. if (varLocation !== -1) { if (matrix.length === 16) { curContext.uniformMatrix4fv(varLocation, transpose, matrix); } else if (matrix.length === 9) { curContext.uniformMatrix3fv(varLocation, transpose, matrix); } else { curContext.uniformMatrix2fv(varLocation, transpose, matrix); } } } //////////////////////////////////////////////////////////////////////////// // Lights //////////////////////////////////////////////////////////////////////////// p.ambientLight = function(r, g, b, x, y, z) { if (p.use3DContext) { if (lightCount === p.MAX_LIGHTS) { throw "can only create " + p.MAX_LIGHTS + " lights"; } var pos = new PVector(x, y, z); var view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); view.mult(pos, pos); curContext.useProgram(programObject3D); uniformf(programObject3D, "lights[" + lightCount + "].color", [r / 255, g / 255, b / 255]); uniformf(programObject3D, "lights[" + lightCount + "].position", pos.array()); uniformi(programObject3D, "lights[" + lightCount + "].type", 0); uniformi(programObject3D, "lightCount", ++lightCount); } }; p.directionalLight = function(r, g, b, nx, ny, nz) { if (p.use3DContext) { if (lightCount === p.MAX_LIGHTS) { throw "can only create " + p.MAX_LIGHTS + " lights"; } curContext.useProgram(programObject3D); // Less code than manually multiplying, but I'll fix // this when I have more time. var dir = [nx, ny, nz, 0.0000001]; var view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); view.mult(dir, dir); uniformf(programObject3D, "lights[" + lightCount + "].color", [r / 255, g / 255, b / 255]); uniformf(programObject3D, "lights[" + lightCount + "].position", [-dir[0], -dir[1], -dir[2]]); uniformi(programObject3D, "lights[" + lightCount + "].type", 1); uniformi(programObject3D, "lightCount", ++lightCount); } }; p.lightFalloff = function lightFalloff(constant, linear, quadratic) { if (p.use3DContext) { curContext.useProgram(programObject3D); uniformf(programObject3D, "falloff", [constant, linear, quadratic]); } }; p.lightSpecular = function lightSpecular(r, g, b) { if (p.use3DContext) { curContext.useProgram(programObject3D); uniformf(programObject3D, "specular", [r / 255, g / 255, b / 255]); } }; /* Sets the default ambient light, directional light, falloff, and specular values. P5 Documentation says specular() is set, but the code calls lightSpecular(). */ p.lights = function lights() { p.ambientLight(128, 128, 128); p.directionalLight(128, 128, 128, 0, 0, -1); p.lightFalloff(1, 0, 0); p.lightSpecular(0, 0, 0); }; p.pointLight = function(r, g, b, x, y, z) { if (p.use3DContext) { if (lightCount === p.MAX_LIGHTS) { throw "can only create " + p.MAX_LIGHTS + " lights"; } // place the point in view space once instead of once per vertex // in the shader. var pos = new PVector(x, y, z); var view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); view.mult(pos, pos); curContext.useProgram(programObject3D); uniformf(programObject3D, "lights[" + lightCount + "].color", [r / 255, g / 255, b / 255]); uniformf(programObject3D, "lights[" + lightCount + "].position", pos.array()); uniformi(programObject3D, "lights[" + lightCount + "].type", 2); uniformi(programObject3D, "lightCount", ++lightCount); } }; /* Disables lighting so the all shapes drawn after this will not be lit. */ p.noLights = function noLights() { if (p.use3DContext) { lightCount = 0; curContext.useProgram(programObject3D); uniformi(programObject3D, "lightCount", lightCount); } }; /* r,g,b - Color of the light x,y,z - position of the light in modeling space nx,ny,nz - direction of the spotlight angle - in radians concentration - */ p.spotLight = function spotLight(r, g, b, x, y, z, nx, ny, nz, angle, concentration) { if (p.use3DContext) { if (lightCount === p.MAX_LIGHTS) { throw "can only create " + p.MAX_LIGHTS + " lights"; } curContext.useProgram(programObject3D); // place the point in view space once instead of once per vertex // in the shader. var pos = new PVector(x, y, z); var view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); view.mult(pos, pos); // transform the spotlight's direction // need to find a solution for this one. Maybe manual mult? var dir = [nx, ny, nz, 0.0000001]; view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); view.mult(dir, dir); uniformf(programObject3D, "lights[" + lightCount + "].color", [r / 255, g / 255, b / 255]); uniformf(programObject3D, "lights[" + lightCount + "].position", pos.array()); uniformf(programObject3D, "lights[" + lightCount + "].direction", [dir[0], dir[1], dir[2]]); uniformf(programObject3D, "lights[" + lightCount + "].concentration", concentration); uniformf(programObject3D, "lights[" + lightCount + "].angle", angle); uniformi(programObject3D, "lights[" + lightCount + "].type", 3); uniformi(programObject3D, "lightCount", ++lightCount); } }; //////////////////////////////////////////////////////////////////////////// // Camera functions //////////////////////////////////////////////////////////////////////////// p.beginCamera = function beginCamera() { if (manipulatingCamera) { throw ("You cannot call beginCamera() again before calling endCamera()"); } else { manipulatingCamera = true; forwardTransform = cameraInv; reverseTransform = cam; } }; p.endCamera = function endCamera() { if (!manipulatingCamera) { throw ("You cannot call endCamera() before calling beginCamera()"); } else { modelView.set(cam); modelViewInv.set(cameraInv); forwardTransform = modelView; reverseTransform = modelViewInv; manipulatingCamera = false; } }; p.camera = function camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ) { if (arguments.length === 0) { //in case canvas is resized cameraX = curElement.width / 2; cameraY = curElement.height / 2; cameraZ = cameraY / Math.tan(cameraFOV / 2); p.camera(cameraX, cameraY, cameraZ, cameraX, cameraY, 0, 0, 1, 0); } else { var z = new p.PVector(eyeX - centerX, eyeY - centerY, eyeZ - centerZ); var y = new p.PVector(upX, upY, upZ); var transX, transY, transZ; z.normalize(); var x = p.PVector.cross(y, z); y = p.PVector.cross(z, x); x.normalize(); y.normalize(); cam.set(x.x, x.y, x.z, 0, y.x, y.y, y.z, 0, z.x, z.y, z.z, 0, 0, 0, 0, 1); cam.translate(-eyeX, -eyeY, -eyeZ); cameraInv.reset(); cameraInv.invApply(x.x, x.y, x.z, 0, y.x, y.y, y.z, 0, z.x, z.y, z.z, 0, 0, 0, 0, 1); cameraInv.translate(eyeX, eyeY, eyeZ); modelView.set(cam); modelViewInv.set(cameraInv); } }; p.perspective = function perspective(fov, aspect, near, far) { if (arguments.length === 0) { //in case canvas is resized cameraY = curElement.height / 2; cameraZ = cameraY / Math.tan(cameraFOV / 2); cameraNear = cameraZ / 10; cameraFar = cameraZ * 10; cameraAspect = curElement.width / curElement.height; p.perspective(cameraFOV, cameraAspect, cameraNear, cameraFar); } else { var a = arguments; var yMax, yMin, xMax, xMin; yMax = near * Math.tan(fov / 2); yMin = -yMax; xMax = yMax * aspect; xMin = yMin * aspect; p.frustum(xMin, xMax, yMin, yMax, near, far); } }; p.frustum = function frustum(left, right, bottom, top, near, far) { frustumMode = true; projection = new PMatrix3D(); projection.set((2 * near) / (right - left), 0, (right + left) / (right - left), 0, 0, (2 * near) / (top - bottom), (top + bottom) / (top - bottom), 0, 0, 0, -(far + near) / (far - near), -(2 * far * near) / (far - near), 0, 0, -1, 0); }; p.ortho = function ortho(left, right, bottom, top, near, far) { if (arguments.length === 0) { p.ortho(0, p.width, 0, p.height, -10, 10); } else { var x = 2 / (right - left); var y = 2 / (top - bottom); var z = -2 / (far - near); var tx = -(right + left) / (right - left); var ty = -(top + bottom) / (top - bottom); var tz = -(far + near) / (far - near); projection = new PMatrix3D(); projection.set(x, 0, 0, tx, 0, y, 0, ty, 0, 0, z, tz, 0, 0, 0, 1); frustumMode = false; } }; p.printProjection = function() { projection.print(); }; p.printCamera = function() { cam.print(); }; //////////////////////////////////////////////////////////////////////////// // Shapes //////////////////////////////////////////////////////////////////////////// p.box = function(w, h, d) { if (p.use3DContext) { // user can uniformly scale the box by // passing in only one argument. if (!h || !d) { h = d = w; } // Modeling transformation var model = new PMatrix3D(); model.scale(w, h, d); // viewing transformation needs to have Y flipped // becuase that's what Processing does. var view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); curContext.useProgram(programObject3D); uniformMatrix(programObject3D, "model", true, model.array()); uniformMatrix(programObject3D, "view", true, view.array()); uniformMatrix(programObject3D, "projection", true, projection.array()); if (doFill === true) { // fix stitching problems. (lines get occluded by triangles // since they share the same depth values). This is not entirely // working, but it's a start for drawing the outline. So // developers can start playing around with styles. curContext.enable(curContext.POLYGON_OFFSET_FILL); curContext.polygonOffset(1, 1); uniformf(programObject3D, "color", fillStyle); var v = new PMatrix3D(); v.set(view); var m = new PMatrix3D(); m.set(model); v.mult(m); var normalMatrix = new PMatrix3D(); normalMatrix.set(v); normalMatrix.invert(); uniformMatrix(programObject3D, "normalTransform", false, normalMatrix.array()); vertexAttribPointer(programObject3D, "Vertex", 3, boxBuffer); vertexAttribPointer(programObject3D, "Normal", 3, boxNormBuffer); curContext.drawArrays(curContext.TRIANGLES, 0, boxVerts.length / 3); curContext.disable(curContext.POLYGON_OFFSET_FILL); } if (lineWidth > 0 && doStroke) { curContext.useProgram(programObject3D); uniformMatrix(programObject3D, "model", true, model.array()); uniformMatrix(programObject3D, "view", true, view.array()); uniformMatrix(programObject3D, "projection", true, projection.array()); uniformf(programObject3D, "color", strokeStyle); curContext.lineWidth(lineWidth); vertexAttribPointer(programObject3D, "Vertex", 3, boxOutlineBuffer); curContext.drawArrays(curContext.LINES, 0, boxOutlineVerts.length / 3); } } }; var initSphere = function() { var i; sphereVerts = []; for (i = 0; i < sphereDetailU; i++) { sphereVerts.push(0); sphereVerts.push(-1); sphereVerts.push(0); sphereVerts.push(sphereX[i]); sphereVerts.push(sphereY[i]); sphereVerts.push(sphereZ[i]); } sphereVerts.push(0); sphereVerts.push(-1); sphereVerts.push(0); sphereVerts.push(sphereX[0]); sphereVerts.push(sphereY[0]); sphereVerts.push(sphereZ[0]); var v1, v11, v2; // middle rings var voff = 0; for (i = 2; i < sphereDetailV; i++) { v1 = v11 = voff; voff += sphereDetailU; v2 = voff; for (var j = 0; j < sphereDetailU; j++) { sphereVerts.push(parseFloat(sphereX[v1])); sphereVerts.push(parseFloat(sphereY[v1])); sphereVerts.push(parseFloat(sphereZ[v1++])); sphereVerts.push(parseFloat(sphereX[v2])); sphereVerts.push(parseFloat(sphereY[v2])); sphereVerts.push(parseFloat(sphereZ[v2++])); } // close each ring v1 = v11; v2 = voff; sphereVerts.push(parseFloat(sphereX[v1])); sphereVerts.push(parseFloat(sphereY[v1])); sphereVerts.push(parseFloat(sphereZ[v1])); sphereVerts.push(parseFloat(sphereX[v2])); sphereVerts.push(parseFloat(sphereY[v2])); sphereVerts.push(parseFloat(sphereZ[v2])); } // add the northern cap for (i = 0; i < sphereDetailU; i++) { v2 = voff + i; sphereVerts.push(parseFloat(sphereX[v2])); sphereVerts.push(parseFloat(sphereY[v2])); sphereVerts.push(parseFloat(sphereZ[v2])); sphereVerts.push(0); sphereVerts.push(1); sphereVerts.push(0); } sphereVerts.push(parseFloat(sphereX[voff])); sphereVerts.push(parseFloat(sphereY[voff])); sphereVerts.push(parseFloat(sphereZ[voff])); sphereVerts.push(0); sphereVerts.push(1); sphereVerts.push(0); //set the buffer data curContext.bindBuffer(curContext.ARRAY_BUFFER, sphereBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, newWebGLArray(sphereVerts), curContext.STATIC_DRAW); }; p.sphereDetail = function sphereDetail(ures, vres) { var i; if (arguments.length === 1) { ures = vres = arguments[0]; } if (ures < 3) { ures = 3; } // force a minimum res if (vres < 2) { vres = 2; } // force a minimum res // if it hasn't changed do nothing if ((ures === sphereDetailU) && (vres === sphereDetailV)) { return; } var delta = p.SINCOS_LENGTH / ures; var cx = new Array(ures); var cz = new Array(ures); // calc unit circle in XZ plane for (i = 0; i < ures; i++) { cx[i] = cosLUT[parseInt((i * delta) % p.SINCOS_LENGTH, 10)]; cz[i] = sinLUT[parseInt((i * delta) % p.SINCOS_LENGTH, 10)]; } // computing vertexlist // vertexlist starts at south pole var vertCount = ures * (vres - 1) + 2; var currVert = 0; // re-init arrays to store vertices sphereX = new Array(vertCount); sphereY = new Array(vertCount); sphereZ = new Array(vertCount); var angle_step = (p.SINCOS_LENGTH * 0.5) / vres; var angle = angle_step; // step along Y axis for (i = 1; i < vres; i++) { var curradius = sinLUT[parseInt(angle % p.SINCOS_LENGTH, 10)]; var currY = -cosLUT[parseInt(angle % p.SINCOS_LENGTH, 10)]; for (var j = 0; j < ures; j++) { sphereX[currVert] = cx[j] * curradius; sphereY[currVert] = currY; sphereZ[currVert++] = cz[j] * curradius; } angle += angle_step; } sphereDetailU = ures; sphereDetailV = vres; // make the sphere verts and norms initSphere(); }; p.sphere = function() { if (p.use3DContext) { var sRad = arguments[0], c; if ((sphereDetailU < 3) || (sphereDetailV < 2)) { p.sphereDetail(30); } // Modeling transformation var model = new PMatrix3D(); model.scale(sRad, sRad, sRad); // viewing transformation needs to have Y flipped // becuase that's what Processing does. var view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); curContext.useProgram(programObject3D); uniformMatrix(programObject3D, "model", true, model.array()); uniformMatrix(programObject3D, "view", true, view.array()); uniformMatrix(programObject3D, "projection", true, projection.array()); var v = new PMatrix3D(); v.set(view); var m = new PMatrix3D(); m.set(model); v.mult(m); var normalMatrix = new PMatrix3D(); normalMatrix.set(v); normalMatrix.invert(); uniformMatrix(programObject3D, "normalTransform", false, normalMatrix.array()); vertexAttribPointer(programObject3D, "Vertex", 3, sphereBuffer); vertexAttribPointer(programObject3D, "Normal", 3, sphereBuffer); if (doFill === true) { // fix stitching problems. (lines get occluded by triangles // since they share the same depth values). This is not entirely // working, but it's a start for drawing the outline. So // developers can start playing around with styles. curContext.enable(curContext.POLYGON_OFFSET_FILL); curContext.polygonOffset(1, 1); uniformf(programObject3D, "color", fillStyle); curContext.drawArrays(curContext.TRIANGLE_STRIP, 0, sphereVerts.length / 3); curContext.disable(curContext.POLYGON_OFFSET_FILL); } if (lineWidth > 0 && doStroke) { curContext.useProgram(programObject3D); vertexAttribPointer(programObject3D, "Vertex", 3, sphereBuffer); uniformMatrix(programObject3D, "model", true, model.array()); uniformMatrix(programObject3D, "view", true, view.array()); uniformMatrix(programObject3D, "projection", true, projection.array()); uniformf(programObject3D, "color", strokeStyle); curContext.lineWidth(lineWidth); curContext.drawArrays(curContext.LINE_STRIP, 0, sphereVerts.length / 3); } } }; //////////////////////////////////////////////////////////////////////////// // Coordinates //////////////////////////////////////////////////////////////////////////// p.modelX = function modelX(x, y, z) { var mv = modelView.array(); var ci = cameraInv.array(); var ax = mv[0] * x + mv[1] * y + mv[2] * z + mv[3]; var ay = mv[4] * x + mv[5] * y + mv[6] * z + mv[7]; var az = mv[8] * x + mv[9] * y + mv[10] * z + mv[11]; var aw = mv[12] * x + mv[13] * y + mv[14] * z + mv[15]; var ox = ci[0] * ax + ci[1] * ay + ci[2] * az + ci[3] * aw; var ow = ci[12] * ax + ci[13] * ay + ci[14] * az + ci[15] * aw; return (ow !== 0) ? ox / ow : ox; }; p.modelY = function modelY(x, y, z) { var mv = modelView.array(); var ci = cameraInv.array(); var ax = mv[0] * x + mv[1] * y + mv[2] * z + mv[3]; var ay = mv[4] * x + mv[5] * y + mv[6] * z + mv[7]; var az = mv[8] * x + mv[9] * y + mv[10] * z + mv[11]; var aw = mv[12] * x + mv[13] * y + mv[14] * z + mv[15]; var oy = ci[4] * ax + ci[5] * ay + ci[6] * az + ci[7] * aw; var ow = ci[12] * ax + ci[13] * ay + ci[14] * az + ci[15] * aw; return (ow !== 0) ? oy / ow : oy; }; p.modelZ = function modelZ(x, y, z) { var mv = modelView.array(); var ci = cameraInv.array(); var ax = mv[0] * x + mv[1] * y + mv[2] * z + mv[3]; var ay = mv[4] * x + mv[5] * y + mv[6] * z + mv[7]; var az = mv[8] * x + mv[9] * y + mv[10] * z + mv[11]; var aw = mv[12] * x + mv[13] * y + mv[14] * z + mv[15]; var oz = ci[8] * ax + ci[9] * ay + ci[10] * az + ci[11] * aw; var ow = ci[12] * ax + ci[13] * ay + ci[14] * az + ci[15] * aw; return (ow !== 0) ? oz / ow : oz; }; //////////////////////////////////////////////////////////////////////////// // Material Properties //////////////////////////////////////////////////////////////////////////// p.ambient = function ambient() { // create an alias to shorten code var a = arguments; // either a shade of gray or a 'color' object. if (p.use3DContext) { curContext.useProgram(programObject3D); uniformi(programObject3D, "usingMat", true); if (a.length === 1) { // color object was passed in if (typeof a[0] === "string") { var c = a[0].slice(5, -1).split(","); uniformf(programObject3D, "mat_ambient", [c[0] / 255, c[1] / 255, c[2] / 255]); } // else a single number was passed in for gray shade else { uniformf(programObject3D, "mat_ambient", [a[0] / 255, a[0] / 255, a[0] / 255]); } } // Otherwise three values were provided (r,g,b) else { uniformf(programObject3D, "mat_ambient", [a[0] / 255, a[1] / 255, a[2] / 255]); } } }; p.emissive = function emissive() { // create an alias to shorten code var a = arguments; if (p.use3DContext) { curContext.useProgram(programObject3D); uniformi(programObject3D, "usingMat", true); // If only one argument was provided, the user either gave us a // shade of gray or a 'color' object. if (a.length === 1) { // color object was passed in if (typeof a[0] === "string") { var c = a[0].slice(5, -1).split(","); uniformf(programObject3D, "mat_emissive", [c[0] / 255, c[1] / 255, c[2] / 255]); } // else a regular number was passed in for gray shade else { uniformf(programObject3D, "mat_emissive", [a[0] / 255, a[0] / 255, a[0] / 255]); } } // Otherwise three values were provided (r,g,b) else { uniformf(programObject3D, "mat_emissive", [a[0] / 255, a[1] / 255, a[2] / 255]); } } }; p.shininess = function shininess(shine) { if (p.use3DContext) { curContext.useProgram(programObject3D); uniformi(programObject3D, "usingMat", true); uniformf(programObject3D, "shininess", shine); } }; /* Documentation says the following calls are valid, but the Processing throws exceptions: specular(gray, alpha) specular(v1, v2, v3, alpha) So we don't support them either <corban> I dont think this matters so much, let us let color handle it. alpha values are not sent anyways. */ p.specular = function specular() { var c = p.color.apply(this, arguments); if (p.use3DContext) { curContext.useProgram(programObject3D); uniformi(programObject3D, "usingMat", true); uniformf(programObject3D, "mat_specular", p.color.toGLArray(c).slice(0, 3)); } }; //////////////////////////////////////////////////////////////////////////// // Coordinates //////////////////////////////////////////////////////////////////////////// p.screenX = function screenX( x, y, z ) { var mv = modelView.array(); var pj = projection.array(); var ax = mv[ 0]*x + mv[ 1]*y + mv[ 2]*z + mv[ 3]; var ay = mv[ 4]*x + mv[ 5]*y + mv[ 6]*z + mv[ 7]; var az = mv[ 8]*x + mv[ 9]*y + mv[10]*z + mv[11]; var aw = mv[12]*x + mv[13]*y + mv[14]*z + mv[15]; var ox = pj[ 0]*ax + pj[ 1]*ay + pj[ 2]*az + pj[ 3]*aw; var ow = pj[12]*ax + pj[13]*ay + pj[14]*az + pj[15]*aw; if ( ow !== 0 ){ ox /= ow; } return p.width * ( 1 + ox ) / 2.0; }; p.screenY = function screenY( x, y, z ) { var mv = modelView.array(); var pj = projection.array(); var ax = mv[ 0]*x + mv[ 1]*y + mv[ 2]*z + mv[ 3]; var ay = mv[ 4]*x + mv[ 5]*y + mv[ 6]*z + mv[ 7]; var az = mv[ 8]*x + mv[ 9]*y + mv[10]*z + mv[11]; var aw = mv[12]*x + mv[13]*y + mv[14]*z + mv[15]; var oy = pj[ 4]*ax + pj[ 5]*ay + pj[ 6]*az + pj[ 7]*aw; var ow = pj[12]*ax + pj[13]*ay + pj[14]*az + pj[15]*aw; if ( ow !== 0 ){ oy /= ow; } return p.height * ( 1 + oy ) / 2.0; }; p.screenZ = function screenZ( x, y, z ) { var mv = modelView.array(); var pj = projection.array(); var ax = mv[ 0]*x + mv[ 1]*y + mv[ 2]*z + mv[ 3]; var ay = mv[ 4]*x + mv[ 5]*y + mv[ 6]*z + mv[ 7]; var az = mv[ 8]*x + mv[ 9]*y + mv[10]*z + mv[11]; var aw = mv[12]*x + mv[13]*y + mv[14]*z + mv[15]; var oz = pj[ 8]*ax + pj[ 9]*ay + pj[10]*az + pj[11]*aw; var ow = pj[12]*ax + pj[13]*ay + pj[14]*az + pj[15]*aw; if ( ow !== 0 ) { oz /= ow; } return ( oz + 1 ) / 2.0; }; //////////////////////////////////////////////////////////////////////////// // Style functions //////////////////////////////////////////////////////////////////////////// p.fill = function fill() { doFill = true; var color = p.color(arguments[0], arguments[1], arguments[2], arguments[3]); if (p.use3DContext) { fillStyle = p.color.toGLArray(color); } else { curContext.fillStyle = p.color.toString(color); } }; p.noFill = function noFill() { doFill = false; }; p.stroke = function stroke() { doStroke = true; var color = p.color(arguments[0], arguments[1], arguments[2], arguments[3]); if (p.use3DContext) { strokeStyle = p.color.toGLArray(color); } else { curContext.strokeStyle = p.color.toString(color); } }; p.noStroke = function noStroke() { doStroke = false; }; p.strokeWeight = function strokeWeight(w) { if (p.use3DContext) { lineWidth = w; } else { curContext.lineWidth = w; } }; p.strokeCap = function strokeCap(value) { curContext.lineCap = value; }; p.strokeJoin = function strokeJoin(value) { curContext.lineJoin = value; }; p.smooth = function() { if (!p.use3DContext) { curElement.style.setProperty("image-rendering", "optimizeQuality", "important"); curContext.mozImageSmoothingEnabled = true; } }; p.noSmooth = function() { if (!p.use3DContext) { curElement.style.setProperty("image-rendering", "optimizeSpeed", "important"); curContext.mozImageSmoothingEnabled = false; } }; //////////////////////////////////////////////////////////////////////////// // Vector drawing functions //////////////////////////////////////////////////////////////////////////// p.Point = function Point(x, y) { this.x = x; this.y = y; this.copy = function() { return new Point(x, y); }; }; p.point = function point(x, y, z) { if (p.use3DContext) { var model = new PMatrix3D(); // move point to position model.translate(x, y, z || 0); var view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); curContext.useProgram(programObject2D); uniformMatrix(programObject2D, "model", true, model.array()); uniformMatrix(programObject2D, "view", true, view.array()); uniformMatrix(programObject2D, "projection", true, projection.array()); if (lineWidth > 0 && doStroke) { // this will be replaced with the new bit shifting color code uniformf(programObject2D, "color", strokeStyle); vertexAttribPointer(programObject2D, "Vertex", 3, pointBuffer); curContext.drawArrays(curContext.POINTS, 0, 1); } } else { if (doStroke) { var oldFill = curContext.fillStyle; curContext.fillStyle = curContext.strokeStyle; curContext.fillRect(Math.round(x), Math.round(y), 1, 1); curContext.fillStyle = oldFill; } } }; p.beginShape = function beginShape(type) { curShape = type; curShapeCount = 0; curvePoints = []; //textureImage = null; vertArray = []; if(p.use3DContext) { //normalMode = NORMAL_MODE_AUTO; } }; p.vertex = function vertex() { if(firstVert){ firstVert = false; } var vert = []; if(arguments.length === 4){ //x, y, u, v vert[0] = arguments[0]; vert[1] = arguments[1]; vert[2] = 0; vert[3] = arguments[2]; vert[4] = arguments[3]; } else{ // x, y, z, u, v vert[0] = arguments[0]; vert[1] = arguments[1]; vert[2] = arguments[2] || 0; vert[3] = arguments[3] || 0; vert[4] = arguments[4] || 0; } // fill rgba vert[5] = fillStyle[0]; vert[6] = fillStyle[1]; vert[7] = fillStyle[2]; vert[8] = fillStyle[3]; // stroke rgba vert[9] = strokeStyle[0]; vert[10] = strokeStyle[1]; vert[11] = strokeStyle[2]; vert[12] = strokeStyle[3]; //normals vert[13] = normalX; vert[14] = normalY; vert[15] = normalZ; vertArray.push(vert); }; var point2D = function point2D(vArray){ var model = new PMatrix3D(); var view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); curContext.useProgram(programObject2D); uniformMatrix(programObject2D, "model", true, model.array()); uniformMatrix(programObject2D, "view", true, view.array()); uniformMatrix(programObject2D, "projection", true, projection.array()); uniformf(programObject2D, "color", strokeStyle); vertexAttribPointer(programObject2D, "Vertex", 3, pointBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, newWebGLArray(vArray), curContext.STREAM_DRAW); curContext.drawArrays(curContext.POINTS, 0, vArray.length/3); }; var line2D = function line2D(vArray, mode){ var ctxMode; if (mode === "LINES"){ ctxMode = curContext.LINES; } else if(mode === "LINE_LOOP"){ ctxMode = curContext.LINE_LOOP; } else{ ctxMode = curContext.LINE_STRIP; } var model = new PMatrix3D(); var view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); curContext.useProgram(programObject2D); uniformMatrix(programObject2D, "model", true, model.array()); uniformMatrix(programObject2D, "view", true, view.array()); uniformMatrix(programObject2D, "projection", true, projection.array()); uniformf(programObject2D, "color", strokeStyle); vertexAttribPointer(programObject2D, "Vertex", 3, lineBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, newWebGLArray(vArray), curContext.STREAM_DRAW); curContext.drawArrays(ctxMode, 0, vArray.length/3); }; var fill2D = function fill2D(vArray, mode){ var ctxMode; if(mode === "TRIANGLES"){ ctxMode = curContext.TRIANGLES; } else if(mode === "TRIANGLE_FAN"){ ctxMode = curContext.TRIANGLE_FAN; } else{ ctxMode = curContext.TRIANGLE_STRIP; } var model = new PMatrix3D(); var view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); curContext.useProgram( programObject2D ); uniformMatrix( programObject2D, "model", true, model.array() ); uniformMatrix( programObject2D, "view", true, view.array() ); uniformMatrix( programObject2D, "projection", true, projection.array() ); curContext.enable( curContext.POLYGON_OFFSET_FILL ); curContext.polygonOffset( 1, 1 ); uniformf( programObject2D, "color", fillStyle); vertexAttribPointer(programObject2D, "Vertex", 3, fillBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, newWebGLArray(vArray), curContext.STREAM_DRAW); curContext.drawArrays( ctxMode, 0, vArray.length/3 ); curContext.disable( curContext.POLYGON_OFFSET_FILL ); }; p.endShape = function endShape(close){ firstVert = true; var i, j, k; var last = vertArray.length - 1; if(!close){ p.CLOSE = false; } else{ p.CLOSE = true; } if(isCurve && curShape === p.POLYGON || isCurve && curShape === undefined){ if(vertArray.length > 3){ if(p.use3DContext){ } else{ var b = [], s = 1 - curTightness; curContext.beginPath(); curContext.moveTo(vertArray[1][0], vertArray[1][1]); /* * Matrix to convert from Catmull-Rom to cubic Bezier * where t = curTightness * |0 1 0 0 | * |(t-1)/6 1 (1-t)/6 0 | * |0 (1-t)/6 1 (t-1)/6 | * |0 0 0 0 | */ for(i = 1; (i+2) < vertArray.length; i++){ b[0] = [vertArray[i][0], vertArray[i][1]]; b[1] = [vertArray[i][0] + (s * vertArray[i+1][0] - s * vertArray[i-1][0]) / 6, vertArray[i][1] + (s * vertArray[i+1][1] - s * vertArray[i-1][1]) / 6]; b[2] = [vertArray[i+1][0] + (s * vertArray[i][0] - s * vertArray[i+2][0]) / 6, vertArray[i+1][1] + (s * vertArray[i][1] - s * vertArray[i+2][1]) / 6]; b[3] = [vertArray[i+1][0], vertArray[i+1][1]]; curContext.bezierCurveTo(b[1][0], b[1][1], b[2][0], b[2][1], b[3][0], b[3][1]); } if(doFill){ curContext.fill(); } if(doStroke){ curContext.stroke(); } curContext.closePath(); } } } else if(isBezier && curShape === p.POLYGON || isBezier && curShape === undefined){ curContext.beginPath(); curContext.moveTo(vertArray[0][0], vertArray[0][1]); for(i = 1; i < vertArray.length; i++){ curContext.bezierCurveTo(vertArray[i][0], vertArray[i][1], vertArray[i][2], vertArray[i][3], vertArray[i][4], vertArray[i][5]); } if(doFill){ curContext.fill(); } if(doStroke){ curContext.stroke(); } curContext.closePath(); } else{ if(p.use3DContext){ // 3D context var lineVertArray = []; var fillVertArray = []; for(i = 0; i < vertArray.length; i++){ for(j = 0; j < 3; j++){ fillVertArray.push(vertArray[i][j]); } } fillVertArray.push(vertArray[0][0]); fillVertArray.push(vertArray[0][1]); fillVertArray.push(vertArray[0][2]); if (curShape === p.POINTS){ for(i = 0; i < vertArray.length; i++){ for(j = 0; j < 3; j++){ lineVertArray.push(vertArray[i][j]); } } point2D(lineVertArray); } else if(curShape === p.LINES){ for(i = 0; i < vertArray.length; i++){ for(j = 0; j < 3; j++){ lineVertArray.push(vertArray[i][j]); } } line2D(lineVertArray, "LINES"); } else if(curShape === p.TRIANGLES){ if(vertArray.length > 2){ for(i = 0; (i+2) < vertArray.length; i+=3){ fillVertArray = []; lineVertArray = []; for(j = 0; j < 3; j++){ for(k = 0; k < 3; k++){ lineVertArray.push(vertArray[i+j][k]); fillVertArray.push(vertArray[i+j][k]); } } if(doStroke){ line2D(lineVertArray, "LINE_LOOP"); } if(doFill){ fill2D(fillVertArray, "TRIANGLES"); } } } } else if(curShape === p.TRIANGLE_STRIP){ if(vertArray.length > 2){ for(i = 0; (i+2) < vertArray.length; i++){ lineVertArray = []; fillVertArray = []; for(j = 0; j < 3; j++){ for(k = 0; k < 3; k++){ lineVertArray.push(vertArray[i+j][k]); fillVertArray.push(vertArray[i+j][k]); } } if(doFill){ fill2D(fillVertArray); } if(doStroke){ line2D(lineVertArray, "LINE_LOOP"); } } } } else if(curShape === p.TRIANGLE_FAN){ if(vertArray.length > 2){ for(i = 0; i < 3; i++){ for(j = 0; j < 3; j++){ lineVertArray.push(vertArray[i][j]); } } if(doStroke){ line2D(lineVertArray, "LINE_LOOP"); } for(i = 2; (i+1) < vertArray.length; i++){ lineVertArray = []; lineVertArray.push(vertArray[0][0]); lineVertArray.push(vertArray[0][1]); lineVertArray.push(vertArray[0][2]); for(j = 0; j < 2; j++){ for(k = 0; k < 3; k++){ lineVertArray.push(vertArray[i+j][k]); } } if(doStroke){ line2D(lineVertArray, "LINE_STRIP"); } } if(doFill){ fill2D(fillVertArray, "TRIANGLE_FAN"); } } } else if(curShape === p.QUADS){ for(i = 0; (i + 3) < vertArray.length; i+=4){ lineVertArray = []; for(j = 0; j < 4; j++){ for(k = 0; k < 3; k++){ lineVertArray.push(vertArray[i+j][k]); } } if(doStroke){ line2D(lineVertArray, "LINE_LOOP"); } if(doFill){ fillVertArray = []; for(j = 0; j < 3; j++){ fillVertArray.push(vertArray[i][j]); } for(j = 0; j < 3; j++){ fillVertArray.push(vertArray[i+1][j]); } for(j = 0; j < 3; j++){ fillVertArray.push(vertArray[i+3][j]); } for(j = 0; j < 3; j++){ fillVertArray.push(vertArray[i+2][j]); } fill2D(fillVertArray, "TRIANGLE_STRIP"); } } } else if(curShape === p.QUAD_STRIP){ var tempArray = []; if(vertArray.length > 3){ for(i = 0; i < 2; i++){ for(j = 0; j < 3; j++){ lineVertArray.push(vertArray[i][j]); } } line2D(lineVertArray, "LINE_STRIP"); if(vertArray.length > 4 && vertArray.length % 2 > 0){ tempArray = fillVertArray.splice(fillVertArray.length - 6); vertArray.pop(); } for(i = 0; (i+3) < vertArray.length; i+=2){ lineVertArray = []; for(j = 0; j < 3; j++){ lineVertArray.push(vertArray[i+1][j]); } for(j = 0; j < 3; j++){ lineVertArray.push(vertArray[i+3][j]); } for(j = 0; j < 3; j++){ lineVertArray.push(vertArray[i+2][j]); } for(j = 0; j < 3; j++){ lineVertArray.push(vertArray[i+0][j]); } line2D(lineVertArray, "LINE_STRIP"); } if(doFill){ fill2D(fillVertArray); } } } else{ if(vertArray.length === 1){ for(j = 0; j < 3; j++){ lineVertArray.push(vertArray[0][j]); } point2D(lineVertArray); } else{ for(i = 0; i < vertArray.length; i++){ for(j = 0; j < 3; j++){ lineVertArray.push(vertArray[i][j]); } } if(p.CLOSE){ line2D(lineVertArray, "LINE_LOOP"); } else{ line2D(lineVertArray, "LINE_STRIP"); } if(doFill){ fill2D(fillVertArray); } } } } // 2D context else{ if (curShape === p.POINTS){ for(i = 0; i < vertArray.length; i++){ p.point(vertArray[i][0], vertArray[i][1]); } } else if(curShape === p.LINES){ for(i = 0; (i + 1) < vertArray.length; i+=2){ p.line(vertArray[i][0], vertArray[i][1], vertArray[i+1][0], vertArray[i+1][1]); } } else if(curShape === p.TRIANGLES){ for(i = 0; (i + 2) < vertArray.length; i+=3){ curContext.beginPath(); curContext.moveTo(vertArray[i][0], vertArray[i][1]); curContext.lineTo(vertArray[i+1][0], vertArray[i+1][1]); curContext.lineTo(vertArray[i+2][0], vertArray[i+2][1]); curContext.lineTo(vertArray[i][0], vertArray[i][1]); if(doFill){ curContext.fill(); } if(doStroke){ curContext.stroke(); } curContext.closePath(); } } else if(curShape === p.TRIANGLE_STRIP){ if(vertArray.length > 2){ curContext.beginPath(); curContext.moveTo(vertArray[0][0], vertArray[0][1]); curContext.lineTo(vertArray[1][0], vertArray[1][1]); for(i = 2; i < vertArray.length; i++){ curContext.lineTo(vertArray[i][0], vertArray[i][1]); curContext.lineTo(vertArray[i-2][0], vertArray[i-2][1]); if(doFill){ curContext.fill(); } if(doStroke){ curContext.stroke(); } curContext.moveTo(vertArray[i][0],vertArray[i][1]); } } } else if(curShape === p.TRIANGLE_FAN){ if(vertArray.length > 2){ curContext.beginPath(); curContext.moveTo(vertArray[0][0], vertArray[0][1]); curContext.lineTo(vertArray[1][0], vertArray[1][1]); curContext.lineTo(vertArray[2][0], vertArray[2][1]); if(doFill){ curContext.fill(); } if(doStroke){ curContext.stroke(); } for(i = 3; i < vertArray.length; i++){ curContext.moveTo(vertArray[0][0], vertArray[0][1]); curContext.lineTo(vertArray[i-1][0], vertArray[i-1][1]); curContext.lineTo(vertArray[i][0], vertArray[i][1]); if(doFill){ curContext.fill(); } if(doStroke){ curContext.stroke(); } } } } else if(curShape === p.QUADS){ for(i = 0; (i + 3) < vertArray.length; i+=4){ curContext.beginPath(); curContext.moveTo(vertArray[i][0], vertArray[i][1]); for(j = 1; j < 4; j++){ curContext.lineTo(vertArray[i+j][0], vertArray[i+j][1]); } curContext.lineTo(vertArray[i][0], vertArray[i][1]); if(doFill){ curContext.fill(); } if(doStroke){ curContext.stroke(); } curContext.closePath(); } } else if(curShape === p.QUAD_STRIP){ if(vertArray.length > 3){ curContext.beginPath(); curContext.moveTo(vertArray[0][0], vertArray[0][1]); curContext.lineTo(vertArray[1][0], vertArray[1][1]); for(i = 2; (i+1) < vertArray.length; i++){ if((i % 2) === 0){ curContext.moveTo(vertArray[i-2][0], vertArray[i-2][1]); curContext.lineTo(vertArray[i][0], vertArray[i][1]); curContext.lineTo(vertArray[i+1][0], vertArray[i+1][1]); curContext.lineTo(vertArray[i-1][0], vertArray[i-1][1]); if(doFill){ curContext.fill(); } if(doStroke){ curContext.stroke(); } } } } } else{ curContext.beginPath(); curContext.moveTo(vertArray[0][0], vertArray[0][1]); for(i = 1; i < vertArray.length; i++){ curContext.lineTo(vertArray[i][0], vertArray[i][1]); } if(p.CLOSE){ curContext.lineTo(vertArray[0][0], vertArray[0][1]); } if(doFill){ curContext.fill(); } if(doStroke){ curContext.stroke(); } } curContext.closePath(); } } isCurve = false; isBezier = false; }; p.bezierVertex = function(){ isBezier = true; var vert = []; if(firstVert){ throw ("vertex() must be used at least once before calling bezierVertex()"); } else{ if(arguments.length === 6){ for(var i = 0; i < arguments.length; i++){ vert[i] = arguments[i]; } } else{ //for 9 arguments (3d) } vertArray.push(vert); } }; p.curveVertex = function(x, y, z) { isCurve = true; p.vertex(x, y, z); }; p.curveVertexSegment = function(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) { var x0 = x2; var y0 = y2; var z0 = z2; var draw = curveDrawMatrix.array(); var xplot1 = draw[4] * x1 + draw[5] * x2 + draw[6] * x3 + draw[7] * x4; var xplot2 = draw[8] * x1 + draw[9] * x2 + draw[10] * x3 + draw[11] * x4; var xplot3 = draw[12] * x1 + draw[13] * x2 + draw[14] * x3 + draw[15] * x4; var yplot1 = draw[4] * y1 + draw[5] * y2 + draw[6] * y3 + draw[7] * y4; var yplot2 = draw[8] * y1 + draw[9] * y2 + draw[10] * y3 + draw[11] * y4; var yplot3 = draw[12] * y1 + draw[13] * y2 + draw[14] * y3 + draw[15] * y4; var zplot1 = draw[4] * z1 + draw[5] * z2 + draw[6] * z3 + draw[7] * z4; var zplot2 = draw[8] * z1 + draw[9] * z2 + draw[10] * z3 + draw[11] * z4; var zplot3 = draw[12] * z1 + draw[13] * z2 + draw[14] * z3 + draw[15] * z4; p.vertex(x0, y0, z0); for (var j = 0; j < curveDetail; j++) { x0 += xplot1; xplot1 += xplot2; xplot2 += xplot3; y0 += yplot1; yplot1 += yplot2; yplot2 += yplot3; z0 += zplot1; zplot1 += zplot2; zplot2 += zplot3; p.vertex(x0, y0, z0); } }; p.curve = function curve() { if (arguments.length === 8) // curve(x1, y1, x2, y2, x3, y3, x4, y4) { p.beginShape(); p.curveVertex(arguments[0], arguments[1]); p.curveVertex(arguments[2], arguments[3]); p.curveVertex(arguments[4], arguments[5]); p.curveVertex(arguments[6], arguments[7]); p.endShape(); } else { // curve( x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); if (p.use3DContext) { p.beginShape(); p.curveVertex(arguments[0], arguments[1], arguments[2]); p.curveVertex(arguments[3], arguments[4], arguments[5]); p.curveVertex(arguments[6], arguments[7], arguments[8]); p.curveVertex(arguments[9], arguments[10], arguments[11]); p.endShape(); } } }; p.curveTightness = function(tightness) { curTightness = tightness; }; //used by both curveDetail and bezierDetail var splineForward = function(segments, matrix) { var f = 1.0 / segments; var ff = f * f; var fff = ff * f; matrix.set(0, 0, 0, 1, fff, ff, f, 0, 6 * fff, 2 * ff, 0, 0, 6 * fff, 0, 0, 0); }; //internal curveInit //used by curveDetail, curveTightness var curveInit = function() { // allocate only if/when used to save startup time if (!curveDrawMatrix) { curveBasisMatrix = new PMatrix3D(); curveDrawMatrix = new PMatrix3D(); curveInited = true; } var s = curTightness; curveBasisMatrix.set(((s - 1) / 2).toFixed(2), ((s + 3) / 2).toFixed(2), ((-3 - s) / 2).toFixed(2), ((1 - s) / 2).toFixed(2), (1 - s), ((-5 - s) / 2).toFixed(2), (s + 2), ((s - 1) / 2).toFixed(2), ((s - 1) / 2).toFixed(2), 0, ((1 - s) / 2).toFixed(2), 0, 0, 1, 0, 0); splineForward(curveDetail, curveDrawMatrix); if (!bezierBasisInverse) { //bezierBasisInverse = bezierBasisMatrix.get(); //bezierBasisInverse.invert(); curveToBezierMatrix = new PMatrix3D(); } // TODO only needed for PGraphicsJava2D? if so, move it there // actually, it's generally useful for other renderers, so keep it // or hide the implementation elsewhere. curveToBezierMatrix.set(curveBasisMatrix); curveToBezierMatrix.preApply(bezierBasisInverse); // multiply the basis and forward diff matrices together // saves much time since this needn't be done for each curve curveDrawMatrix.apply(curveBasisMatrix); }; p.curveDetail = function curveDetail() { curveDetail = arguments[0]; curveInit(); }; p.rectMode = function rectMode(aRectMode) { curRectMode = aRectMode; }; p.imageMode = function(mode) { switch (mode) { case p.CORNER: imageModeConvert = imageModeCorner; break; case p.CORNERS: imageModeConvert = imageModeCorners; break; case p.CENTER: imageModeConvert = imageModeCenter; break; default: throw "Invalid imageMode"; } }; p.ellipseMode = function ellipseMode(aEllipseMode) { curEllipseMode = aEllipseMode; }; p.arc = function arc(x, y, width, height, start, stop) { if (width <= 0) { return; } if (curEllipseMode === p.CORNER) { x += width / 2; y += height / 2; } curContext.moveTo(x, y); curContext.beginPath(); curContext.arc(x, y, curEllipseMode === p.CENTER_RADIUS ? width : width / 2, start, stop, false); if (doStroke) { curContext.stroke(); } curContext.lineTo(x, y); if (doFill) { curContext.fill(); } curContext.closePath(); }; p.line = function line() { var x1, y1, z1, x2, y2, z2; if (p.use3DContext) { if (arguments.length === 6) { x1 = arguments[0]; y1 = arguments[1]; z1 = arguments[2]; x2 = arguments[3]; y2 = arguments[4]; z2 = arguments[5]; } else if (arguments.length === 4) { x1 = arguments[0]; y1 = arguments[1]; z1 = 0; x2 = arguments[2]; y2 = arguments[3]; z2 = 0; } var lineVerts = [x1, y1, z1, x2, y2, z2]; var model = new PMatrix3D(); //model.scale(w, h, d); var view = new PMatrix3D(); view.scale(1, -1, 1); view.apply(modelView.array()); curContext.useProgram(programObject2D); uniformMatrix(programObject2D, "model", true, model.array()); uniformMatrix(programObject2D, "view", true, view.array()); uniformMatrix(programObject2D, "projection", true, projection.array()); if (lineWidth > 0 && doStroke) { curContext.useProgram(programObject2D); uniformf(programObject2D, "color", strokeStyle); curContext.lineWidth(lineWidth); vertexAttribPointer(programObject2D, "Vertex", 3, lineBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, newWebGLArray(lineVerts), curContext.STREAM_DRAW); curContext.drawArrays(curContext.LINES, 0, 2); } } else { x1 = arguments[0]; y1 = arguments[1]; x2 = arguments[2]; y2 = arguments[3]; if (doStroke) { curContext.beginPath(); curContext.moveTo(x1 || 0, y1 || 0); curContext.lineTo(x2 || 0, y2 || 0); curContext.stroke(); curContext.closePath(); } } }; p.bezier = function bezier(x1, y1, x2, y2, x3, y3, x4, y4) { curContext.beginPath(); curContext.moveTo(x1, y1); curContext.bezierCurveTo(x2, y2, x3, y3, x4, y4); curContext.stroke(); curContext.closePath(); }; p.bezierPoint = function bezierPoint(a, b, c, d, t) { return (1 - t) * (1 - t) * (1 - t) * a + 3 * (1 - t) * (1 - t) * t * b + 3 * (1 - t) * t * t * c + t * t * t * d; }; p.bezierTangent = function bezierTangent(a, b, c, d, t) { return (3 * t * t * (-a + 3 * b - 3 * c + d) + 6 * t * (a - 2 * b + c) + 3 * (-a + b)); }; p.curvePoint = function curvePoint(a, b, c, d, t) { return 0.5 * ((2 * b) + (-a + c) * t + (2 * a - 5 * b + 4 * c - d) * t * t + (-a + 3 * b - 3 * c + d) * t * t * t); }; p.curveTangent = function curveTangent(a, b, c, d, t) { return 0.5 * ((-a + c) + 2 * (2 * a - 5 * b + 4 * c - d) * t + 3 * (-a + 3 * b - 3 * c + d) * t * t); }; p.triangle = function triangle(x1, y1, x2, y2, x3, y3) { p.beginShape(p.TRIANGLES); p.vertex(x1, y1, 0); p.vertex(x2, y2, 0); p.vertex(x3, y3, 0); p.endShape(); }; p.quad = function quad(x1, y1, x2, y2, x3, y3, x4, y4) { p.beginShape(p.QUADS); p.vertex(x1, y1, 0); p.vertex(x2, y2, 0); p.vertex(x3, y3, 0); p.vertex(x4, y4, 0); p.endShape(); }; p.rect = function rect(x, y, width, height) { if (!width && !height) { return; } curContext.beginPath(); var offsetStart = 0; var offsetEnd = 0; if (curRectMode === p.CORNERS) { width -= x; height -= y; } if (curRectMode === p.RADIUS) { width *= 2; height *= 2; } if (curRectMode === p.CENTER || curRectMode === p.RADIUS) { x -= width / 2; y -= height / 2; } curContext.rect( Math.round(x) - offsetStart, Math.round(y) - offsetStart, Math.round(width) + offsetEnd, Math.round(height) + offsetEnd); if (doFill) { curContext.fill(); } if (doStroke) { curContext.stroke(); } curContext.closePath(); }; p.ellipse = function ellipse(x, y, width, height) { x = x || 0; y = y || 0; if (width <= 0 && height <= 0) { return; } curContext.beginPath(); if (curEllipseMode === p.RADIUS) { width *= 2; height *= 2; } if (curEllipseMode === p.CORNERS) { width = width - x; height = height - y; } if (curEllipseMode === p.CORNER || curEllipseMode === p.CORNERS) { x += width / 2; y += height / 2; } var offsetStart = 0; // Shortcut for drawing a circle if (width === height) { curContext.arc(x - offsetStart, y - offsetStart, width / 2, 0, p.TWO_PI, false); } else { var w = width / 2, h = height / 2, C = 0.5522847498307933; var c_x = C * w, c_y = C * h; // TODO: Audit curContext.moveTo(x + w, y); curContext.bezierCurveTo(x + w, y - c_y, x + c_x, y - h, x, y - h); curContext.bezierCurveTo(x - c_x, y - h, x - w, y - c_y, x - w, y); curContext.bezierCurveTo(x - w, y + c_y, x - c_x, y + h, x, y + h); curContext.bezierCurveTo(x + c_x, y + h, x + w, y + c_y, x + w, y); } if (doFill) { curContext.fill(); } if (doStroke) { curContext.stroke(); } curContext.closePath(); }; p.normal = function normal(nx, ny, nz) { if (arguments.length !== 3 || !(typeof nx === "number" && typeof ny === "number" && typeof nz === "number")) { throw "normal() requires three numeric arguments."; } normalX = nx; normalY = ny; normalZ = nz; if (curShape !== 0) { if (normalMode === p.NORMAL_MODE_AUTO) { normalMode = p.NORMAL_MODE_SHAPE; } else if (normalMode === p.NORMAL_MODE_SHAPE) { normalMode = p.NORMAL_MODE_VERTEX; } } }; //////////////////////////////////////////////////////////////////////////// // Raster drawing functions //////////////////////////////////////////////////////////////////////////// // TODO: function incomplete p.save = function save(file) {}; var Temporary2DContext = document.createElement('canvas').getContext('2d'); var PImage = function PImage(aWidth, aHeight, aFormat) { this.get = function(x, y, w, h) { if (!arguments.length) { return p.get(this); } else if (arguments.length === 2) { return p.get(x, y, this); } else if (arguments.length === 4) { return p.get(x, y, w, h, this); } }; this.set = function(x, y, c) { p.set(x, y, c, this); }; this.blend = function(srcImg, x, y, width, height, dx, dy, dwidth, dheight, MODE) { if (arguments.length === 9) { p.blend(this, srcImg, x, y, width, height, dx, dy, dwidth, dheight, this); } else if (arguments.length === 10) { p.blend(srcImg, x, y, width, height, dx, dy, dwidth, dheight, MODE, this); } }; this.copy = function(srcImg, sx, sy, swidth, sheight, dx, dy, dwidth, dheight) { if (arguments.length === 8) { p.blend(this, srcImg, sx, sy, swidth, sheight, dx, dy, dwidth, p.REPLACE, this); } else if (arguments.length === 9) { p.blend(srcImg, sx, sy, swidth, sheight, dx, dy, dwidth, dheight, p.REPLACE, this); } }; this.resize = function(w, h) { if (this.width !== 0 || this.height !== 0) { // make aspect ratio if w or h is 0 if (w === 0 && h !== 0) { w = this.width / this.height * h; } else if (h === 0 && w !== 0) { h = w / (this.width / this.height); } // put 'this.imageData' into a new canvas var canvas = document.createElement('canvas'); canvas.width = this.width; canvas.height = this.height; // changed for 0.9 slightly this one line canvas.getContext('2d').putImageData(this.imageData, 0, 0); // pass new canvas to drawimage with w,h var canvasResized = document.createElement('canvas'); canvasResized.width = w; canvasResized.height = h; canvasResized.getContext('2d').drawImage(canvas, 0, 0, w, h); // pull imageData object out of canvas into ImageData object var imageData = canvasResized.getContext('2d').getImageData(0, 0, w, h); // set this as new pimage this.fromImageData(imageData); } }; this.mask = function(mask) { this._mask = undefined; if (mask instanceof PImage) { if (mask.width === this.width && mask.height === this.height) { this._mask = mask; } else { throw "mask must have the same dimensions as PImage."; } } else if (typeof mask === "object" && mask.constructor === Array) { // this is a pixel array // mask pixel array needs to be the same length as this.pixels // how do we update this for 0.9 this.imageData holding pixels ^^ // mask.constructor ? and this.pixels.length = this.imageData.data.length instead ? if (this.pixels.length === mask.length) { this._mask = mask; } else { throw "mask array must be the same length as PImage pixels array."; } } }; // handle the sketch code for pixels[] and pixels.length // parser code converts pixels[] to getPixels() // or setPixels(), .length becomes getLength() this.pixels = { getLength: (function(aImg) { return function() { return aImg.imageData.data.length ? aImg.imageData.data.length/4 : 0; }; }(this)), getPixel: (function(aImg) { return function(i) { var offset = i*4; return p.color.toInt(aImg.imageData.data[offset], aImg.imageData.data[offset+1], aImg.imageData.data[offset+2], aImg.imageData.data[offset+3]); }; }(this)), setPixel: (function(aImg) { return function(i,c) { if(c && typeof c === "number") { var offset = i*4; // split c into array var c2 = p.color.toArray(c); // change pixel to c aImg.imageData.data[offset] = c2[0]; aImg.imageData.data[offset+1] = c2[1]; aImg.imageData.data[offset+2] = c2[2]; aImg.imageData.data[offset+3] = c2[3]; } }; }(this)) }; // These are intentionally left blank for PImages, we work live with pixels and draw as necessary this.loadPixels = function() {}; this.updatePixels = function() {}; this.toImageData = function() { // changed for 0.9 var canvas = document.createElement('canvas'); canvas.height = this.height; canvas.width = this.width; var ctx = canvas.getContext('2d'); ctx.putImageData(this.imageData, 0, 0); return ctx.getImageData(0, 0, this.width, this.height); }; this.toDataURL = function() { var canvas = document.createElement('canvas'); canvas.height = this.height; canvas.width = this.width; var ctx = canvas.getContext('2d'); var imgData = ctx.createImageData(this.width, this.height); // changed for 0.9 ctx.putImageData(this.imageData, 0, 0); return canvas.toDataURL(); }; this.fromImageData = function(canvasImg) { this.width = canvasImg.width; this.height = canvasImg.height; this.imageData = canvasImg; // changed for 0.9 this.format = p.ARGB; // changed for 0.9 }; this.fromHTMLImageData = function(htmlImg) { // convert an <img> to a PImage var canvas = document.createElement("canvas"); canvas.width = htmlImg.width; canvas.height = htmlImg.height; var context = canvas.getContext("2d"); context.drawImage(htmlImg, 0, 0); var imageData = context.getImageData(0, 0, htmlImg.width, htmlImg.height); this.fromImageData(imageData); }; if (arguments.length === 1) { // convert an <img> to a PImage this.fromHTMLImageData(arguments[0]); } else if (arguments.length === 2 || arguments.length === 3) { this.width = aWidth || 1; this.height = aHeight || 1; // changed for 0.9 this.imageData = curContext.createImageData(this.width, this.height); this.format = (aFormat === p.ARGB || aFormat === p.ALPHA) ? aFormat : p.RGB; } }; p.PImage = PImage; try { // Opera createImageData fix if (! ("createImageData" in CanvasRenderingContext2D.prototype)) { CanvasRenderingContext2D.prototype.createImageData = function(sw, sh) { return this.getImageData(0, 0, sw, sh); }; } } catch(e) {} p.createImage = function createImage(w, h, mode) { // changed for 0.9 return new PImage(w,h,mode); }; // Loads an image for display. Type is an extension. Callback is fired on load. p.loadImage = function loadImage(file, type, callback) { // if type is specified add it with a . to file to make the filename if (type) { file = file + "." + type; } // if image is in the preloader cache return a new PImage if (p.pjs.imageCache[file]) { return new PImage(p.pjs.imageCache[file]); } // else aysnc load it else { var pimg = new PImage(0, 0, p.ARGB); var img = document.createElement('img'); pimg.sourceImg = img; img.onload = (function(aImage, aPImage, aCallback) { var image = aImage; var pimg = aPImage; var callback = aCallback; return function() { // change the <img> object into a PImage now that its loaded pimg.fromHTMLImageData(image); pimg.loaded = true; if (callback) { callback(); } }; }(img, pimg, callback)); img.src = file; // needs to be called after the img.onload function is declared or it wont work in opera return pimg; } }; // async loading of large images, same functionality as loadImage above p.requestImage = p.loadImage; // Gets a single pixel or block of pixels from the current Canvas Context or a PImage p.get = function get(x, y, w, h, img) { var c; // for 0 2 and 4 arguments use curContext, otherwise PImage.get was called if (!arguments.length) { //return a PImage of curContext c = new PImage(p.width, p.height, p.RGB); c.fromImageData(curContext.getImageData(0, 0, p.width, p.height)); return c; } else if (arguments.length === 5) { // PImage.get(x,y,w,h) was called, return x,y,w,h PImage of img // changed for 0.9, offset start point needs to be *4 var start = y * img.width * 4 + (x*4); var end = (y + h) * img.width * 4 + ((x + w) * 4); c = new PImage(w, h, p.RGB); for (var i = start, j = 0; i < end; i++, j++) { // changed in 0.9 c.imageData.data[j] = img.imageData.data[i]; if (j*4 + 1 % w === 0) { //completed one line, increment i by offset i += (img.width - w) * 4; } } return c; } else if (arguments.length === 4) { // return a PImage of w and h from cood x,y of curContext c = new PImage(w, h, p.RGB); c.fromImageData(curContext.getImageData(x, y, w, h)); return c; } else if (arguments.length === 3) { // PImage.get(x,y) was called, return the color (int) at x,y of img // changed in 0.9 var offset = y * w.width * 4 + (x * 4); return p.color.toInt(w.imageData.data[offset], w.imageData.data[offset + 1], w.imageData.data[offset + 2], w.imageData.data[offset + 3]); } else if (arguments.length === 2) { // return the color at x,y (int) of curContext // create a PImage object of size 1x1 and return the int of the pixels array element 0 if (x < p.width && x >= 0 && y >= 0 && y < p.height) { // x,y is inside canvas space c = new PImage(1, 1, p.RGB); c.fromImageData(curContext.getImageData(x, y, 1, 1)); // changed for 0.9 return p.color.toInt(c.imageData.data[0], c.imageData.data[1], c.imageData.data[2], c.imageData.data[3]); } else { // x,y is outside image return transparent black return 0; } } else if (arguments.length === 1) { // PImage.get() was called, return the PImage return x; } }; // Creates a new Processing instance and passes it back for... processing p.createGraphics = function createGraphics(w, h) { var canvas = document.createElement("canvas"); var ret = new Processing(canvas); ret.size(w, h); ret.canvas = canvas; return ret; }; // Paints a pixel array into the canvas p.set = function set(x, y, obj, img) { var color, oldFill; // PImage.set(x,y,c) was called, set coordinate x,y color to c of img if (arguments.length === 4) { // changed in 0.9 var c = p.color.toArray(obj); var offset = y * img.width * 4 + (x*4); img.imageData.data[offset] = c[0]; img.imageData.data[offset+1] = c[1]; img.imageData.data[offset+2] = c[2]; img.imageData.data[offset+3] = c[3]; } else if (arguments.length === 3) { // called p.set(), was it with a color or a img ? if (typeof obj === "number") { oldFill = curContext.fillStyle; color = obj; curContext.fillStyle = p.color.toString(color); curContext.fillRect(Math.round(x), Math.round(y), 1, 1); curContext.fillStyle = oldFill; } else if (obj instanceof PImage) { p.image(obj, x, y); } } }; p.imageData = {}; // handle the sketch code for pixels[] // parser code converts pixels[] to getPixels() // or setPixels(), .length becomes getLength() p.pixels = { getLength: function() { return p.imageData.data.length ? p.imageData.data.length/4 : 0; }, getPixel: function(i) { var offset = i*4; return p.color.toInt(p.imageData.data[offset], p.imageData.data[offset+1], p.imageData.data[offset+2], p.imageData.data[offset+3]); }, setPixel: function(i,c) { if(c && typeof c === "number") { var offset = i*4; // split c into array var c2 = p.color.toArray(c); // change pixel to c p.imageData.data[offset] = c2[0]; p.imageData.data[offset+1] = c2[1]; p.imageData.data[offset+2] = c2[2]; p.imageData.data[offset+3] = c2[3]; } } }; // Gets a 1-Dimensional pixel array from Canvas p.loadPixels = function() { // changed in 0.9 p.imageData = p.get(0, 0, p.width, p.height).imageData; }; // Draws a 1-Dimensional pixel array to Canvas p.updatePixels = function() { // changed in 0.9 if (p.imageData) { curContext.putImageData(p.imageData, 0, 0); } }; // Draw an image or a color to the background p.background = function background() { var color, a, img; // background params are either a color or a PImage if (typeof arguments[0] === 'number') { color = p.color.apply(this, arguments); // override alpha value, processing ignores the alpha for background color color = color | p.ALPHA_MASK; } else if (arguments.length === 1 && arguments[0] instanceof PImage) { img = arguments[0]; if (!img.pixels || img.width !== p.width || img.height !== p.height) { throw "Background image must be the same dimensions as the canvas."; } } else { throw "Incorrect background parameters."; } if (p.use3DContext) { if (typeof color !== 'undefined') { var c = p.color.toGLArray(color); refreshBackground = function() { curContext.clearColor(c[0], c[1], c[2], c[3]); curContext.clear(curContext.COLOR_BUFFER_BIT | curContext.DEPTH_BUFFER_BIT); }; } else { // Handle image background for 3d context. not done yet. refreshBackground = function() {}; } } else { // 2d context if (typeof color !== 'undefined') { refreshBackground = function() { var oldFill = curContext.fillStyle; curContext.fillStyle = p.color.toString(color); curContext.fillRect(0, 0, p.width, p.height); curContext.fillStyle = oldFill; }; } else { refreshBackground = function() { p.image(img, 0, 0); }; } } refreshBackground(); }; // Draws an image to the Canvas p.image = function image(img, x, y, w, h) { if (img.width > 0) { var bounds = imageModeConvert(x || 0, y || 0, w || img.width, h || img.height, arguments.length < 4); var obj = img.toImageData(); if (img._mask) { var j, size; if (img._mask instanceof PImage) { var objMask = img._mask.toImageData(); for (j = 2, size = img.width * img.height * 4; j < size; j += 4) { // using it as an alpha channel obj.data[j + 1] = objMask.data[j]; // but only the blue color channel } } else { for (j = 0, size = img._mask.length; j < size; ++j) { obj.data[(j << 2) + 3] = img._mask[j]; } } } // draw the image //curContext.putImageData(obj, x, y); // this causes error if data overflows the canvas dimensions curTint(obj); var c = document.createElement('canvas'); c.width = obj.width; c.height = obj.height; var ctx = c.getContext('2d'); ctx.putImageData(obj, 0, 0); curContext.drawImage(c, 0, 0, img.width, img.height, bounds.x, bounds.y, bounds.w, bounds.h); } }; // Clears a rectangle in the Canvas element or the whole Canvas p.clear = function clear(x, y, width, height) { if (arguments.length === 0) { curContext.clearRect(0, 0, p.width, p.height); } else { curContext.clearRect(x, y, width, height); } }; p.tint = function tint() { var tintColor = p.color.apply(this, arguments); var r = p.red(tintColor) / colorModeX; var g = p.green(tintColor) / colorModeY; var b = p.blue(tintColor) / colorModeZ; var a = p.alpha(tintColor) / colorModeA; curTint = function(obj) { var data = obj.data, length = 4 * obj.width * obj.height; for (var i = 0; i < length;) { data[i++] *= r; data[i++] *= g; data[i++] *= b; data[i++] *= a; } }; }; p.noTint = function noTint() { curTint = function() {}; }; p.copy = function copy(src, sx, sy, sw, sh, dx, dy, dw, dh) { if (arguments.length === 8) { p.copy(p, src, sx, sy, sw, sh, dx, dy, dw); return; } p.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, p.REPLACE); }; p.blend = function blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode, pimgdest) { if (arguments.length === 9) { p.blend(p, src, sx, sy, sw, sh, dx, dy, dw, dh); } else if (arguments.length === 10 || arguments.length === 11) { var sx2 = sx + sw; var sy2 = sy + sh; var dx2 = dx + dw; var dy2 = dy + dh; var dest; // check if pimgdest is there and pixels, if so this was a call from pimg.blend if (arguments.length === 10) { p.loadPixels(); dest = p; } else if (arguments.length === 11 && pimgdest && pimgdest.imageData) { dest = pimgdest; } if (src === p) { if (p.intersect(sx, sy, sx2, sy2, dx, dy, dx2, dy2)) { p.blit_resize(p.get(sx, sy, sx2 - sx, sy2 - sy), 0, 0, sx2 - sx - 1, sy2 - sy - 1, dest.imageData.data, dest.width, dest.height, dx, dy, dx2, dy2, mode); } else { // same as below, except skip the loadPixels() because it'd be redundant p.blit_resize(src, sx, sy, sx2, sy2, dest.imageData.data, dest.width, dest.height, dx, dy, dx2, dy2, mode); } } else { src.loadPixels(); p.blit_resize(src, sx, sy, sx2, sy2, dest.imageData.data, dest.width, dest.height, dx, dy, dx2, dy2, mode); } if (arguments.length === 10) { p.updatePixels(); } } }; // shared variables for blit_resize(), filter_new_scanline(), filter_bilinear() // change this in the future to not be exposed to p p.shared = { fracU: 0, ifU: 0, fracV: 0, ifV: 0, u1: 0, u2: 0, v1: 0, v2: 0, sX: 0, sY: 0, iw: 0, iw1: 0, ih1: 0, ul: 0, ll: 0, ur: 0, lr: 0, cUL: 0, cLL: 0, cUR: 0, cLR: 0, srcXOffset: 0, srcYOffset: 0, r: 0, g: 0, b: 0, a: 0, srcBuffer: null }; p.intersect = function intersect(sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2) { var sw = sx2 - sx1 + 1; var sh = sy2 - sy1 + 1; var dw = dx2 - dx1 + 1; var dh = dy2 - dy1 + 1; if (dx1 < sx1) { dw += dx1 - sx1; if (dw > sw) { dw = sw; } } else { var w = sw + sx1 - dx1; if (dw > w) { dw = w; } } if (dy1 < sy1) { dh += dy1 - sy1; if (dh > sh) { dh = sh; } } else { var h = sh + sy1 - dy1; if (dh > h) { dh = h; } } return ! (dw <= 0 || dh <= 0); }; p.filter_new_scanline = function filter_new_scanline() { p.shared.sX = p.shared.srcXOffset; p.shared.fracV = p.shared.srcYOffset & p.PREC_MAXVAL; p.shared.ifV = p.PREC_MAXVAL - p.shared.fracV; p.shared.v1 = (p.shared.srcYOffset >> p.PRECISIONB) * p.shared.iw; p.shared.v2 = Math.min((p.shared.srcYOffset >> p.PRECISIONB) + 1, p.shared.ih1) * p.shared.iw; }; p.filter_bilinear = function filter_bilinear() { p.shared.fracU = p.shared.sX & p.PREC_MAXVAL; p.shared.ifU = p.PREC_MAXVAL - p.shared.fracU; p.shared.ul = (p.shared.ifU * p.shared.ifV) >> p.PRECISIONB; p.shared.ll = (p.shared.ifU * p.shared.fracV) >> p.PRECISIONB; p.shared.ur = (p.shared.fracU * p.shared.ifV) >> p.PRECISIONB; p.shared.lr = (p.shared.fracU * p.shared.fracV) >> p.PRECISIONB; p.shared.u1 = (p.shared.sX >> p.PRECISIONB); p.shared.u2 = Math.min(p.shared.u1 + 1, p.shared.iw1); // get color values of the 4 neighbouring texels // changed for 0.9 var cULoffset = (p.shared.v1 + p.shared.u1) * 4; var cURoffset = (p.shared.v1 + p.shared.u2) * 4; var cLLoffset = (p.shared.v2 + p.shared.u1) * 4; var cLRoffset = (p.shared.v2 + p.shared.u2) * 4; p.shared.cUL = p.color.toInt(p.shared.srcBuffer[cULoffset], p.shared.srcBuffer[cULoffset+1], p.shared.srcBuffer[cULoffset+2], p.shared.srcBuffer[cULoffset+3]); p.shared.cUR = p.color.toInt(p.shared.srcBuffer[cURoffset], p.shared.srcBuffer[cURoffset+1], p.shared.srcBuffer[cURoffset+2], p.shared.srcBuffer[cURoffset+3]); p.shared.cLL = p.color.toInt(p.shared.srcBuffer[cLLoffset], p.shared.srcBuffer[cLLoffset+1], p.shared.srcBuffer[cLLoffset+2], p.shared.srcBuffer[cLLoffset+3]); p.shared.cLR = p.color.toInt(p.shared.srcBuffer[cLRoffset], p.shared.srcBuffer[cLRoffset+1], p.shared.srcBuffer[cLRoffset+2], p.shared.srcBuffer[cLRoffset+3]); p.shared.r = ((p.shared.ul * ((p.shared.cUL & p.RED_MASK) >> 16) + p.shared.ll * ((p.shared.cLL & p.RED_MASK) >> 16) + p.shared.ur * ((p.shared.cUR & p.RED_MASK) >> 16) + p.shared.lr * ((p.shared.cLR & p.RED_MASK) >> 16)) << p.PREC_RED_SHIFT) & p.RED_MASK; p.shared.g = ((p.shared.ul * (p.shared.cUL & p.GREEN_MASK) + p.shared.ll * (p.shared.cLL & p.GREEN_MASK) + p.shared.ur * (p.shared.cUR & p.GREEN_MASK) + p.shared.lr * (p.shared.cLR & p.GREEN_MASK)) >>> p.PRECISIONB) & p.GREEN_MASK; p.shared.b = (p.shared.ul * (p.shared.cUL & p.BLUE_MASK) + p.shared.ll * (p.shared.cLL & p.BLUE_MASK) + p.shared.ur * (p.shared.cUR & p.BLUE_MASK) + p.shared.lr * (p.shared.cLR & p.BLUE_MASK)) >>> p.PRECISIONB; p.shared.a = ((p.shared.ul * ((p.shared.cUL & p.ALPHA_MASK) >>> 24) + p.shared.ll * ((p.shared.cLL & p.ALPHA_MASK) >>> 24) + p.shared.ur * ((p.shared.cUR & p.ALPHA_MASK) >>> 24) + p.shared.lr * ((p.shared.cLR & p.ALPHA_MASK) >>> 24)) << p.PREC_ALPHA_SHIFT) & p.ALPHA_MASK; return p.shared.a | p.shared.r | p.shared.g | p.shared.b; }; p.blit_resize = function blit_resize(img, srcX1, srcY1, srcX2, srcY2, destPixels, screenW, screenH, destX1, destY1, destX2, destY2, mode) { var x, y; // iterator vars if (srcX1 < 0) { srcX1 = 0; } if (srcY1 < 0) { srcY1 = 0; } if (srcX2 >= img.width) { srcX2 = img.width - 1; } if (srcY2 >= img.height) { srcY2 = img.height - 1; } var srcW = srcX2 - srcX1; var srcH = srcY2 - srcY1; var destW = destX2 - destX1; var destH = destY2 - destY1; var smooth = true; // may as well go with the smoothing these days if (!smooth) { srcW++; srcH++; } if (destW <= 0 || destH <= 0 || srcW <= 0 || srcH <= 0 || destX1 >= screenW || destY1 >= screenH || srcX1 >= img.width || srcY1 >= img.height) { return; } var dx = Math.floor(srcW / destW * p.PRECISIONF); var dy = Math.floor(srcH / destH * p.PRECISIONF); p.shared.srcXOffset = Math.floor(destX1 < 0 ? -destX1 * dx : srcX1 * p.PRECISIONF); p.shared.srcYOffset = Math.floor(destY1 < 0 ? -destY1 * dy : srcY1 * p.PRECISIONF); if (destX1 < 0) { destW += destX1; destX1 = 0; } if (destY1 < 0) { destH += destY1; destY1 = 0; } destW = Math.min(destW, screenW - destX1); destH = Math.min(destH, screenH - destY1); // changed in 0.9, TODO var destOffset = destY1 * screenW + destX1; var destColor; p.shared.srcBuffer = img.imageData.data; if (smooth) { // use bilinear filtering p.shared.iw = img.width; p.shared.iw1 = img.width - 1; p.shared.ih1 = img.height - 1; switch (mode) { case p.BLEND: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.blend(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.blend(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.ADD: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.add(destColor, p.filter_bilinear())); destColor = p.color.toArray(p.modes.add(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.add(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.SUBTRACT: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.subtract(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.subtract(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.LIGHTEST: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.lightest(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.lightest(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.DARKEST: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.darkest(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.darkest(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.REPLACE: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.filter_bilinear()); //destPixels[destOffset + x] = p.filter_bilinear(); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.DIFFERENCE: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.difference(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.difference(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.EXCLUSION: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.exclusion(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.exclusion(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.MULTIPLY: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.multiply(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.multiply(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.SCREEN: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.screen(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.screen(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.OVERLAY: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.overlay(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.overlay(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.HARD_LIGHT: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.hard_light(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.hard_light(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.SOFT_LIGHT: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.soft_light(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.soft_light(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.DODGE: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.dodge(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.dodge(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; case p.BURN: for (y = 0; y < destH; y++) { p.filter_new_scanline(); for (x = 0; x < destW; x++) { // changed for 0.9 destColor = p.color.toInt(destPixels[(destOffset + x) * 4], destPixels[((destOffset + x) * 4) + 1], destPixels[((destOffset + x) * 4) + 2], destPixels[((destOffset + x) * 4) + 3]); destColor = p.color.toArray(p.modes.burn(destColor, p.filter_bilinear())); //destPixels[destOffset + x] = p.modes.burn(destPixels[destOffset + x], p.filter_bilinear()); destPixels[(destOffset + x) * 4] = destColor[0]; destPixels[(destOffset + x) * 4 + 1] = destColor[1]; destPixels[(destOffset + x) * 4 + 2] = destColor[2]; destPixels[(destOffset + x) * 4 + 3] = destColor[3]; p.shared.sX += dx; } destOffset += screenW; p.shared.srcYOffset += dy; } break; } } }; //////////////////////////////////////////////////////////////////////////// // Font handling //////////////////////////////////////////////////////////////////////////// // Loads a font from an SVG or Canvas API p.loadFont = function loadFont(name) { if (name.indexOf(".svg") === -1) { return { name: name, width: function(str) { if (curContext.mozMeasureText) { return curContext.mozMeasureText( typeof str === "number" ? String.fromCharCode(str) : str) / curTextSize; } else { return 0; } } }; } else { // If the font is a glyph, calculate by SVG table var font = p.loadGlyphs(name); return { name: name, glyph: true, units_per_em: font.units_per_em, horiz_adv_x: 1 / font.units_per_em * font.horiz_adv_x, ascent: font.ascent, descent: font.descent, width: function(str) { var width = 0; var len = str.length; for (var i = 0; i < len; i++) { try { width += parseFloat(p.glyphLook(p.glyphTable[name], str[i]).horiz_adv_x); } catch(e) { Processing.debug(e); } } return width / p.glyphTable[name].units_per_em; } }; } }; p.createFont = function(name, size) {}; // Sets a 'current font' for use p.textFont = function textFont(name, size) { curTextFont = name; p.textSize(size); }; // Sets the font size p.textSize = function textSize(size) { if (size) { curTextSize = size; } }; p.textAlign = function textAlign() {}; // A lookup table for characters that can not be referenced by Object p.glyphLook = function glyphLook(font, chr) { try { switch (chr) { case "1": return font.one; case "2": return font.two; case "3": return font.three; case "4": return font.four; case "5": return font.five; case "6": return font.six; case "7": return font.seven; case "8": return font.eight; case "9": return font.nine; case "0": return font.zero; case " ": return font.space; case "$": return font.dollar; case "!": return font.exclam; case '"': return font.quotedbl; case "#": return font.numbersign; case "%": return font.percent; case "&": return font.ampersand; case "'": return font.quotesingle; case "(": return font.parenleft; case ")": return font.parenright; case "*": return font.asterisk; case "+": return font.plus; case ",": return font.comma; case "-": return font.hyphen; case ".": return font.period; case "/": return font.slash; case "_": return font.underscore; case ":": return font.colon; case ";": return font.semicolon; case "<": return font.less; case "=": return font.equal; case ">": return font.greater; case "?": return font.question; case "@": return font.at; case "[": return font.bracketleft; case "\\": return font.backslash; case "]": return font.bracketright; case "^": return font.asciicircum; case "`": return font.grave; case "{": return font.braceleft; case "|": return font.bar; case "}": return font.braceright; case "~": return font.asciitilde; // If the character is not 'special', access it by object reference default: return font[chr]; } } catch(e) { Processing.debug(e); } }; // Print some text to the Canvas p.text = function text() { if (typeof arguments[0] !== 'undefined') { var str = arguments[0], x, y, z, pos, width, height; if (typeof str === 'number' && (str + "").indexOf('.') >= 0) { // Make sure .15 rounds to .1, but .151 rounds to .2. if ((str * 1000) - Math.floor(str * 1000) === 0.5) { str = str - 0.0001; } str = str.toFixed(3); } str = str.toString(); if (arguments.length === 1) { // for text( str ) p.text(str, lastTextPos[0], lastTextPos[1]); } else if (arguments.length === 3) { // for text( str, x, y) text(str, arguments[1], arguments[2], 0); } else if (arguments.length === 4) { // for text( str, x, y, z) x = arguments[1]; y = arguments[2]; z = arguments[3]; do { pos = str.indexOf("\n"); if (pos !== -1) { if (pos !== 0) { text(str.substring(0, pos)); } y += curTextSize; str = str.substring(pos + 1, str.length); } } while (pos !== -1); // TODO: handle case for 3d text if (p.use3DContext) { } width = 0; // If the font is a standard Canvas font... if (!curTextFont.glyph) { if (str && (curContext.fillText || curContext.mozDrawText)) { curContext.save(); curContext.font = curContext.mozTextStyle = curTextSize + "px " + curTextFont.name; if (curContext.fillText) { curContext.fillText(str, x, y); width = curContext.measureText(str).width; } else if (curContext.mozDrawText) { curContext.translate(x, y); curContext.mozDrawText(str); width = curContext.mozMeasureText(str); } curContext.restore(); } } else { // If the font is a Batik SVG font... var font = p.glyphTable[curTextFont.name]; curContext.save(); curContext.translate(x, y + curTextSize); var upem = font.units_per_em, newScale = 1 / upem * curTextSize; curContext.scale(newScale, newScale); var len = str.length; for (var i = 0; i < len; i++) { // Test character against glyph table try { p.glyphLook(font, str[i]).draw(); } catch(e) { Processing.debug(e); } } curContext.restore(); } // TODO: Handle case for 3d text if (p.use3DContext) { } lastTextPos[0] = x + width; lastTextPos[1] = y; lastTextPos[2] = z; } else if (arguments.length === 5) { // for text( str, x, y , width, height) text(str, arguments[1], arguments[2], arguments[3], arguments[4], 0); } else if (arguments.length === 6) { // for text( stringdata, x, y , width, height, z) x = arguments[1]; y = arguments[2]; width = arguments[3]; height = arguments[4]; z = arguments[5]; if (str.length > 0) { if (curTextSize > height) { return; } var spaceMark = -1; var start = 0; var lineWidth = 0; var letterWidth = 0; var textboxWidth = width; lastTextPos[0] = x; lastTextPos[1] = y - 0.4 * curTextSize; curContext.font = curTextSize + "px " + curTextFont.name; for (var j = 0; j < str.length; j++) { if (curContext.fillText) { letterWidth = curContext.measureText(str[j]).width; } else if (curContext.mozDrawText) { letterWidth = curContext.mozMeasureText(str[j]); } if (str[j] !== "\n" && (str[j] === " " || (str[j - 1] !== " " && str[j + 1] === " ") || lineWidth + 2 * letterWidth < textboxWidth)) { // check a line of text if (str[j] === " ") { spaceMark = j; } lineWidth += letterWidth; } else { // draw a line of text if (start === spaceMark + 1) { // in case a whole line without a space spaceMark = j; } lastTextPos[0] = x; lastTextPos[1] = lastTextPos[1] + curTextSize; if (str[j] === "\n") { text(str.substring(start, j)); start = j + 1; } else { text(str.substring(start, spaceMark + 1)); start = spaceMark + 1; } lineWidth = 0; if (lastTextPos[1] + 2 * curTextSize > y + height + 0.6 * curTextSize) { // stop if no enough space for one more line draw return; } j = start - 1; } } if (start !== str.length) { // draw the last line lastTextPos[0] = x; lastTextPos[1] = lastTextPos[1] + curTextSize; for (; start < str.length; start++) { text(str[start]); } } } // end str != "" } // end arguments.length == 6 } }; // Load Batik SVG Fonts and parse to pre-def objects for quick rendering p.loadGlyphs = function loadGlyph(url) { var x, y, cx, cy, nx, ny, d, a, lastCom, lenC, horiz_adv_x, getXY = '[0-9\\-]+', path; // Return arrays of SVG commands and coords // get this to use p.matchAll() - will need to work around the lack of null return var regex = function regex(needle, hay) { var i = 0, results = [], latest, regexp = new RegExp(needle, "g"); latest = results[i] = regexp.exec(hay); while (latest) { i++; latest = results[i] = regexp.exec(hay); } return results; }; var buildPath = function buildPath(d) { var c = regex("[A-Za-z][0-9\\- ]+|Z", d); // Begin storing path object path = "var path={draw:function(){curContext.beginPath();curContext.save();"; x = 0; y = 0; cx = 0; cy = 0; nx = 0; ny = 0; d = 0; a = 0; lastCom = ""; lenC = c.length - 1; // Loop through SVG commands translating to canvas eqivs functions in path object for (var j = 0; j < lenC; j++) { var com = c[j][0], xy = regex(getXY, com); switch (com[0]) { case "M": //curContext.moveTo(x,-y); x = parseFloat(xy[0][0]); y = parseFloat(xy[1][0]); path += "curContext.moveTo(" + x + "," + (-y) + ");"; break; case "L": //curContext.lineTo(x,-y); x = parseFloat(xy[0][0]); y = parseFloat(xy[1][0]); path += "curContext.lineTo(" + x + "," + (-y) + ");"; break; case "H": //curContext.lineTo(x,-y) x = parseFloat(xy[0][0]); path += "curContext.lineTo(" + x + "," + (-y) + ");"; break; case "V": //curContext.lineTo(x,-y); y = parseFloat(xy[0][0]); path += "curContext.lineTo(" + x + "," + (-y) + ");"; break; case "T": //curContext.quadraticCurveTo(cx,-cy,nx,-ny); nx = parseFloat(xy[0][0]); ny = parseFloat(xy[1][0]); if (lastCom === "Q" || lastCom === "T") { d = Math.sqrt(Math.pow(x - cx, 2) + Math.pow(cy - y, 2)); a = Math.PI + Math.atan2(cx - x, cy - y); cx = x + (Math.sin(a) * (d)); cy = y + (Math.cos(a) * (d)); } else { cx = x; cy = y; } path += "curContext.quadraticCurveTo(" + cx + "," + (-cy) + "," + nx + "," + (-ny) + ");"; x = nx; y = ny; break; case "Q": //curContext.quadraticCurveTo(cx,-cy,nx,-ny); cx = parseFloat(xy[0][0]); cy = parseFloat(xy[1][0]); nx = parseFloat(xy[2][0]); ny = parseFloat(xy[3][0]); path += "curContext.quadraticCurveTo(" + cx + "," + (-cy) + "," + nx + "," + (-ny) + ");"; x = nx; y = ny; break; case "Z": //curContext.closePath(); path += "curContext.closePath();"; break; } lastCom = com[0]; } path += "doStroke?curContext.stroke():0;"; path += "doFill?curContext.fill():0;"; path += "curContext.restore();"; path += "curContext.translate(" + horiz_adv_x + ",0);"; path += "}}"; return path; }; // Parse SVG font-file into block of Canvas commands var parseSVGFont = function parseSVGFontse(svg) { // Store font attributes var font = svg.getElementsByTagName("font"); p.glyphTable[url].horiz_adv_x = font[0].getAttribute("horiz-adv-x"); var font_face = svg.getElementsByTagName("font-face")[0]; p.glyphTable[url].units_per_em = parseFloat(font_face.getAttribute("units-per-em")); p.glyphTable[url].ascent = parseFloat(font_face.getAttribute("ascent")); p.glyphTable[url].descent = parseFloat(font_face.getAttribute("descent")); var glyph = svg.getElementsByTagName("glyph"), len = glyph.length; // Loop through each glyph in the SVG for (var i = 0; i < len; i++) { // Store attributes for this glyph var unicode = glyph[i].getAttribute("unicode"); var name = glyph[i].getAttribute("glyph-name"); horiz_adv_x = glyph[i].getAttribute("horiz-adv-x"); if (horiz_adv_x === null) { horiz_adv_x = p.glyphTable[url].horiz_adv_x; } d = glyph[i].getAttribute("d"); // Split path commands in glpyh if (d !== undefined) { path = buildPath(d); eval(path); // Store glyph data to table object p.glyphTable[url][name] = { name: name, unicode: unicode, horiz_adv_x: horiz_adv_x, draw: path.draw }; } } // finished adding glyphs to table }; // Load and parse Batik SVG font as XML into a Processing Glyph object var loadXML = function loadXML() { var xmlDoc; try { xmlDoc = document.implementation.createDocument("", "", null); } catch(e_fx_op) { Processing.debug(e_fx_op.message); return; } try { xmlDoc.async = false; xmlDoc.load(url); parseSVGFont(xmlDoc.getElementsByTagName("svg")[0]); } catch(e_sf_ch) { // Google Chrome, Safari etc. Processing.debug(e_sf_ch); try { var xmlhttp = new window.XMLHttpRequest(); xmlhttp.open("GET", url, false); xmlhttp.send(null); parseSVGFont(xmlhttp.responseXML.documentElement); } catch(e) { Processing.debug(e_sf_ch); } } }; // Create a new object in glyphTable to store this font p.glyphTable[url] = {}; // Begin loading the Batik SVG font... loadXML(url); // Return the loaded font for attribute grabbing return p.glyphTable[url]; }; //////////////////////////////////////////////////////////////////////////// // Class methods //////////////////////////////////////////////////////////////////////////// p.extendClass = function extendClass(obj, args, fn) { if (arguments.length === 3) { fn.apply(obj, args); } else { args.call(obj); } }; p.addMethod = function addMethod(object, name, fn) { if (object[name]) { var args = fn.length, oldfn = object[name]; object[name] = function() { if (arguments.length === args) { return fn.apply(this, arguments); } else { return oldfn.apply(this, arguments); } }; } else { object[name] = fn; } }; ////////////////////////////////////////////////////////////////////////// // Event handling ////////////////////////////////////////////////////////////////////////// p.pjs.eventHandlers = []; function attach(elem, type, fn) { if (elem.addEventListener) { elem.addEventListener(type, fn, false); } else { elem.attachEvent("on" + type, fn); } p.pjs.eventHandlers.push([elem, type, fn]); } attach(curElement, "mousemove", function(e) { var element = curElement, offsetX = 0, offsetY = 0; p.pmouseX = p.mouseX; p.pmouseY = p.mouseY; if (element.offsetParent) { do { offsetX += element.offsetLeft; offsetY += element.offsetTop; } while (element = element.offsetParent); } // Dropping support for IE clientX and clientY, switching to pageX and pageY so we don't have to calculate scroll offset. // Removed in ticket #184. See rev: 2f106d1c7017fed92d045ba918db47d28e5c16f4 p.mouseX = e.pageX - offsetX; p.mouseY = e.pageY - offsetY; if (p.mouseMoved && !mousePressed) { p.mouseMoved(); } if (mousePressed && p.mouseDragged) { p.mouseDragged(); p.mouseDragging = true; } }); attach(curElement, "mouseout", function(e) { }); attach(curElement, "mousedown", function(e) { mousePressed = true; p.mouseDragging = false; switch (e.which) { case 1: p.mouseButton = p.LEFT; break; case 2: p.mouseButton = p.CENTER; break; case 3: p.mouseButton = p.RIGHT; break; } p.mouseDown = true; if (typeof p.mousePressed === "function") { p.mousePressed(); } else { p.mousePressed = true; } }); attach(curElement, "mouseup", function(e) { mousePressed = false; if (p.mouseClicked && !p.mouseDragging) { p.mouseClicked(); } if (typeof p.mousePressed !== "function") { p.mousePressed = false; } if (p.mouseReleased) { p.mouseReleased(); } }); var mouseWheelHandler = function(e) { var delta = 0; if (e.wheelDelta) { delta = e.wheelDelta / 120; if (window.opera) { delta = -delta; } } else if (e.detail) { delta = -e.detail / 3; } p.mouseScroll = delta; if (delta && typeof p.mouseScrolled === 'function') { p.mouseScrolled(); } }; // Support Gecko and non-Gecko scroll events attach(document, 'DOMMouseScroll', mouseWheelHandler); attach(document, 'mousewheel', mouseWheelHandler); attach(document, "keydown", function(e) { keyPressed = true; p.keyCode = null; p.key = e.keyCode; // Letters if (e.keyCode >= 65 && e.keyCode <= 90) { // A-Z // Keys return ASCII for upcased letters. // Convert to downcase if shiftKey is not pressed. if (!e.shiftKey) { p.key += 32; } } // Numbers and their shift-symbols else if (e.keyCode >= 48 && e.keyCode <= 57) { // 0-9 if (e.shiftKey) { switch (e.keyCode) { case 49: p.key = 33; break; // ! case 50: p.key = 64; break; // @ case 51: p.key = 35; break; // # case 52: p.key = 36; break; // $ case 53: p.key = 37; break; // % case 54: p.key = 94; break; // ^ case 55: p.key = 38; break; // & case 56: p.key = 42; break; // * case 57: p.key = 40; break; // ( case 48: p.key = 41; break; // ) } } } // Coded keys else if (codedKeys.indexOf(e.keyCode) >= 0) { // SHIFT, CONTROL, ALT, LEFT, RIGHT, UP, DOWN p.key = p.CODED; p.keyCode = e.keyCode; } // Symbols and their shift-symbols else { if (e.shiftKey) { switch (e.keyCode) { case 107: p.key = 43; break; // + case 219: p.key = 123; break; // { case 221: p.key = 125; break; // } case 222: p.key = 34; break; // " } } else { switch (e.keyCode) { case 188: p.key = 44; break; // , case 109: p.key = 45; break; // - case 190: p.key = 46; break; // . case 191: p.key = 47; break; // / case 192: p.key = 96; break; // ~ case 219: p.key = 91; break; // [ case 220: p.key = 92; break; // \ case 221: p.key = 93; break; // ] case 222: p.key = 39; break; // ' } } } if (typeof p.keyPressed === "function") { p.keyPressed(); } else { p.keyPressed = true; } }); attach(document, "keyup", function(e) { keyPressed = false; if (typeof p.keyPressed !== "function") { p.keyPressed = false; } if (p.keyReleased) { p.keyReleased(); } }); attach(document, "keypress", function (e) { if (p.keyTyped) { p.keyTyped(); } }); // Place-holder for debugging function p.debug = function(e) {}; // Get the DOM element if string was passed if (typeof curElement === "string") { curElement = document.getElementById(curElement); } // Send aCode Processing syntax to be converted to JavaScript if (aCode) { var parsedCode = typeof aCode === "function" ? undefined : Processing.parse(aCode, p); if (!this.use3DContext) { // Setup default 2d canvas context. curContext = curElement.getContext('2d'); modelView = new PMatrix2D(); // Canvas has trouble rendering single pixel stuff on whole-pixel // counts, so we slightly offset it (this is super lame). curContext.translate(0.5, 0.5); curContext.lineCap = 'round'; // Set default stroke and fill color p.stroke(0); p.fill(255); p.noSmooth(); p.disableContextMenu(); } // Step through the libraries that were attached at doc load... for (var i in Processing.lib) { if (Processing.lib) { // Init the libraries in the context of this p_instance Processing.lib[i].call(this); } } var localizedProperties = ""; for (var propertyName in p) { localizedProperties += "var " + propertyName + "=__p__." + propertyName + ";"; if (typeof p[propertyName] !== "function" || typeof p[propertyName] !== "object") { localizedProperties += "__p__.__defineGetter__('" + propertyName + "',function(){return " + propertyName + ";});" + "__p__.__defineSetter__('" + propertyName + "',function(v){" + propertyName + "=v;});"; } } var executeSketch = function() { // Don't start until all specified images in the cache are preloaded if (!p.pjs.imageCache.pending) { if(typeof aCode === "function") { aCode(p); } else { eval (" (function(__p__) { " + localizedProperties + parsedCode + " if (setup) {" + " __p__.setup = setup;" + " setup();" + " }" + " if (draw) {" + " __p__.draw = draw;" + " if (!doLoop) {" + " redraw();" + " } else {" + " loop();" + " }" + " }" + " })(p);" ); } } else { window.setTimeout(executeSketch, 10); } }; // The parser adds custom methods to the processing context executeSketch(); } }; // Share lib space Processing.lib = {}; // Parse Processing (Java-like) syntax to JavaScript syntax with Regex Processing.parse = function parse(aCode, p) { // Function to grab all code in the opening and closing of two characters var nextBrace = function(right, openChar, closeChar) { var rest = right, position = 0, leftCount = 1, rightCount = 0; while (leftCount !== rightCount) { var nextLeft = rest.indexOf(openChar), nextRight = rest.indexOf(closeChar); if (nextLeft < nextRight && nextLeft !== -1) { leftCount++; rest = rest.slice(nextLeft + 1); position += nextLeft + 1; } else { rightCount++; rest = rest.slice(nextRight + 1); position += nextRight + 1; } } return right.slice(0, position - 1); }; // Force characters-as-bytes to work. //aCode = aCode.replace(/('(.){1}')/g, "$1.charCodeAt(0)"); aCode = aCode.replace(/'.{1}'/g, function(all) { return "(new Char(" + all + "))"; }); // Parse out @pjs directive, if any. var dm = /\/\*\s*@pjs\s+((?:[^\*]|\*+[^\*\/])*)\*\//g.exec(aCode); if (dm && dm.length === 2) { var directives = dm.splice(1, 2)[0].replace('\n', '').replace('\r', '').split(';'); // We'll L/RTrim, and also remove any surrounding double quotes (e.g., just take string contents) var clean = function(s) { return s.replace(/^\s*\"?/, '').replace(/\"?\s*$/, ''); }; for (var i = 0, dl = directives.length; i < dl; i++) { var pair = directives[i].split('='); if (pair && pair.length === 2) { var key = clean(pair[0]); var value = clean(pair[1]); // A few directives require work beyond storying key/value pairings if (key === "preload") { var list = value.split(','); // All pre-loaded images will get put in imageCache, keyed on filename for (var j = 0, ll = list.length; j < ll; j++) { var imageName = clean(list[j]); var img = new Image(); img.onload = (function() { return function() { p.pjs.imageCache.pending--; }; }()); p.pjs.imageCache.pending++; p.pjs.imageCache[imageName] = img; img.src = imageName; } } else if (key === "opaque") { p.canvas.mozOpaque = value === "true"; } else { p.pjs[key] = value; } } } aCode = aCode.replace(dm[0], ''); } // Saves all strings into an array // masks all strings into <STRING n> // to be replaced with the array strings after parsing is finished var strings = []; aCode = aCode.replace(/(["'])(\\\1|.)*?(\1)/g, function(all) { strings.push(all); return "<STRING " + (strings.length - 1) + ">"; }); // Windows newlines cause problems: aCode = aCode.replace(/\r\n?/g, "\n"); // Remove multi-line comments aCode = aCode.replace(/\/\*[\s\S]*?\*\//g, ""); // Remove end-of-line comments aCode = aCode.replace(/\/\/.*\n/g, "\n"); // Weird parsing errors with % aCode = aCode.replace(/([^\s])%([^\s])/g, "$1 % $2"); // Since frameRate() and frameRate are different things, // we need to differentiate them somehow. So when we parse // the Processing.js source, replace frameRate so it isn't // confused with frameRate(). aCode = aCode.replace(/(\s*=\s*|\(*\s*)frameRate(\s*\)+?|\s*;)/, "$1p.FRAME_RATE$2"); // Simple convert a function-like thing to function aCode = aCode.replace(/(?:static )?(\w+(?:\[\])*\s+)(\w+)\s*(\([^\)]*\)\s*\{)/g, function(all, type, name, args) { if (name === "if" || name === "for" || name === "while" || type === "public ") { return all; } else { return "PROCESSING." + name + " = function " + name + args; } }); var matchMethod = /PROCESSING\.(\w+ = function \w+\([^\)]*\)\s*\{)/, mc; while ((mc = aCode.match(matchMethod))) { var prev = RegExp.leftContext, allNext = RegExp.rightContext, next = nextBrace(allNext, "{", "}"); aCode = prev + "processing." + mc[1] + next + "};" + allNext.slice(next.length + 1); } // Delete import statements, ie. import processing.video.*; // https://processing-js.lighthouseapp.com/projects/41284/tickets/235-fix-parsing-of-java-import-statement aCode = aCode.replace(/import\s+(.+);/g, ""); //replace catch (IOException e) to catch (e) aCode = aCode.replace(/catch\s*\(\W*\w*\s+(\w*)\W*\)/g, "catch ($1)"); //delete the multiple catch block var catchBlock = /(catch[^\}]*\})\W*catch[^\}]*\}/; while (catchBlock.test(aCode)) { aCode = aCode.replace(new RegExp(catchBlock), "$1"); } Error.prototype.printStackTrace = function() { this.toString(); }; // changes pixels[n] into pixels.getPixels(n) // and pixels[n] = n2 into pixels.setPixels(n, n2) var matchPixels = /pixels\s*\[/, mp; while ((mp = aCode.match(matchPixels))) { var left = RegExp.leftContext, allRest = RegExp.rightContext, rest = nextBrace(allRest, "[", "]"), getOrSet = "getPixel"; allRest = allRest.slice(rest.length + 1); allRest = (function(){ return allRest.replace(/^\s*=([^;]*)([;])/, function(all, middle, end){ rest += ", " + middle; getOrSet = "setPixel"; return end; }); }()); aCode = left + "pixels." + getOrSet + "(" + rest + ")" + allRest; } // changes pixel.length to pixels.getLength() aCode = aCode.replace(/pixels.length/g, "pixels.getLength()"); // Force .length() to be .length aCode = aCode.replace(/\.length\(\)/g, ".length"); // foo( int foo, float bar ) aCode = aCode.replace(/([\(,]\s*)(\w+)((?:\[\])+|\s+)\s*(\w+\s*[\),])/g, "$1$4"); aCode = aCode.replace(/([\(,]\s*)(\w+)((?:\[\])+|\s+)\s*(\w+\s*[\),])/g, "$1$4"); // float[] foo = new float[5]; aCode = aCode.replace(/new\s+(\w+)\s*((?:\[(?:[^\]]*)\])+)\s*(\{[^;]*\}\s*;)*/g, function(all, name, args, initVars) { if (initVars) { return initVars.replace(/\{/g, "[").replace(/\}/g, "]"); } else { return "new ArrayList(" + args.replace(/\[\]/g, "[0]").slice(1, -1).split("][").join(", ") + ");"; } }); // What does this do? This does the same thing as "Fix Array[] foo = {...} to [...]" below aCode = aCode.replace(/(?:static\s+)?\w+\[\]\s*(\w+)\[?\]?\s*=\s*\{.*?\};/g, function(all) { return all.replace(/\{/g, "[").replace(/\}/g, "]"); }); // int|float foo; var intFloat = /(\s*(?:int|float)\s+(?!\[\])*(?:\s*|[^\(;]*?,\s*))([a-zA-Z]\w*)\s*(,|;)/i; while (intFloat.test(aCode)) { aCode = (function() { return aCode.replace(new RegExp(intFloat), function(all, type, name, sep) { return type + " " + name + " = 0" + sep; }); }()); } // float foo = 5; aCode = aCode.replace(/(?:final\s+)?(\w+)((?:\[\s*\])+|\s)\s*(\w+)\[?\]?(\s*[=,;])/g, function(all, type, arr, name, sep) { if (type === "return" || type === "else") { return all; } else { return "var " + name + sep; } }); // Fix Array[] foo = {...} to [...] aCode = aCode.replace(/\=\s*\{((.|\s)*?\};)/g, function(all, data) { return "= [" + data.replace(/\{/g, "[").replace(/\}/g, "]"); }); // super() is a reserved word aCode = aCode.replace(/super\(/g, "superMethod("); // Stores the variables and mathods of a single class var SuperClass = function(name){ return { className: name, classVariables: "", classFunctions: [] }; }; var arrayOfSuperClasses = []; // implements Int1, Int2 aCode = aCode.replace(/implements\s+(\w+\s*(,\s*\w+\s*)*)\s*\{/g, function(all, interfaces) { var names = interfaces.replace(/\s+/g, "").split(","); return "{ var __psj_interfaces = new ArrayList([\"" + names.join("\", \"") + "\"]);"; }); // Simply turns an interface into a class aCode = aCode.replace(/interface/g, "class"); var classes = ["int", "float", "boolean", "String", "byte", "double", "long", "ArrayList"]; var classReplace = function(all, name, extend) { classes.push(name); // Move arguments up from constructor return "function " + name + "() {\n " + (extend ? "var __self=this;function superMethod(){extendClass(__self,arguments," + extend + ");}\n" : "") + (extend ? "extendClass(this, " + extend + ");\n" : "") + "<CLASS " + name + " " + extend + ">"; }; var matchClasses = /(?:public\s+|abstract\s+|static\s+)*class\s+?(\w+)\s*(?:extends\s*(\w+)\s*)?\{/g; aCode = aCode.replace(matchClasses, classReplace); var matchClass = /<CLASS (\w+) (\w+)?>/, m; while ((m = aCode.match(matchClass))) { var left = RegExp.leftContext, allRest = RegExp.rightContext, rest = nextBrace(allRest, "{", "}"), className = m[1], thisSuperClass = new SuperClass(className), extendingClass = m[2]; allRest = allRest.slice(rest.length + 1); // Fix class method names // this.collide = function() { ... } rest = (function() { return rest.replace(/(?:public\s+)?processing.\w+ = function (\w+)\(([^\)]*?)\)/g, function(all, name, args) { thisSuperClass.classFunctions.push(name + "|"); return "ADDMETHOD(this, '" + name + "', (function(public) { return function(" + args + ")"; }); }()); var matchMethod = /ADDMETHOD([^,]+, \s*?')([^']*)('[\s\S]*?\{[^\{]*?\{)/, mc, methods = "", publicVars = "", methodsArray = []; while ((mc = rest.match(matchMethod))) { var prev = RegExp.leftContext, allNext = RegExp.rightContext, next = nextBrace(allNext, "{", "}"); methodsArray.push("addMethod" + mc[1] + mc[2] + mc[3] + next + "};})(this));\n"); publicVars += mc[2] + "|"; if (extendingClass){ for (var i = 0, aLength = arrayOfSuperClasses.length; i < aLength; i++){ if (extendingClass === arrayOfSuperClasses[i].className){ publicVars += arrayOfSuperClasses[i].classVariables; for (var x = 0, fLength = arrayOfSuperClasses[i].classFunctions.length; x < fLength; x++){ publicVars += arrayOfSuperClasses[i].classFunctions[x]; } } } } rest = prev + allNext.slice(next.length + 1); } var matchConstructor = new RegExp("\\b" + className + "\\s*\\(([^\\)]*?)\\)\\s*{"), c, constructor = "", constructorsArray = []; // Extract all constructors and put them into the variable "constructors" while ((c = rest.match(matchConstructor))) { var prev = RegExp.leftContext, allNext = RegExp.rightContext, next = nextBrace(allNext, "{", "}"), args = c[1]; args = args.split(/,\s*?/); if (args[0].match(/^\s*$/)) { args.shift(); } constructor = "if ( arguments.length === " + args.length + " ) {\n"; for (var i = 0, aLength = args.length; i < aLength; i++) { constructor += " var " + args[i] + " = arguments[" + i + "];\n"; } constructor += next + "}\n"; constructorsArray.push(constructor); rest = prev + allNext.slice(next.length + 1); } var vars = "", staticVars = "", localStaticVars = []; // Put all member variables into "vars" // and keep a list of all public variables rest = (function(){ rest.replace(/(?:final|private|public)?\s*?(?:(static)\s+)?var\s+([^;]*?;)/g, function(all, staticVar, variable) { variable = "this." + variable.replace(/,\s*/g, ";\nthis.") .replace(/this.(\w+);/g, "this.$1 = null;") + '\n'; publicVars += variable.replace(/\s*this\.(\w+)\s*(;|=).*\s?/g, "$1|"); thisSuperClass.classVariables += variable.replace(/\s*this\.(\w+)\s*(;|=).*\s?/g, "$1|"); if (staticVar === "static"){ // Fix static methods variable = variable.replace(/this\.(\w+)\s*=\s*([^;]*?;)/g, function(all, sVariable, value){ localStaticVars.push(sVariable); value = value.replace(new RegExp("(" + localStaticVars.join("|") + ")", "g"), className + ".$1"); staticVars += className + "." + sVariable + " = " + value; return "if (typeof " + className + "." + sVariable + " === 'undefined'){ " + className + "." + sVariable + " = " + value + " }\n" + "this.__defineGetter__('" + sVariable + "', function(){ return "+ className + "." + sVariable + "; });\n" + "this.__defineSetter__('" + sVariable + "', function(val){ " + className + "." + sVariable + " = val; });\n"; }); } vars += variable; return ""; }); }()); // add this. to public variables used inside member functions, and constructors if (publicVars) { // Search functions for public variables for (var i = 0, aLength = methodsArray.length; i < aLength; i++){ methodsArray[i] = (function(){ return methodsArray[i].replace(/(addMethod.*?\{ return function\((.*?)\)\s*\{)([\s\S]*?)(\};\}\)\(this\)\);)/g, function(all, header, localParams, body, footer) { body = body.replace(/this\./g, "public."); localParams = localParams.replace(/\s*,\s*/g, "|"); return header + body.replace(new RegExp("(var\\s+?|\\.)?\\b(" + publicVars.substr(0, publicVars.length-1) + ")\\b", "g"), function (all, first, variable) { if (first === ".") { return all; } else if (/var\s*?$/.test(first)) { localParams += "|" + variable; return all; } else if (localParams && new RegExp("\\b(" + localParams + ")\\b").test(variable)){ return all; } else { return "public." + variable; } }) + footer; }); }()); } // Search constructors for public variables for (var i = 0, localParameters = "", aLength = constructorsArray.length; i < aLength; i++){ localParameters = ""; (function(){ constructorsArray[i].replace(/var\s+(\w+) = arguments\[[^\]]\];/g, function(all, localParam){ localParameters += localParam + "|"; }); }()); (function(){ constructorsArray[i] = constructorsArray[i].replace(new RegExp("(var\\s+?|\\.)?\\b(" + publicVars.substr(0, publicVars.length-1) + ")\\b", "g"), function (all, first, variable) { if (first === ".") { return all; } else if (/var\s*?$/.test(first)) { localParameters += variable + "|"; return all; } else if (localParameters && new RegExp("\\b(" + localParameters.substr(0, localParameters.length-1) + ")\\b").test(variable)){ return all; } else { return "this." + variable; } }); }()); } } var constructors = ""; for (var i = 0, aLength = methodsArray.length; i < aLength; i++){ methods += methodsArray[i]; } for (var i = 0, aLength = constructorsArray.length; i < aLength; i++){ constructors += constructorsArray[i]; } arrayOfSuperClasses.push(thisSuperClass); rest = vars + "\n" + methods + "\n" + constructors; aCode = left + rest + "\n}" + staticVars + allRest; } // Do some tidying up, where necessary aCode = aCode.replace(/processing.\w+ = function addMethod/g, "addMethod"); // Remove processing. from leftover functions aCode = aCode.replace(/processing\.((\w+) = function)/g, "$1"); // Check if 3D context is invoked -- this is not the best way to do this. if (aCode.match(/size\((?:.+),(?:.+),\s*(OPENGL|P3D)\s*\);/)) { p.use3DContext = true; } // Handle (int) Casting aCode = aCode.replace(/\(int\)/g, "0|"); // Remove Casting aCode = aCode.replace(new RegExp("\\((" + classes.join("|") + ")(\\[\\])*\\)", "g"), ""); // Force numbers to exist // //aCode = aCode.replace(/([^.])(\w+)\s*\+=/g, "$1$2 = ($2||0) +"); var toNumbers = function(str) { var ret = []; str.replace(/(..)/g, function(str) { ret.push(parseInt(str, 16)); }); return ret; }; // Convert #aaaaaa into color aCode = aCode.replace(/#([a-f0-9]{6})/ig, function(m, hex) { var num = toNumbers(hex); return "defaultColor(" + num[0] + "," + num[1] + "," + num[2] + ")"; }); // Convert 3.0f to just 3.0 aCode = aCode.replace(/(\d+)f/g, "$1"); // replaces all masked strings from <STRING n> to the appropriate string contained in the strings array for (var n = 0, sl = strings.length; n < sl; n++) { aCode = (function() { return aCode.replace(new RegExp("(.*)(<STRING " + n + ">)(.*)", "g"), function(all, quoteStart, match, quoteEnd) { var returnString = all, notString = true, quoteType = "", escape = false; for (var x = 0, ql = quoteStart.length; x < ql; x++) { if (notString) { if (quoteStart.charAt(x) === "\"" || quoteStart.charAt(x) === "'") { quoteType = quoteStart.charAt(x); notString = false; } } else { if (!escape) { if (quoteStart.charAt(x) === "\\") { escape = true; } else if (quoteStart.charAt(x) === quoteType) { notString = true; quoteType = ""; } } else { escape = false; } } } if (notString) { // Match is not inside a string returnString = quoteStart + strings[n] + quoteEnd; } return returnString; }); }()); } return aCode; }; // IE Unfriendly AJAX Method var ajax = function(url) { var AJAX = new window.XMLHttpRequest(); if (AJAX) { AJAX.open("GET", url + "?t=" + new Date().getTime(), false); AJAX.send(null); return AJAX.responseText; } else { return false; } }; // Automatic Initialization Method var init = function() { var canvas = document.getElementsByTagName('canvas'); for (var i = 0, l = canvas.length; i < l; i++) { // datasrc and data-src are deprecated. var processingSources = canvas[i].getAttribute('data-processing-sources'); if (processingSources === null) { // Temporary fallback for datasrc and data-src processingSources = canvas[i].getAttribute('data-src'); if (processingSources === null) { processingSources = canvas[i].getAttribute('datasrc'); } } if (processingSources) { // The problem: if the HTML canvas dimensions differ from the // dimensions specified in the size() call in the sketch, for // 3D sketches, browsers will either not render or render the // scene incorrectly. To fix this, we need to adjust the attributes // of the canvas width and height. // Get the source, we'll need to find what the user has used in size() var filenames = processingSources.split(' '); var code = ""; for (var j=0, fl=filenames.length; j<fl; j++) { if (filenames[j]) { code += ajax(filenames[j]) + ";\n"; // deal with files that don't end with newline } } new Processing(canvas[i], code); } } }; document.addEventListener('DOMContentLoaded', function() { init(); }, false); }());
FRAME_RATE regex fix tic 651
processing.js
FRAME_RATE regex fix tic 651
<ide><path>rocessing.js <ide> // we need to differentiate them somehow. So when we parse <ide> // the Processing.js source, replace frameRate so it isn't <ide> // confused with frameRate(). <del> aCode = aCode.replace(/(\s*=\s*|\(*\s*)frameRate(\s*\)+?|\s*;)/, "$1p.FRAME_RATE$2"); <add> aCode = aCode.replace(/frameRate\s*([^\(])/g, "FRAME_RATE$1"); <ide> <ide> // Simple convert a function-like thing to function <ide> aCode = aCode.replace(/(?:static )?(\w+(?:\[\])*\s+)(\w+)\s*(\([^\)]*\)\s*\{)/g, function(all, type, name, args) {
JavaScript
mit
945839144c3c1d3b4fe16207ac605fd5fec00b17
0
aakashrajput/Pokemon-Showdown,Zarel/Pokemon-Showdown,Zarel/Pokemon-Showdown,Kokonoe-san/Glacia-PS,AnaRitaTorres/Pokemon-Showdown,cadaeic/Pokemon-Showdown,zek7rom/SpacialGaze,Kokonoe-san/Glacia-PS,jd4564/Pokemon-Showdown,Lord-Haji/SpacialGaze,Mystifi/Exiled,panpawn/Gold-Server,DesoGit/TsunamiPS,Sora-League/Sora,xfix/Pokemon-Showdown,Flareninja/Showdown-Boilerplate,TbirdClanWish/Pokemon-Showdown,Lord-Haji/SpacialGaze,Elveman/RPCShowdownServer,panpawn/Gold-Server,azum4roll/Pokemon-Showdown,Sora-League/Sora,Elveman/RPCShowdownServer,svivian/Pokemon-Showdown,SolarisFox/Pokemon-Showdown,urkerab/Pokemon-Showdown,Guernouille/Pokemon-Showdown,CharizardtheFireMage/Showdown-Boilerplate,PS-Spectral/Spectral,Enigami/Pokemon-Showdown,aakashrajput/Pokemon-Showdown,DesoGit/Tsunami_PS,azum4roll/Pokemon-Showdown,xfix/Pokemon-Showdown,AnaRitaTorres/Pokemon-Showdown,ZestOfLife/FestiveLife,ZestOfLife/FestiveLife,Mystifi/Exiled,urkerab/Pokemon-Showdown,xfix/Pokemon-Showdown,xCrystal/Pokemon-Showdown,CreaturePhil/Showdown-Boilerplate,danpantry/Pokemon-Showdown,svivian/Pokemon-Showdown,ShowdownHelper/Saffron,panpawn/Gold-Server,AustinXII/Pokemon-Showdown,Volcos/SpacialGaze,SolarisFox/Pokemon-Showdown,panpawn/Pokemon-Showdown,Pikachuun/Pokemon-Showdown,KewlStatics/Alliance,Sora-League/Sora,Mystifi/Exiled,KewlStatics/Shit,Git-Worm/City-PS,CreaturePhil/Showdown-Boilerplate,CreaturePhil/Showdown-Boilerplate,jd4564/Pokemon-Showdown,xCrystal/Pokemon-Showdown,DarkSuicune/Pokemon-Showdown,Guernouille/Pokemon-Showdown,Enigami/Pokemon-Showdown,aakashrajput/Pokemon-Showdown,HoeenCoder/SpacialGaze,cadaeic/Pokemon-Showdown,Enigami/Pokemon-Showdown,xCrystal/Pokemon-Showdown,CharizardtheFireMage/Showdown-Boilerplate,xfix/Pokemon-Showdown,Bryan-0/Pokemon-Showdown,HoeenCoder/SpacialGaze,DesoGit/TsunamiPS,Zarel/Pokemon-Showdown,AustinXII/Pokemon-Showdown,ShowdownHelper/Saffron,svivian/Pokemon-Showdown,EienSeiryuu/Pokemon-Showdown,PS-Spectral/Spectral,PS-Spectral/Spectral,QuiteQuiet/Pokemon-Showdown,jumbowhales/Pokemon-Showdown,panpawn/Pokemon-Showdown,Bryan-0/Pokemon-Showdown,AWailOfATail/Pokemon-Showdown,AustinXII/Pokemon-Showdown,svivian/Pokemon-Showdown,Pikachuun/Pokemon-Showdown,Enigami/Pokemon-Showdown,DesoGit/Tsunami_PS,zek7rom/SpacialGaze,AWailOfATail/Pokemon-Showdown,danpantry/Pokemon-Showdown,jumbowhales/Pokemon-Showdown,jumbowhales/Pokemon-Showdown,Flareninja/Showdown-Boilerplate,ShowdownHelper/Saffron,Lord-Haji/SpacialGaze,KewlStatics/Alliance,urkerab/Pokemon-Showdown,QuiteQuiet/Pokemon-Showdown,xfix/Pokemon-Showdown,svivian/Pokemon-Showdown,sirDonovan/Pokemon-Showdown,KewlStatics/Shit,DarkSuicune/Pokemon-Showdown,sirDonovan/Pokemon-Showdown,QuiteQuiet/Pokemon-Showdown,HoeenCoder/SpacialGaze,DesoGit/Tsunami_PS,Git-Worm/City-PS,TbirdClanWish/Pokemon-Showdown,Volcos/SpacialGaze,AWailOfATail/Pokemon-Showdown,sirDonovan/Pokemon-Showdown,EienSeiryuu/Pokemon-Showdown,HoeenCoder/SpacialGaze
/** * System commands * Pokemon Showdown - http://pokemonshowdown.com/ * * These are system commands - commands required for Pokemon Showdown * to run. A lot of these are sent by the client. * * System commands should not be modified, added, or removed. If you'd * like to modify or add commands, add or edit files in chat-plugins/ * * For the API, see chat-plugins/COMMANDS.md * * @license MIT license */ 'use strict'; /* eslint no-else-return: "error" */ const crypto = require('crypto'); const fs = require('fs'); const MAX_REASON_LENGTH = 300; const MUTE_LENGTH = 7 * 60 * 1000; const HOURMUTE_LENGTH = 60 * 60 * 1000; const SLOWCHAT_MINIMUM = 2; const SLOWCHAT_MAXIMUM = 60; const SLOWCHAT_USER_REQUIREMENT = 10; exports.commands = { version: function (target, room, user) { if (!this.runBroadcast()) return; this.sendReplyBox("Server version: <b>" + CommandParser.package.version + "</b>"); }, auth: 'authority', stafflist: 'authority', globalauth: 'authority', authlist: 'authority', authority: function (target, room, user, connection) { if (target) { let targetRoom = Rooms.search(target); let unavailableRoom = targetRoom && (targetRoom !== room && (targetRoom.modjoin || targetRoom.staffRoom) && !user.can('makeroom')); if (targetRoom && !unavailableRoom) return this.parse('/roomauth1 ' + target); return this.parse('/userauth ' + target); } let rankLists = {}; let ranks = Object.keys(Config.groups); for (let u in Users.usergroups) { let rank = Users.usergroups[u].charAt(0); if (rank === ' ' || rank === '+') continue; // In case the usergroups.csv file is not proper, we check for the server ranks. if (ranks.includes(rank)) { let name = Users.usergroups[u].substr(1); if (!rankLists[rank]) rankLists[rank] = []; if (name) rankLists[rank].push(name); } } let buffer = Object.keys(rankLists).sort((a, b) => (Config.groups[b] || {rank: 0}).rank - (Config.groups[a] || {rank: 0}).rank ).map(r => (Config.groups[r] ? "**" + Config.groups[r].name + "s** (" + r + ")" : r) + ":\n" + rankLists[r].sort((a, b) => toId(a).localeCompare(toId(b))).join(", ") ); if (!buffer.length) return connection.popup("This server has no global authority."); connection.popup(buffer.join("\n\n")); }, authhelp: ["/auth - Show global staff for the server.", "/auth [room] - Show what roomauth a room has.", "/auth [user] - Show what global and roomauth a user has."], me: function (target, room, user, connection) { // By default, /me allows a blank message if (!target) target = ''; target = this.canTalk('/me ' + target); if (!target) return; return target; }, mee: function (target, room, user, connection) { // By default, /mee allows a blank message if (!target) target = ''; target = target.trim(); if (/[A-Za-z0-9]/.test(target.charAt(0))) { return this.errorReply("To prevent confusion, /mee can't start with a letter or number."); } target = this.canTalk('/mee ' + target); if (!target) return; return target; }, 'battle!': 'battle', battle: function (target, room, user, connection, cmd) { if (cmd === 'battle') return this.sendReply("What?! How are you not more excited to battle?! Try /battle! to show me you're ready."); if (!target) target = "randombattle"; return this.parse("/search " + target); }, avatar: function (target, room, user) { if (!target) return this.parse('/avatars'); let parts = target.split(','); let avatarid = toId(parts[0]); let avatar = 0; let avatarTable = { lucas: 1, dawn: 2, youngster: 3, lass: 4, camper: 5, picnicker: 6, bugcatcher: 7, aromalady: 8, twins: 9, hiker: 10, battlegirl: 11, fisherman: 12, cyclist: 13, cyclistf: 14, blackbelt: 15, artist: 16, pokemonbreeder: 17, pokemonbreederf: 18, cowgirl: 19, jogger: 20, pokefan: 21, pokefanf: 22, pokekid: 23, youngcouple: 24, acetrainer: 25, acetrainerf: 26, waitress: 27, veteran: 28, ninjaboy: 29, dragontamer: 30, birdkeeper: 31, doubleteam: 32, richboy: 33, lady: 34, gentleman: 35, socialite: 36, madame: 36, beauty: 37, collector: 38, policeman: 39, pokemonranger: 40, pokemonrangerf: 41, scientist: 42, swimmer: 43, swimmerf: 44, tuber: 45, tuberf: 46, sailor: 47, sisandbro: 48, ruinmaniac: 49, psychic: 50, psychicf: 51, gambler: 52, dppguitarist: 53, acetrainersnow: 54, acetrainersnowf: 55, skier: 56, skierf: 57, roughneck: 58, clown: 59, worker: 60, schoolkid: 61, schoolkidf: 62, roark: 63, barry: 64, byron: 65, aaron: 66, bertha: 67, flint: 68, lucian: 69, dppcynthia: 70, bellepa: 71, rancher: 72, mars: 73, galacticgrunt: 74, gardenia: 75, crasherwake: 76, maylene: 77, fantina: 78, candice: 79, volkner: 80, parasollady: 81, waiter: 82, interviewers: 83, cameraman: 84, oli: 84, reporter: 85, roxy: 85, idol: 86, grace: 86, cyrus: 87, jupiter: 88, saturn: 89, galacticgruntf: 90, argenta: 91, palmer: 92, thorton: 93, buck: 94, darach: 95, marley: 96, mira: 97, cheryl: 98, riley: 99, dahlia: 100, ethan: 101, lyra: 102, archer: 132, ariana: 133, proton: 134, petrel: 135, mysteryman: 136, eusine: 136, ptlucas: 137, ptdawn: 138, falkner: 141, bugsy: 142, whitney: 143, morty: 144, chuck: 145, jasmine: 146, pryce: 147, clair: 148, will: 149, koga: 150, bruno: 151, karen: 152, lance: 153, brock: 154, misty: 155, ltsurge: 156, erica: 157, janine: 158, sabrina: 159, blaine: 160, blue: 161, red2: 162, red: 163, silver: 164, giovanni: 165, unknownf: 166, unknownm: 167, unknown: 168, hilbert: 169, hilda: 170, chili: 179, cilan: 180, cress: 181, lenora: 188, burgh: 189, elesa: 190, clay: 191, skyla: 192, cheren: 206, bianca: 207, n: 209, brycen: 222, iris: 223, drayden: 224, shauntal: 246, marshal: 247, grimsley: 248, caitlin: 249, ghetsis: 250, ingo: 256, alder: 257, cynthia: 260, emmet: 261, dueldiskhilbert: 262, dueldiskhilda: 263, hugh: 264, rosa: 265, nate: 266, colress: 267, bw2beauty: 268, bw2ghetsis: 269, bw2plasmagrunt: 270, bw2plasmagruntf: 271, bw2iris: 272, brycenman: 273, shadowtriad: 274, rood: 275, zinzolin: 276, bw2cheren: 277, marlon: 278, roxie: 279, roxanne: 280, brawly: 281, wattson: 282, flannery: 283, norman: 284, winona: 285, tate: 286, liza: 287, juan: 288, guitarist: 289, steven: 290, wallace: 291, magicqueen: 292, bellelba: 292, benga: 293, bw2elesa: '#bw2elesa', teamrocket: '#teamrocket', yellow: '#yellow', zinnia: '#zinnia', clemont: '#clemont', }; if (avatarid in avatarTable) { avatar = avatarTable[avatarid]; } else { avatar = parseInt(avatarid); } if (typeof avatar === 'number' && (!avatar || avatar > 294 || avatar < 1)) { if (!parts[1]) { this.errorReply("Invalid avatar."); } return false; } user.avatar = avatar; if (!parts[1]) { this.sendReply("Avatar changed to:\n" + '|raw|<img src="//play.pokemonshowdown.com/sprites/trainers/' + (typeof avatar === 'string' ? avatar.substr(1) : avatar) + '.png" alt="" width="80" height="80" />'); } }, avatarhelp: ["/avatar [avatar number 1 to 293] - Change your trainer sprite."], signout: 'logout', logout: function (target, room, user) { user.resetName(); }, requesthelp: 'report', report: function (target, room, user) { if (room.id === 'help') { this.sendReply("Ask one of the Moderators (@) in the Help room."); } else { this.parse('/join help'); } }, r: 'reply', reply: function (target, room, user) { if (!target) return this.parse('/help reply'); if (!user.lastPM) { return this.errorReply("No one has PMed you yet."); } return this.parse('/msg ' + (user.lastPM || '') + ', ' + target); }, replyhelp: ["/reply OR /r [message] - Send a private message to the last person you received a message from, or sent a message to."], pm: 'msg', whisper: 'msg', w: 'msg', msg: function (target, room, user, connection) { if (!target) return this.parse('/help msg'); target = this.splitTarget(target); let targetUser = this.targetUser; if (!target) { this.errorReply("You forgot the comma."); return this.parse('/help msg'); } this.pmTarget = (targetUser || this.targetUsername); if (!targetUser) { this.errorReply("User " + this.targetUsername + " not found. Did you misspell their name?"); return this.parse('/help msg'); } if (!targetUser.connected) { return this.errorReply("User " + this.targetUsername + " is offline."); } if (Config.pmmodchat && !user.matchesRank(Config.pmmodchat)) { let groupName = Config.groups[Config.pmmodchat] && Config.groups[Config.pmmodchat].name || Config.pmmodchat; return this.errorReply("Because moderated chat is set, you must be of rank " + groupName + " or higher to PM users."); } if (user.locked && !targetUser.can('lock')) { return this.errorReply("You can only private message members of the global moderation team (users marked by @ or above in the Help room) when locked."); } if (targetUser.locked && !user.can('lock')) { return this.errorReply("This user is locked and cannot PM."); } if (targetUser.ignorePMs && targetUser.ignorePMs !== user.group && !user.can('lock')) { if (!targetUser.can('lock')) { return this.errorReply("This user is blocking private messages right now."); } else if (targetUser.can('bypassall')) { return this.errorReply("This admin is too busy to answer private messages right now. Please contact a different staff member."); } } if (user.ignorePMs && user.ignorePMs !== targetUser.group && !targetUser.can('lock')) { return this.errorReply("You are blocking private messages right now."); } target = this.canTalk(target, null, targetUser); if (!target) return false; let message; if (target.charAt(0) === '/' && target.charAt(1) !== '/') { // PM command let innerCmdIndex = target.indexOf(' '); let innerCmd = (innerCmdIndex >= 0 ? target.slice(1, innerCmdIndex) : target.slice(1)); let innerTarget = (innerCmdIndex >= 0 ? target.slice(innerCmdIndex + 1) : ''); switch (innerCmd) { case 'me': case 'mee': case 'announce': break; case 'ME': case 'MEE': message = '|pm|' + user.getIdentity().toUpperCase() + '|' + targetUser.getIdentity() + '|/' + innerCmd.toLowerCase() + ' ' + innerTarget; break; case 'invite': case 'inv': { let targetRoom = Rooms.search(innerTarget); if (!targetRoom || targetRoom === Rooms.global) return this.errorReply('The room "' + innerTarget + '" does not exist.'); if (targetRoom.staffRoom && !targetUser.isStaff) return this.errorReply('User "' + this.targetUsername + '" requires global auth to join room "' + targetRoom.id + '".'); if (targetRoom.modjoin) { if (targetRoom.auth && (targetRoom.isPrivate === true || targetUser.group === ' ') && !(targetUser.userid in targetRoom.auth)) { this.parse('/roomvoice ' + targetUser.name, false, targetRoom); if (!(targetUser.userid in targetRoom.auth)) { return; } } } if (targetRoom.isPrivate === true && targetRoom.modjoin && targetRoom.auth) { if (!(user.userid in targetRoom.auth)) { return this.errorReply('The room "' + innerTarget + '" does not exist.'); } if (Config.groupsranking.indexOf(targetRoom.auth[targetUser.userid] || ' ') < Config.groupsranking.indexOf(targetRoom.modjoin) && !targetUser.can('bypassall')) { return this.errorReply('The user "' + targetUser.name + '" does not have permission to join "' + innerTarget + '".'); } } if (targetRoom.auth && targetRoom.isPrivate && !(user.userid in targetRoom.auth) && !user.can('makeroom')) { return this.errorReply('You do not have permission to invite people to this room.'); } target = '/invite ' + targetRoom.id; break; } default: return this.errorReply("The command '/" + innerCmd + "' was unrecognized or unavailable in private messages. To send a message starting with '/" + innerCmd + "', type '//" + innerCmd + "'."); } } if (!message) message = '|pm|' + user.getIdentity() + '|' + targetUser.getIdentity() + '|' + target; user.send(message); if (targetUser !== user) targetUser.send(message); targetUser.lastPM = user.userid; user.lastPM = targetUser.userid; }, msghelp: ["/msg OR /whisper OR /w [username], [message] - Send a private message."], pminfobox: function (target, room, user, connection) { if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); if (!user.can('addhtml', null, room)) return false; if (!target) return this.parse("/help pminfobox"); target = this.canHTML(target); if (!target) return; target = this.splitTarget(target); let targetUser = this.targetUser; if (!targetUser || !targetUser.connected) return this.errorReply("User " + targetUser + " is not currently online."); if (!(targetUser in room.users) && !user.can('addhtml')) return this.errorReply("You do not have permission to use this command to users who are not in this room."); if (targetUser.ignorePMs) return this.errorReply("This user is currently ignoring PMs."); if (targetUser.locked) return this.errorReply("This user is currently locked, so you cannot send them a pminfobox."); // Apply the infobox to the message target = '/raw <div class="infobox">' + target + '</div>'; let message = '|pm|' + user.getIdentity() + '|' + targetUser.getIdentity() + '|' + target; user.send(message); if (targetUser !== user) targetUser.send(message); targetUser.lastPM = user.userid; user.lastPM = targetUser.userid; }, pminfoboxhelp: ["/pminfobox [user], [html]- PMs an [html] infobox to [user]. Requires * ~"], blockpm: 'ignorepms', blockpms: 'ignorepms', ignorepm: 'ignorepms', ignorepms: function (target, room, user) { if (user.ignorePMs === (target || true)) return this.errorReply("You are already blocking private messages! To unblock, use /unblockpms"); if (user.can('lock') && !user.can('bypassall')) return this.errorReply("You are not allowed to block private messages."); user.ignorePMs = true; if (target in Config.groups) { user.ignorePMs = target; return this.sendReply("You are now blocking private messages, except from staff and " + target + "."); } return this.sendReply("You are now blocking private messages, except from staff."); }, ignorepmshelp: ["/blockpms - Blocks private messages. Unblock them with /unignorepms."], unblockpm: 'unignorepms', unblockpms: 'unignorepms', unignorepm: 'unignorepms', unignorepms: function (target, room, user) { if (!user.ignorePMs) return this.errorReply("You are not blocking private messages! To block, use /blockpms"); user.ignorePMs = false; return this.sendReply("You are no longer blocking private messages."); }, unignorepmshelp: ["/unblockpms - Unblocks private messages. Block them with /blockpms."], idle: 'away', afk: 'away', away: function (target, room, user) { this.parse('/blockchallenges'); this.parse('/blockpms ' + target); }, awayhelp: ["/away - Blocks challenges and private messages. Unblock them with /back."], unaway: 'back', unafk: 'back', back: function () { this.parse('/unblockpms'); this.parse('/unblockchallenges'); }, backhelp: ["/back - Unblocks challenges and/or private messages, if either are blocked."], rank: function (target, room, user) { if (!target) target = user.name; Ladders.visualizeAll(target).then(values => { let buffer = '<div class="ladder"><table>'; buffer += '<tr><td colspan="8">User: <strong>' + Tools.escapeHTML(target) + '</strong></td></tr>'; let ratings = values.join(''); if (!ratings) { buffer += '<tr><td colspan="8"><em>This user has not played any ladder games yet.</em></td></tr>'; } else { buffer += '<tr><th>Format</th><th><abbr title="Elo rating">Elo</abbr></th><th>W</th><th>L</th><th>Total</th>'; buffer += ratings; } buffer += '</table></div>'; this.sendReply('|raw|' + buffer); }); }, makeprivatechatroom: 'makechatroom', makechatroom: function (target, room, user, connection, cmd) { if (!this.can('makeroom')) return; // `,` is a delimiter used by a lot of /commands // `|` and `[` are delimiters used by the protocol // `-` has special meaning in roomids if (target.includes(',') || target.includes('|') || target.includes('[') || target.includes('-')) { return this.errorReply("Room titles can't contain any of: ,|[-"); } let id = toId(target); if (!id) return this.parse('/help makechatroom'); // Check if the name already exists as a room or alias if (Rooms.search(id)) return this.errorReply("The room '" + target + "' already exists."); if (!Rooms.global.addChatRoom(target)) return this.errorReply("An error occurred while trying to create the room '" + target + "'."); if (cmd === 'makeprivatechatroom') { let targetRoom = Rooms.search(target); targetRoom.isPrivate = true; targetRoom.chatRoomData.isPrivate = true; Rooms.global.writeChatRoomData(); if (Rooms.get('upperstaff')) { Rooms.get('upperstaff').add('|raw|<div class="broadcast-green">Private chat room created: <b>' + Tools.escapeHTML(target) + '</b></div>').update(); } this.sendReply("The private chat room '" + target + "' was created."); } else { if (Rooms.get('staff')) { Rooms.get('staff').add('|raw|<div class="broadcast-green">Public chat room created: <b>' + Tools.escapeHTML(target) + '</b></div>').update(); } if (Rooms.get('upperstaff')) { Rooms.get('upperstaff').add('|raw|<div class="broadcast-green">Public chat room created: <b>' + Tools.escapeHTML(target) + '</b></div>').update(); } this.sendReply("The chat room '" + target + "' was created."); } }, makechatroomhelp: ["/makechatroom [roomname] - Creates a new room named [roomname]. Requires: & ~"], makegroupchat: function (target, room, user, connection, cmd) { if (!user.autoconfirmed) { return this.errorReply("You must be autoconfirmed to make a groupchat."); } if (!user.confirmed) { return this.errorReply("You must be global voice or roomdriver+ in some public room to make a groupchat."); } // if (!this.can('makegroupchat')) return false; if (target.length > 64) return this.errorReply("Title must be under 32 characters long."); let targets = target.split(',', 2); // Title defaults to a random 8-digit number. let title = targets[0].trim(); if (title.length >= 32) { return this.errorReply("Title must be under 32 characters long."); } else if (!title) { title = ('' + Math.floor(Math.random() * 100000000)); } else if (Config.chatfilter) { let filterResult = Config.chatfilter.call(this, title, user, null, connection); if (!filterResult) return; if (title !== filterResult) { return this.errorReply("Invalid title."); } } // `,` is a delimiter used by a lot of /commands // `|` and `[` are delimiters used by the protocol // `-` has special meaning in roomids if (title.includes(',') || title.includes('|') || title.includes('[') || title.includes('-')) { return this.errorReply("Room titles can't contain any of: ,|[-"); } // Even though they're different namespaces, to cut down on confusion, you // can't share names with registered chatrooms. let existingRoom = Rooms.search(toId(title)); if (existingRoom && !existingRoom.modjoin) return this.errorReply("The room '" + title + "' already exists."); // Room IDs for groupchats are groupchat-TITLEID let titleid = toId(title); if (!titleid) { titleid = '' + Math.floor(Math.random() * 100000000); } let roomid = 'groupchat-' + user.userid + '-' + titleid; // Titles must be unique. if (Rooms.search(roomid)) return this.errorReply("A group chat named '" + title + "' already exists."); // Tab title is prefixed with '[G]' to distinguish groupchats from // registered chatrooms if (Monitor.countGroupChat(connection.ip)) { this.errorReply("Due to high load, you are limited to creating 4 group chats every hour."); return; } // Privacy settings, default to hidden. let privacy = (toId(targets[1]) === 'private') ? true : 'hidden'; let groupChatLink = '<code>&lt;&lt;' + roomid + '>></code>'; let groupChatURL = ''; if (Config.serverid) { groupChatURL = 'http://' + (Config.serverid === 'showdown' ? 'psim.us' : Config.serverid + '.psim.us') + '/' + roomid; groupChatLink = '<a href="' + groupChatURL + '">' + groupChatLink + '</a>'; } let titleHTML = ''; if (/^[0-9]+$/.test(title)) { titleHTML = groupChatLink; } else { titleHTML = Tools.escapeHTML(title) + ' <small style="font-weight:normal;font-size:9pt">' + groupChatLink + '</small>'; } let targetRoom = Rooms.createChatRoom(roomid, '[G] ' + title, { isPersonal: true, isPrivate: privacy, auth: {}, introMessage: '<h2 style="margin-top:0">' + titleHTML + '</h2><p>There are several ways to invite people:<br />- in this chat: <code>/invite USERNAME</code><br />- anywhere in PS: link to <code>&lt;&lt;' + roomid + '>></code>' + (groupChatURL ? '<br />- outside of PS: link to <a href="' + groupChatURL + '">' + groupChatURL + '</a>' : '') + '</p><p>This room will expire after 40 minutes of inactivity or when the server is restarted.</p><p style="margin-bottom:0"><button name="send" value="/roomhelp">Room management</button>', }); if (targetRoom) { // The creator is RO. targetRoom.auth[user.userid] = '#'; // Join after creating room. No other response is given. user.joinRoom(targetRoom.id); return; } return this.errorReply("An unknown error occurred while trying to create the room '" + title + "'."); }, makegroupchathelp: ["/makegroupchat [roomname], [hidden|private] - Creates a group chat named [roomname]. Leave off privacy to default to hidden. Requires global voice or roomdriver+ in a public room to make a groupchat."], deregisterchatroom: function (target, room, user) { if (!this.can('makeroom')) return; this.errorReply("NOTE: You probably want to use `/deleteroom` now that it exists."); let id = toId(target); if (!id) return this.parse('/help deregisterchatroom'); let targetRoom = Rooms.search(id); if (!targetRoom) return this.errorReply("The room '" + target + "' doesn't exist."); target = targetRoom.title || targetRoom.id; if (Rooms.global.deregisterChatRoom(id)) { this.sendReply("The room '" + target + "' was deregistered."); this.sendReply("It will be deleted as of the next server restart."); return; } return this.errorReply("The room '" + target + "' isn't registered."); }, deregisterchatroomhelp: ["/deregisterchatroom [roomname] - Deletes room [roomname] after the next server restart. Requires: & ~"], deletechatroom: 'deleteroom', deletegroupchat: 'deleteroom', deleteroom: function (target, room, user) { let roomid = target.trim(); if (!roomid) return this.parse('/help deleteroom'); let targetRoom = Rooms.search(roomid); if (!targetRoom) return this.errorReply("The room '" + target + "' doesn't exist."); if (room.isPersonal) { if (!this.can('editroom', null, targetRoom)) return; } else { if (!this.can('makeroom')) return; } target = targetRoom.title || targetRoom.id; if (targetRoom.id === 'global') { return this.errorReply("This room can't be deleted."); } if (targetRoom.chatRoomData) { if (targetRoom.isPrivate) { if (Rooms.get('upperstaff')) { Rooms.get('upperstaff').add(`|raw|<div class="broadcast-red">Private chat room deleted by ${user.userid}: <b>${Tools.escapeHTML(target)}</b></div>`).update(); } } else { if (Rooms.get('staff')) { Rooms.get('staff').add('|raw|<div class="broadcast-red">Public chat room deleted: <b>' + Tools.escapeHTML(target) + '</b></div>').update(); } if (Rooms.get('upperstaff')) { Rooms.get('upperstaff').add(`|raw|<div class="broadcast-red">Public chat room deleted by ${user.userid}: <b>${Tools.escapeHTML(target)}</b></div>`).update(); } } } targetRoom.add("|raw|<div class=\"broadcast-red\"><b>This room has been deleted.</b></div>"); targetRoom.update(); // |expire| needs to be its own message targetRoom.add("|expire|This room has been deleted."); this.sendReply("The room '" + target + "' was deleted."); targetRoom.update(); targetRoom.destroy(); }, deleteroomhelp: ["/deleteroom [roomname] - Deletes room [roomname]. Requires: & ~"], hideroom: 'privateroom', hiddenroom: 'privateroom', secretroom: 'privateroom', publicroom: 'privateroom', privateroom: function (target, room, user, connection, cmd) { if (room.battle || room.isPersonal) { if (!this.can('editroom', null, room)) return; } else { // registered chatrooms show up on the room list and so require // higher permissions to modify privacy settings if (!this.can('makeroom')) return; } let setting; switch (cmd) { case 'privateroom': return this.parse('/help privateroom'); case 'publicroom': setting = false; break; case 'secretroom': setting = true; break; default: if (room.isPrivate === true && target !== 'force') { return this.sendReply(`This room is a secret room. Use "/publicroom" to make it public, or "/hiddenroom force" to force it hidden.`); } setting = 'hidden'; break; } if ((setting === true || room.isPrivate === true) && !room.isPersonal) { if (!this.can('makeroom')) return; } if (target === 'off' || !setting) { if (!room.isPrivate) { return this.errorReply(`This room is already public.`); } if (room.isPersonal) return this.errorReply(`This room can't be made public.`); if (room.privacySetter && user.can('nooverride', null, room) && !user.can('makeroom')) { if (!room.privacySetter.has(user.userid)) { const privacySetters = Array.from(room.privacySetter).join(', '); return this.errorReply(`You can't make the room public since you didn't make it private - only ${privacySetters} can.`); } room.privacySetter.delete(user.userid); if (room.privacySetter.size) { const privacySetters = Array.from(room.privacySetter).join(', '); return this.sendReply(`You are no longer forcing the room to stay private, but ${privacySetters} also need${Tools.plural(room.privacySetter, '', 's')} to use /publicroom to make the room public.`); } } delete room.isPrivate; room.privacySetter = null; this.addModCommand(`${user.name} made this room public.`); if (room.chatRoomData) { delete room.chatRoomData.isPrivate; Rooms.global.writeChatRoomData(); } } else { const settingName = (setting === true ? 'secret' : setting); if (room.isPrivate === setting) { if (room.privacySetter && !room.privacySetter.has(user.userid)) { room.privacySetter.add(user.userid); return this.sendReply(`This room is already ${settingName}, but is now forced to stay that way until you use /publicroom.`); } return this.errorReply(`This room is already ${settingName}.`); } room.isPrivate = setting; this.addModCommand(`${user.name} made this room ${settingName}.`); if (room.chatRoomData) { room.chatRoomData.isPrivate = setting; Rooms.global.writeChatRoomData(); } room.privacySetter = new Set([user.userid]); } }, privateroomhelp: ["/secretroom - Makes a room secret. Secret rooms are visible to & and up. Requires: & ~", "/hiddenroom [on/off] - Makes a room hidden. Hidden rooms are visible to % and up, and inherit global ranks. Requires: \u2605 & ~", "/publicroom - Makes a room public. Requires: \u2605 & ~"], modjoin: function (target, room, user) { if (!target) { const modjoinSetting = room.modjoin === true ? "sync" : room.modjoin || "off"; return this.sendReply(`Modjoin is currently set to: ${modjoinSetting}`); } if (room.battle || room.isPersonal) { if (!this.can('editroom', null, room)) return; } else { if (!this.can('makeroom')) return; } if (room.tour && !room.tour.modjoin) return this.errorReply(`You can't do this in tournaments where modjoin is prohibited.`); if (target === 'off' || target === 'false') { if (!room.modjoin) return this.errorReply(`Modjoin is already turned off in this room.`); delete room.modjoin; this.addModCommand(`${user.name} turned off modjoin.`); if (room.chatRoomData) { delete room.chatRoomData.modjoin; Rooms.global.writeChatRoomData(); } return; } else if (target === 'sync') { if (room.modjoin === true) return this.errorReply(`Modjoin is already set to sync modchat in this room.`); room.modjoin = true; this.addModCommand(`${user.name} set modjoin to sync with modchat.`); } else if (target in Config.groups) { if (room.battle && !this.can('makeroom')) return; if (room.isPersonal && !user.can('makeroom') && target !== '+') return this.errorReply(`/modjoin - Access denied from setting modjoin past + in group chats.`); if (room.modjoin === target) return this.errorReply(`Modjoin is already set to ${target} in this room.`); room.modjoin = target; this.addModCommand(`${user.name} set modjoin to ${target}.`); } else { this.errorReply(`Unrecognized modjoin setting.`); this.parse('/help modjoin'); return false; } if (room.chatRoomData) { room.chatRoomData.modjoin = room.modjoin; Rooms.global.writeChatRoomData(); } if (!room.modchat) this.parse('/modchat ' + Config.groupsranking[1]); if (!room.isPrivate) this.parse('/hiddenroom'); }, modjoinhelp: ["/modjoin [+|%|@|*|&|~|#|off] - Sets modjoin. Users lower than the specified rank can't join this room. Requires: # & ~", "/modjoin [sync|off] - Sets modjoin. Only users who can speak in modchat can join this room. Requires: # & ~"], officialchatroom: 'officialroom', officialroom: function (target, room, user) { if (!this.can('makeroom')) return; if (!room.chatRoomData) { return this.errorReply(`/officialroom - This room can't be made official`); } if (target === 'off') { if (!room.isOfficial) return this.errorReply(`This chat room is already unofficial.`); delete room.isOfficial; this.addModCommand(`${user.name} made this chat room unofficial.`); delete room.chatRoomData.isOfficial; Rooms.global.writeChatRoomData(); } else { if (room.isOfficial) return this.errorReply(`This chat room is already official.`); room.isOfficial = true; this.addModCommand(`${user.name} made this chat room official.`); room.chatRoomData.isOfficial = true; Rooms.global.writeChatRoomData(); } }, roomdesc: function (target, room, user) { if (!target) { if (!this.runBroadcast()) return; if (!room.desc) return this.sendReply(`This room does not have a description set.`); this.sendReplyBox(Tools.html`The room description is: ${room.desc}`); return; } if (!this.can('declare')) return false; if (target.length > 80) return this.errorReply(`Error: Room description is too long (must be at most 80 characters).`); let normalizedTarget = ' ' + target.toLowerCase().replace('[^a-zA-Z0-9]+', ' ').trim() + ' '; if (normalizedTarget.includes(' welcome ')) { return this.errorReply(`Error: Room description must not contain the word "welcome".`); } if (normalizedTarget.slice(0, 9) === ' discuss ') { return this.errorReply(`Error: Room description must not start with the word "discuss".`); } if (normalizedTarget.slice(0, 12) === ' talk about ' || normalizedTarget.slice(0, 17) === ' talk here about ') { return this.errorReply(`Error: Room description must not start with the phrase "talk about".`); } room.desc = target; this.sendReply(`(The room description is now: ${target})`); this.privateModCommand(`(${user.name} changed the roomdesc to: "${target}".)`); if (room.chatRoomData) { room.chatRoomData.desc = room.desc; Rooms.global.writeChatRoomData(); } }, topic: 'roomintro', roomintro: function (target, room, user) { if (!target) { if (!this.runBroadcast()) return; if (!room.introMessage) return this.sendReply("This room does not have an introduction set."); this.sendReply('|raw|<div class="infobox infobox-limited">' + room.introMessage.replace(/\n/g, '') + '</div>'); if (!this.broadcasting && user.can('declare', null, room)) { this.sendReply('Source:'); this.sendReplyBox( '<code>/roomintro ' + Tools.escapeHTML(room.introMessage).split('\n').map(line => { return line.replace(/^(\t+)/, (match, $1) => '&nbsp;'.repeat(4 * $1.length)).replace(/^(\s+)/, (match, $1) => '&nbsp;'.repeat($1.length)); }).join('<br />') + '</code>' ); } return; } if (!this.can('declare', null, room)) return false; target = this.canHTML(target); if (!target) return; if (!/</.test(target)) { // not HTML, do some simple URL linking let re = /(https?:\/\/(([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?))/g; target = target.replace(re, '<a href="$1">$1</a>'); } if (target.substr(0, 11) === '/roomintro ') target = target.substr(11); room.introMessage = target.replace(/\r/g, ''); this.sendReply("(The room introduction has been changed to:)"); this.sendReply('|raw|<div class="infobox infobox-limited">' + room.introMessage.replace(/\n/g, '') + '</div>'); this.privateModCommand(`(${user.name} changed the roomintro.)`); this.logEntry(room.introMessage.replace(/\n/g, '')); if (room.chatRoomData) { room.chatRoomData.introMessage = room.introMessage; Rooms.global.writeChatRoomData(); } }, deletetopic: 'deleteroomintro', deleteroomintro: function (target, room, user) { if (!this.can('declare', null, room)) return false; if (!room.introMessage) return this.errorReply("This room does not have a introduction set."); this.privateModCommand(`(${user.name} deleted the roomintro.)`); this.logEntry(target); delete room.introMessage; if (room.chatRoomData) { delete room.chatRoomData.introMessage; Rooms.global.writeChatRoomData(); } }, stafftopic: 'staffintro', staffintro: function (target, room, user) { if (!target) { if (!this.can('mute', null, room)) return false; if (!room.staffMessage) return this.sendReply("This room does not have a staff introduction set."); this.sendReply('|raw|<div class="infobox">' + room.staffMessage.replace(/\n/g, '') + '</div>'); if (user.can('ban', null, room)) { this.sendReply('Source:'); this.sendReplyBox( '<code>/staffintro ' + Tools.escapeHTML(room.staffMessage).split('\n').map(line => { return line.replace(/^(\t+)/, (match, $1) => '&nbsp;'.repeat(4 * $1.length)).replace(/^(\s+)/, (match, $1) => '&nbsp;'.repeat($1.length)); }).join('<br />') + '</code>' ); } return; } if (!this.can('ban', null, room)) return false; target = this.canHTML(target); if (!target) return; if (!/</.test(target)) { // not HTML, do some simple URL linking let re = /(https?:\/\/(([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?))/g; target = target.replace(re, '<a href="$1">$1</a>'); } if (target.substr(0, 12) === '/staffintro ') target = target.substr(12); room.staffMessage = target.replace(/\r/g, ''); this.sendReply("(The staff introduction has been changed to:)"); this.sendReply('|raw|<div class="infobox">' + target.replace(/\n/g, '') + '</div>'); this.privateModCommand(`(${user.name} changed the staffintro.)`); this.logEntry(room.staffMessage.replace(/\n/g, '')); if (room.chatRoomData) { room.chatRoomData.staffMessage = room.staffMessage; Rooms.global.writeChatRoomData(); } }, deletestafftopic: 'deletestaffintro', deletestaffintro: function (target, room, user) { if (!this.can('ban', null, room)) return false; if (!room.staffMessage) return this.errorReply("This room does not have a staff introduction set."); this.privateModCommand(`(${user.name} deleted the staffintro.)`); this.logEntry(target); delete room.staffMessage; if (room.chatRoomData) { delete room.chatRoomData.staffMessage; Rooms.global.writeChatRoomData(); } }, roomalias: function (target, room, user) { if (!target) { if (!this.runBroadcast()) return; if (!room.aliases || !room.aliases.length) return this.sendReplyBox("This room does not have any aliases."); return this.sendReplyBox("This room has the following aliases: " + room.aliases.join(", ") + ""); } if (!this.can('makeroom')) return false; let alias = toId(target); if (!alias.length) return this.errorReply("Only alphanumeric characters are valid in an alias."); if (Rooms(alias) || Rooms.aliases.has(alias)) return this.errorReply("You cannot set an alias to an existing room or alias."); if (room.isPersonal) return this.errorReply("Personal rooms can't have aliases."); Rooms.aliases.set(alias, room.id); this.privateModCommand(`(${user.name} added the room alias '${target}'.)`); if (!room.aliases) room.aliases = []; room.aliases.push(alias); if (room.chatRoomData) { room.chatRoomData.aliases = room.aliases; Rooms.global.writeChatRoomData(); } }, removeroomalias: function (target, room, user) { if (!room.aliases) return this.errorReply("This room does not have any aliases."); if (!this.can('makeroom')) return false; let alias = toId(target); if (!alias || !Rooms.aliases.has(alias)) return this.errorReply("Please specify an existing alias."); if (Rooms.aliases.get(alias) !== room.id) return this.errorReply("You may only remove an alias from the current room."); this.privateModCommand(`(${user.name} removed the room alias '${target}'.)`); let aliasIndex = room.aliases.indexOf(alias); if (aliasIndex >= 0) { room.aliases.splice(aliasIndex, 1); Rooms.aliases.delete(alias); Rooms.global.writeChatRoomData(); } }, roomowner: function (target, room, user) { if (!room.chatRoomData) { return this.sendReply("/roomowner - This room isn't designed for per-room moderation to be added"); } if (!target) return this.parse('/help roomowner'); target = this.splitTarget(target, true); let targetUser = this.targetUser; let name = this.targetUsername; let userid = toId(name); if (!Users.isUsernameKnown(userid)) { return this.errorReply(`User '${this.targetUsername}' is offline and unrecognized, and so can't be promoted.`); } if (!this.can('makeroom')) return false; if (!room.auth) room.auth = room.chatRoomData.auth = {}; room.auth[userid] = '#'; this.addModCommand(`${name} was appointed Room Owner by ${user.name}.`); if (targetUser) { targetUser.popup(`You were appointed Room Owner by ${user.name} in ${room.id}.`); room.onUpdateIdentity(targetUser); } Rooms.global.writeChatRoomData(); }, roomownerhelp: ["/roomowner [username] - Appoints [username] as a room owner. Requires: & ~"], roomdemote: 'roompromote', roompromote: function (target, room, user, connection, cmd) { if (!room.auth) { this.sendReply("/roompromote - This room isn't designed for per-room moderation"); return this.sendReply("Before setting room mods, you need to set it up with /roomowner"); } if (!target) return this.parse('/help roompromote'); target = this.splitTarget(target, true); let targetUser = this.targetUser; let userid = toId(this.targetUsername); let name = targetUser ? targetUser.name : this.targetUsername; if (!userid) return this.parse('/help roompromote'); if (!targetUser && !Users.isUsernameKnown(userid)) { return this.errorReply("User '" + name + "' is offline and unrecognized, and so can't be promoted."); } if (targetUser && !targetUser.registered) { return this.errorReply("User '" + name + "' is unregistered, and so can't be promoted."); } let currentGroup = room.getAuth({userid, group: (Users.usergroups[userid] || ' ').charAt(0)}); let nextGroup = target; if (target === 'deauth') nextGroup = Config.groupsranking[0]; if (!nextGroup) { return this.errorReply("Please specify a group such as /roomvoice or /roomdeauth"); } if (!Config.groups[nextGroup]) { return this.errorReply("Group '" + nextGroup + "' does not exist."); } if (Config.groups[nextGroup].globalonly || (Config.groups[nextGroup].battleonly && !room.battle)) { return this.errorReply("Group 'room" + Config.groups[nextGroup].id + "' does not exist as a room rank."); } let groupName = Config.groups[nextGroup].name || "regular user"; if ((room.auth[userid] || Config.groupsranking[0]) === nextGroup) { return this.errorReply("User '" + name + "' is already a " + groupName + " in this room."); } if (!user.can('makeroom')) { if (currentGroup !== ' ' && !user.can('room' + (Config.groups[currentGroup] ? Config.groups[currentGroup].id : 'voice'), null, room)) { return this.errorReply("/" + cmd + " - Access denied for promoting/demoting from " + (Config.groups[currentGroup] ? Config.groups[currentGroup].name : "an undefined group") + "."); } if (nextGroup !== ' ' && !user.can('room' + Config.groups[nextGroup].id, null, room)) { return this.errorReply("/" + cmd + " - Access denied for promoting/demoting to " + Config.groups[nextGroup].name + "."); } } if (targetUser && targetUser.locked && !room.isPrivate && !room.battle && !room.isPersonal && (nextGroup === '%' || nextGroup === '@' || nextGroup === '*')) { return this.errorReply("Locked users can't be promoted."); } if (nextGroup === ' ') { delete room.auth[userid]; } else { room.auth[userid] = nextGroup; } // Only show popup if: user is online and in the room, the room is public, and not a groupchat or a battle. let needsPopup = targetUser && room.users[targetUser.userid] && !room.isPrivate && !room.isPersonal && !room.battle; if (nextGroup in Config.groups && currentGroup in Config.groups && Config.groups[nextGroup].rank < Config.groups[currentGroup].rank) { if (targetUser && room.users[targetUser.userid] && !Config.groups[nextGroup].modlog) { // if the user can't see the demotion message (i.e. rank < %), it is shown in the chat targetUser.send(">" + room.id + "\n(You were demoted to Room " + groupName + " by " + user.name + ".)"); } this.privateModCommand("(" + name + " was demoted to Room " + groupName + " by " + user.name + ".)"); if (needsPopup) targetUser.popup("You were demoted to Room " + groupName + " by " + user.name + " in " + room.id + "."); } else if (nextGroup === '#') { this.addModCommand("" + name + " was promoted to " + groupName + " by " + user.name + "."); if (needsPopup) targetUser.popup("You were promoted to " + groupName + " by " + user.name + " in " + room.id + "."); } else { this.addModCommand("" + name + " was promoted to Room " + groupName + " by " + user.name + "."); if (needsPopup) targetUser.popup("You were promoted to Room " + groupName + " by " + user.name + " in " + room.id + "."); } if (targetUser) targetUser.updateIdentity(room.id); if (room.chatRoomData) Rooms.global.writeChatRoomData(); }, roompromotehelp: ["/roompromote OR /roomdemote [username], [group symbol] - Promotes/demotes the user to the specified room rank. Requires: @ * # & ~", "/room[group] [username] - Promotes/demotes the user to the specified room rank. Requires: @ * # & ~", "/roomdeauth [username] - Removes all room rank from the user. Requires: @ * # & ~"], roomstaff: 'roomauth', roomauth1: 'roomauth', roomauth: function (target, room, user, connection, cmd) { let userLookup = ''; if (cmd === 'roomauth1') userLookup = '\n\nTo look up auth for a user, use /userauth ' + target; let targetRoom = room; if (target) targetRoom = Rooms.search(target); let unavailableRoom = targetRoom && (targetRoom !== room && (targetRoom.modjoin || targetRoom.staffRoom) && !user.can('makeroom')); if (!targetRoom || unavailableRoom) return this.errorReply("The room '" + target + "' does not exist."); if (!targetRoom.auth) return this.sendReply("/roomauth - The room '" + (targetRoom.title ? targetRoom.title : target) + "' isn't designed for per-room moderation and therefore has no auth list." + userLookup); let rankLists = {}; for (let u in targetRoom.auth) { if (!rankLists[targetRoom.auth[u]]) rankLists[targetRoom.auth[u]] = []; rankLists[targetRoom.auth[u]].push(u); } let buffer = Object.keys(rankLists).sort((a, b) => (Config.groups[b] || {rank:0}).rank - (Config.groups[a] || {rank:0}).rank ).map(r => { let roomRankList = rankLists[r].sort(); roomRankList = roomRankList.map(s => s in targetRoom.users ? "**" + s + "**" : s); return (Config.groups[r] ? Config.groups[r].name + "s (" + r + ")" : r) + ":\n" + roomRankList.join(", "); }); if (!buffer.length) { connection.popup("The room '" + targetRoom.title + "' has no auth." + userLookup); return; } if (targetRoom !== room) buffer.unshift("" + targetRoom.title + " room auth:"); connection.popup(buffer.join("\n\n") + userLookup); }, userauth: function (target, room, user, connection) { let targetId = toId(target) || user.userid; let targetUser = Users.getExact(targetId); let targetUsername = (targetUser ? targetUser.name : target); let buffer = []; let innerBuffer = []; let group = Users.usergroups[targetId]; if (group) { buffer.push('Global auth: ' + group.charAt(0)); } Rooms.rooms.forEach((curRoom, id) => { if (!curRoom.auth || curRoom.isPrivate) return; group = curRoom.auth[targetId]; if (!group) return; innerBuffer.push(group + id); }); if (innerBuffer.length) { buffer.push('Room auth: ' + innerBuffer.join(', ')); } if (targetId === user.userid || user.can('lock')) { innerBuffer = []; Rooms.rooms.forEach((curRoom, id) => { if (!curRoom.auth || !curRoom.isPrivate) return; if (curRoom.isPrivate === true) return; let auth = curRoom.auth[targetId]; if (!auth) return; innerBuffer.push(auth + id); }); if (innerBuffer.length) { buffer.push('Hidden room auth: ' + innerBuffer.join(', ')); } } if (targetId === user.userid || user.can('makeroom')) { innerBuffer = []; for (let i = 0; i < Rooms.global.chatRooms.length; i++) { let curRoom = Rooms.global.chatRooms[i]; if (!curRoom.auth || !curRoom.isPrivate) continue; if (curRoom.isPrivate !== true) continue; let auth = curRoom.auth[targetId]; if (!auth) continue; innerBuffer.push(auth + curRoom.id); } if (innerBuffer.length) { buffer.push('Private room auth: ' + innerBuffer.join(', ')); } } if (!buffer.length) { buffer.push("No global or room auth."); } buffer.unshift("" + targetUsername + " user auth:"); connection.popup(buffer.join("\n\n")); }, rb: 'roomban', roomban: function (target, room, user, connection) { if (!target) return this.parse('/help roomban'); if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); target = this.splitTarget(target); let targetUser = this.targetUser; let name = this.targetUsername; let userid = toId(name); if (!userid || !targetUser) return this.errorReply("User '" + name + "' not found."); if (target.length > MAX_REASON_LENGTH) { return this.errorReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters."); } if (!this.can('ban', targetUser, room)) return false; if (!room.bannedUsers || !room.bannedIps) { return this.errorReply("Room bans are not meant to be used in room " + room.id + "."); } if (room.bannedUsers[userid] && room.bannedIps[targetUser.latestIp]) return this.sendReply("User " + targetUser.name + " is already banned from room " + room.id + "."); if (targetUser in room.users || user.can('lock')) { targetUser.popup( "|html|<p>" + Tools.escapeHTML(user.name) + " has banned you from the room " + room.id + ".</p>" + (target ? "<p>Reason: " + Tools.escapeHTML(target) + "</p>" : "") + "<p>To appeal the ban, PM the staff member that banned you" + (room.auth ? " or a room owner. </p><p><button name=\"send\" value=\"/roomauth " + room.id + "\">List Room Staff</button></p>" : ".</p>") ); } this.addModCommand("" + targetUser.name + " was banned from room " + room.id + " by " + user.name + "." + (target ? " (" + target + ")" : "")); let acAccount = (targetUser.autoconfirmed !== targetUser.userid && targetUser.autoconfirmed); let alts = room.roomBan(targetUser); if (!(room.isPersonal || room.isPrivate === true) || user.can('alts', targetUser)) { if (alts.length) { this.privateModCommand("(" + targetUser.name + "'s " + (acAccount ? " ac account: " + acAccount + ", " : "") + "roombanned alts: " + alts.join(", ") + ")"); for (let i = 0; i < alts.length; ++i) { this.add('|unlink|' + toId(alts[i])); } } else if (acAccount) { this.privateModCommand("(" + targetUser.name + "'s ac account: " + acAccount + ")"); } } if (targetUser.confirmed && room.chatRoomData && !room.isPrivate) { Monitor.log("[CrisisMonitor] Confirmed user " + targetUser.name + (targetUser.confirmed !== targetUser.userid ? " (" + targetUser.confirmed + ")" : "") + " was roombanned from " + room.id + " by " + user.name + ", and should probably be demoted."); } let lastid = targetUser.getLastId(); this.add('|unlink|roomhide|' + lastid); if (lastid !== toId(this.inputUsername)) this.add('|unlink|roomhide|' + toId(this.inputUsername)); }, roombanhelp: ["/roomban [username] - Bans the user from the room you are in. Requires: @ # & ~"], unroomban: 'roomunban', roomunban: function (target, room, user, connection) { if (!target) return this.parse('/help roomunban'); if (!room.bannedUsers || !room.bannedIps) { return this.errorReply("Room bans are not meant to be used in room " + room.id + "."); } if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); this.splitTarget(target, true); let targetUser = this.targetUser; let userid = room.isRoomBanned(targetUser) || toId(target); if (!userid) return this.errorReply("User '" + target + "' is an invalid username."); if (!this.can('ban', null, room)) return false; let unbannedUserid = room.unRoomBan(userid); if (!unbannedUserid) return this.errorReply("User " + userid + " is not banned from room " + room.id + "."); this.addModCommand("" + unbannedUserid + " was unbanned from room " + room.id + " by " + user.name + "."); }, roomunbanhelp: ["/roomunban [username] - Unbans the user from the room you are in. Requires: @ # & ~"], autojoin: function (target, room, user, connection) { Rooms.global.autojoinRooms(user, connection); let targets = target.split(','); let autojoins = []; if (targets.length > 11 || connection.inRooms.size > 1) return; for (let i = 0; i < targets.length; i++) { if (user.tryJoinRoom(targets[i], connection) === null) { autojoins.push(targets[i]); } } connection.autojoins = autojoins.join(','); }, joim: 'join', j: 'join', join: function (target, room, user, connection) { if (!target) return this.parse('/help join'); if (target.startsWith('http://')) target = target.slice(7); if (target.startsWith('https://')) target = target.slice(8); if (target.startsWith('play.pokemonshowdown.com/')) target = target.slice(25); if (target.startsWith('psim.us/')) target = target.slice(8); if (user.tryJoinRoom(target, connection) === null) { connection.sendTo(target, "|noinit|namerequired|The room '" + target + "' does not exist or requires a login to join."); } }, joinhelp: ["/join [roomname] - Attempt to join the room [roomname]."], leave: 'part', part: function (target, room, user, connection) { if (room.id === 'global') return false; let targetRoom = Rooms.search(target); if (target && !targetRoom) { return this.errorReply("The room '" + target + "' does not exist."); } user.leaveRoom(targetRoom || room, connection); }, /********************************************************* * Moderating: Punishments *********************************************************/ kick: 'warn', k: 'warn', warn: function (target, room, user) { if (!target) return this.parse('/help warn'); if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); if (room.isPersonal && !user.can('warn')) return this.errorReply("Warning is unavailable in group chats."); target = this.splitTarget(target); let targetUser = this.targetUser; if (!targetUser || !targetUser.connected) return this.errorReply("User '" + this.targetUsername + "' not found."); if (!(targetUser in room.users)) { return this.errorReply("User " + this.targetUsername + " is not in the room " + room.id + "."); } if (target.length > MAX_REASON_LENGTH) { return this.errorReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters."); } if (!this.can('warn', targetUser, room)) return false; this.addModCommand("" + targetUser.name + " was warned by " + user.name + "." + (target ? " (" + target + ")" : "")); targetUser.send('|c|~|/warn ' + target); let userid = targetUser.getLastId(); this.add('|unlink|' + userid); if (userid !== toId(this.inputUsername)) this.add('|unlink|' + toId(this.inputUsername)); }, warnhelp: ["/warn OR /k [username], [reason] - Warns a user showing them the Pok\u00e9mon Showdown Rules and [reason] in an overlay. Requires: % @ # & ~"], redirect: 'redir', redir: function (target, room, user, connection) { if (!target) return this.parse('/help redirect'); if (room.isPrivate || room.isPersonal) return this.errorReply("Users cannot be redirected from private or personal rooms."); target = this.splitTarget(target); let targetUser = this.targetUser; let targetRoom = Rooms.search(target); if (!targetRoom || targetRoom.modjoin) { return this.errorReply("The room '" + target + "' does not exist."); } if (!this.can('warn', targetUser, room) || !this.can('warn', targetUser, targetRoom)) return false; if (!targetUser || !targetUser.connected) { return this.errorReply("User " + this.targetUsername + " not found."); } if (targetRoom.id === "global") return this.errorReply("Users cannot be redirected to the global room."); if (targetRoom.isPrivate || targetRoom.isPersonal) { return this.parse('/msg ' + this.targetUsername + ', /invite ' + targetRoom.id); } if (targetRoom.users[targetUser.userid]) { return this.errorReply("User " + targetUser.name + " is already in the room " + targetRoom.title + "!"); } if (!room.users[targetUser.userid]) { return this.errorReply("User " + this.targetUsername + " is not in the room " + room.id + "."); } if (targetUser.joinRoom(targetRoom.id) === false) return this.errorReply("User " + targetUser.name + " could not be joined to room " + targetRoom.title + ". They could be banned from the room."); this.addModCommand("" + targetUser.name + " was redirected to room " + targetRoom.title + " by " + user.name + "."); targetUser.leaveRoom(room); }, redirhelp: ["/redirect OR /redir [username], [roomname] - Attempts to redirect the user [username] to the room [roomname]. Requires: % @ & ~"], m: 'mute', mute: function (target, room, user, connection, cmd) { if (!target) return this.parse('/help mute'); if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); target = this.splitTarget(target); let targetUser = this.targetUser; if (!targetUser) return this.errorReply("User '" + this.targetUsername + "' not found."); if (target.length > MAX_REASON_LENGTH) { return this.errorReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters."); } let muteDuration = ((cmd === 'hm' || cmd === 'hourmute') ? HOURMUTE_LENGTH : MUTE_LENGTH); if (!this.can('mute', targetUser, room)) return false; let canBeMutedFurther = ((room.getMuteTime(targetUser) || 0) <= (muteDuration * 5 / 6)); if (targetUser.locked || (room.isMuted(targetUser) && !canBeMutedFurther) || room.isRoomBanned(targetUser)) { let problem = " but was already " + (targetUser.locked ? "locked" : room.isMuted(targetUser) ? "muted" : "room banned"); if (!target) { return this.privateModCommand("(" + targetUser.name + " would be muted by " + user.name + problem + ".)"); } return this.addModCommand("" + targetUser.name + " would be muted by " + user.name + problem + "." + (target ? " (" + target + ")" : "")); } if (targetUser in room.users) targetUser.popup("|modal|" + user.name + " has muted you in " + room.id + " for " + Tools.toDurationString(muteDuration) + ". " + target); this.addModCommand("" + targetUser.name + " was muted by " + user.name + " for " + Tools.toDurationString(muteDuration) + "." + (target ? " (" + target + ")" : "")); if (targetUser.autoconfirmed && targetUser.autoconfirmed !== targetUser.userid) this.privateModCommand("(" + targetUser.name + "'s ac account: " + targetUser.autoconfirmed + ")"); let userid = targetUser.getLastId(); this.add('|unlink|' + userid); if (userid !== toId(this.inputUsername)) this.add('|unlink|' + toId(this.inputUsername)); room.mute(targetUser, muteDuration, false); }, mutehelp: ["/mute OR /m [username], [reason] - Mutes a user with reason for 7 minutes. Requires: % @ * # & ~"], hm: 'hourmute', hourmute: function (target) { if (!target) return this.parse('/help hourmute'); this.run('mute'); }, hourmutehelp: ["/hourmute OR /hm [username], [reason] - Mutes a user with reason for an hour. Requires: % @ * # & ~"], um: 'unmute', unmute: function (target, room, user) { if (!target) return this.parse('/help unmute'); target = this.splitTarget(target); if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); if (!this.can('mute', null, room)) return false; let targetUser = this.targetUser; let successfullyUnmuted = room.unmute(targetUser ? targetUser.userid : this.targetUsername, "Your mute in '" + room.title + "' has been lifted."); if (successfullyUnmuted) { this.addModCommand("" + (targetUser ? targetUser.name : successfullyUnmuted) + " was unmuted by " + user.name + "."); } else { this.errorReply("" + (targetUser ? targetUser.name : this.targetUsername) + " is not muted."); } }, unmutehelp: ["/unmute [username] - Removes mute from user. Requires: % @ * # & ~"], forcelock: 'lock', l: 'lock', ipmute: 'lock', lock: function (target, room, user, connection, cmd) { if (!target) return this.parse('/help lock'); target = this.splitTarget(target); let targetUser = this.targetUser; if (!targetUser) return this.errorReply("User '" + this.targetUsername + "' not found."); if (target.length > MAX_REASON_LENGTH) { return this.errorReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters."); } if (!this.can('lock', targetUser)) return false; let name = targetUser.getLastName(); let userid = targetUser.getLastId(); if (targetUser.locked && !target) { let problem = " but was already locked"; return this.privateModCommand("(" + name + " would be locked by " + user.name + problem + ".)"); } if (targetUser.confirmed) { if (cmd === 'forcelock') { let from = targetUser.deconfirm(); Monitor.log("[CrisisMonitor] " + name + " was locked by " + user.name + " and demoted from " + from.join(", ") + "."); this.globalModlog("CRISISDEMOTE", targetUser, " from " + from.join(", ")); } else { return this.sendReply("" + name + " is a confirmed user. If you are sure you would like to lock them use /forcelock."); } } else if (cmd === 'forcelock') { return this.errorReply("Use /lock; " + name + " is not a confirmed user."); } // Destroy personal rooms of the locked user. targetUser.inRooms.forEach(roomid => { if (roomid === 'global') return; let targetRoom = Rooms.get(roomid); if (targetRoom.isPersonal && targetRoom.auth[userid] === '#') { targetRoom.destroy(); } }); targetUser.popup("|modal|" + user.name + " has locked you from talking in chats, battles, and PMing regular users." + (target ? "\n\nReason: " + target : "") + "\n\nIf you feel that your lock was unjustified, you can still PM staff members (%, @, &, and ~) to discuss it" + (Config.appealurl ? " or you can appeal:\n" + Config.appealurl : ".") + "\n\nYour lock will expire in a few days."); this.addModCommand("" + name + " was locked from talking by " + user.name + "." + (target ? " (" + target + ")" : ""), " (" + targetUser.latestIp + ")"); let alts = targetUser.getAlts(); let acAccount = (targetUser.autoconfirmed !== userid && targetUser.autoconfirmed); if (alts.length) { this.privateModCommand("(" + name + "'s " + (acAccount ? " ac account: " + acAccount + ", " : "") + "locked alts: " + alts.join(", ") + ")"); } else if (acAccount) { this.privateModCommand("(" + name + "'s ac account: " + acAccount + ")"); } this.add('|unlink|hide|' + userid); if (userid !== toId(this.inputUsername)) this.add('|unlink|hide|' + toId(this.inputUsername)); this.globalModlog("LOCK", targetUser, " by " + user.name + (target ? ": " + target : "")); Punishments.lock(targetUser, null, null, target); return true; }, lockhelp: ["/lock OR /l [username], [reason] - Locks the user from talking in all chats. Requires: % @ * & ~"], wl: 'weeklock', weeklock: function (target, room, user, connection, cmd) { if (!target) return this.parse('/help weeklock'); target = this.splitTarget(target); let targetUser = this.targetUser; if (!targetUser) return this.errorReply("User '" + this.targetUsername + "' not found."); if (target.length > MAX_REASON_LENGTH) { return this.errorReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters."); } if (!this.can('lock', targetUser)) return false; let name = targetUser.getLastName(); let userid = targetUser.getLastId(); if (targetUser.locked && !target) { let problem = " but was already locked"; return this.privateModCommand("(" + name + " would be locked by " + user.name + problem + ".)"); } if (targetUser.confirmed) { if (cmd === 'forcelock') { let from = targetUser.deconfirm(); Monitor.log("[CrisisMonitor] " + name + " was locked by " + user.name + " and demoted from " + from.join(", ") + "."); this.globalModlog("CRISISDEMOTE", targetUser, " from " + from.join(", ")); } else { return this.sendReply("" + name + " is a confirmed user. If you are sure you would like to lock them use /forcelock."); } } else if (cmd === 'forcelock') { return this.errorReply("Use /lock; " + name + " is not a confirmed user."); } // Destroy personal rooms of the locked user. targetUser.inRooms.forEach(roomid => { if (roomid === 'global') return; let targetRoom = Rooms.get(roomid); if (targetRoom.isPersonal && targetRoom.auth[userid] === '#') { targetRoom.destroy(); } }); targetUser.popup("|modal|" + user.name + " has locked you from talking in chats, battles, and PMing regular users for a week." + (target ? "\n\nReason: " + target : "") + "\n\nIf you feel that your lock was unjustified, you can still PM staff members (%, @, &, and ~) to discuss it" + (Config.appealurl ? " or you can appeal:\n" + Config.appealurl : ".") + "\n\nYour lock will expire in a few days."); this.addModCommand("" + name + " was locked from talking for a week by " + user.name + "." + (target ? " (" + target + ")" : ""), " (" + targetUser.latestIp + ")"); let alts = targetUser.getAlts(); let acAccount = (targetUser.autoconfirmed !== userid && targetUser.autoconfirmed); if (alts.length) { this.privateModCommand("(" + name + "'s " + (acAccount ? " ac account: " + acAccount + ", " : "") + "locked alts: " + alts.join(", ") + ")"); } else if (acAccount) { this.privateModCommand("(" + name + "'s ac account: " + acAccount + ")"); } this.add('|unlink|hide|' + userid); if (userid !== toId(this.inputUsername)) this.add('|unlink|hide|' + toId(this.inputUsername)); this.globalModlog("WEEKLOCK", targetUser, " by " + user.name + (target ? ": " + target : "")); Punishments.lock(targetUser, Date.now() + 7 * 24 * 60 * 60 * 1000, null, target); return true; }, weeklockhelp: ["/weeklock OR /wl [username], [reason] - Locks the user from talking in all chats for one week. Requires: % @ * & ~"], unlock: function (target, room, user) { if (!target) return this.parse('/help unlock'); if (!this.can('lock')) return false; let targetUser = Users.get(target); if (targetUser && targetUser.namelocked) { return this.errorReply(`User ${targetUser.name} is namelocked, not locked. Use /unnamelock to unnamelock them.`); } let reason = ''; if (targetUser && targetUser.locked && targetUser.locked.charAt(0) === '#') { reason = ' (' + targetUser.locked + ')'; } let unlocked = Punishments.unlock(target); if (unlocked) { this.addModCommand(unlocked.join(", ") + " " + ((unlocked.length > 1) ? "were" : "was") + " unlocked by " + user.name + "." + reason); if (!reason) this.globalModlog("UNLOCK", target, " by " + user.name); if (targetUser) targetUser.popup("" + user.name + " has unlocked you."); } else { this.errorReply("User '" + target + "' is not locked."); } }, unlockhelp: ["/unlock [username] - Unlocks the user. Requires: % @ * & ~"], forceban: 'ban', b: 'ban', ban: function (target, room, user, connection, cmd) { if (!target) return this.parse('/help ban'); target = this.splitTarget(target); let targetUser = this.targetUser; if (!targetUser) return this.errorReply("User '" + this.targetUsername + "' not found."); if (target.length > MAX_REASON_LENGTH) { return this.errorReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters."); } if (!this.can('ban', targetUser)) return false; let name = targetUser.getLastName(); let userid = targetUser.getLastId(); if (Punishments.getPunishType(userid) === 'BANNED' && !target && !targetUser.connected) { let problem = " but was already banned"; return this.privateModCommand("(" + name + " would be banned by " + user.name + problem + ".)"); } if (targetUser.confirmed) { if (cmd === 'forceban') { let from = targetUser.deconfirm(); Monitor.log("[CrisisMonitor] " + name + " was banned by " + user.name + " and demoted from " + from.join(", ") + "."); this.globalModlog("CRISISDEMOTE", targetUser, " from " + from.join(", ")); } else { return this.sendReply("" + name + " is a confirmed user. If you are sure you would like to ban them use /forceban."); } } else if (cmd === 'forceban') { return this.errorReply("Use /ban; " + name + " is not a confirmed user."); } // Destroy personal rooms of the banned user. targetUser.inRooms.forEach(roomid => { if (roomid === 'global') return; let targetRoom = Rooms.get(roomid); if (targetRoom.isPersonal && targetRoom.auth[userid] === '#') { targetRoom.destroy(); } }); targetUser.popup("|modal|" + user.name + " has banned you." + (target ? "\n\nReason: " + target : "") + (Config.appealurl ? "\n\nIf you feel that your ban was unjustified, you can appeal:\n" + Config.appealurl : "") + "\n\nYour ban will expire in a few days."); this.addModCommand("" + name + " was banned by " + user.name + "." + (target ? " (" + target + ")" : ""), " (" + targetUser.latestIp + ")"); let alts = targetUser.getAlts(); let acAccount = (targetUser.autoconfirmed !== userid && targetUser.autoconfirmed); if (alts.length) { let guests = alts.length; alts = alts.filter(alt => alt.substr(0, 7) !== '[Guest '); guests -= alts.length; this.privateModCommand("(" + name + "'s " + (acAccount ? " ac account: " + acAccount + ", " : "") + "banned alts: " + alts.join(", ") + (guests ? " [" + guests + " guests]" : "") + ")"); for (let i = 0; i < alts.length; ++i) { this.add('|unlink|' + toId(alts[i])); } } else if (acAccount) { this.privateModCommand("(" + name + "'s ac account: " + acAccount + ")"); } this.add('|unlink|hide|' + userid); if (userid !== toId(this.inputUsername)) this.add('|unlink|hide|' + toId(this.inputUsername)); Punishments.ban(targetUser, null, null, target); this.globalModlog("BAN", targetUser, " by " + user.name + (target ? ": " + target : "")); return true; }, banhelp: ["/ban OR /b [username], [reason] - Kick user from all rooms and ban user's IP address with reason. Requires: @ * & ~"], unban: function (target, room, user) { if (!target) return this.parse('/help unban'); if (!this.can('ban')) return false; let name = Punishments.unban(target); if (name) { this.addModCommand("" + name + " was unbanned by " + user.name + "."); this.globalModlog("UNBAN", name, " by " + user.name); } else { this.errorReply("User '" + target + "' is not banned."); } }, unbanhelp: ["/unban [username] - Unban a user. Requires: @ * & ~"], unbanall: function (target, room, user) { if (!this.can('rangeban')) return false; if (!target) { user.lastCommand = '/unbanall'; this.errorReply("THIS WILL UNBAN AND UNLOCK ALL USERS."); this.errorReply("To confirm, use: /unbanall confirm"); return; } if (user.lastCommand !== '/unbanall' || target !== 'confirm') { return this.parse('/help unbanall'); } // we have to do this the hard way since it's no longer a global let punishKeys = ['bannedIps', 'bannedUsers', 'lockedIps', 'lockedUsers', 'lockedRanges', 'rangeLockedUsers']; for (let i = 0; i < punishKeys.length; i++) { let dict = Punishments[punishKeys[i]]; for (let entry in dict) delete dict[entry]; } this.addModCommand("All bans and locks have been lifted by " + user.name + "."); }, unbanallhelp: ["/unbanall - Unban all IP addresses. Requires: & ~"], deroomvoiceall: function (target, room, user) { if (!this.can('editroom', null, room)) return false; if (!room.auth) return this.errorReply("Room does not have roomauth."); if (!target) { user.lastCommand = '/deroomvoiceall'; this.errorReply("THIS WILL DEROOMVOICE ALL ROOMVOICED USERS."); this.errorReply("To confirm, use: /deroomvoiceall confirm"); return; } if (user.lastCommand !== '/deroomvoiceall' || target !== 'confirm') { return this.parse('/help deroomvoiceall'); } let count = 0; for (let userid in room.auth) { if (room.auth[userid] === '+') { delete room.auth[userid]; if (userid in room.users) room.users[userid].updateIdentity(room.id); count++; } } if (!count) { return this.sendReply("(This room has zero roomvoices)"); } if (room.chatRoomData) { Rooms.global.writeChatRoomData(); } this.addModCommand("All " + count + " roomvoices have been cleared by " + user.name + "."); }, deroomvoiceallhelp: ["/deroomvoiceall - Devoice all roomvoiced users. Requires: # & ~"], rangeban: 'banip', banip: function (target, room, user) { target = this.splitTargetText(target); let targetIp = this.targetUsername.trim(); if (!targetIp || !/^[0-9.*]+$/.test(targetIp)) return this.parse('/help banip'); if (!target) return this.errorReply("/banip requires a ban reason"); if (!this.can('rangeban')) return false; Punishments.ipSearch(targetIp); if (Punishments.ips.has(targetIp)) return this.errorReply("The IP " + (targetIp.charAt(targetIp.length - 1) === '*' ? "range " : "") + targetIp + " has already been temporarily locked/banned."); Punishments.banRange(targetIp, target); this.addModCommand("" + user.name + " hour-banned the " + (target.charAt(target.length - 1) === '*' ? "IP range" : "IP") + " " + targetIp + ": " + target); }, baniphelp: ["/banip [ip] - Globally bans this IP or IP range for an hour. Accepts wildcards to ban ranges. Existing users on the IP will not be banned. Requires: & ~"], unrangeban: 'unbanip', unbanip: function (target, room, user) { target = target.trim(); if (!target) { return this.parse('/help unbanip'); } if (!this.can('rangeban')) return false; if (!Punishments.ips.has(target)) { return this.errorReply("" + target + " is not a locked/banned IP or IP range."); } Punishments.ips.delete(target); this.addModCommand("" + user.name + " unbanned the " + (target.charAt(target.length - 1) === '*' ? "IP range" : "IP") + ": " + target); }, unbaniphelp: ["/unbanip [ip] - Unbans. Accepts wildcards to ban ranges. Requires: & ~"], rangelock: 'lockip', lockip: function (target, room, user) { target = this.splitTargetText(target); let targetIp = this.targetUsername.trim(); if (!targetIp || !/^[0-9.*]+$/.test(targetIp)) return this.parse('/help lockip'); if (!target) return this.errorReply("/lockip requires a lock reason"); if (!this.can('rangeban')) return false; Punishments.ipSearch(targetIp); if (Punishments.ips.has(targetIp)) return this.sendReply("The IP " + (targetIp.charAt(targetIp.length - 1) === '*' ? "range " : "") + targetIp + " has already been temporarily locked/banned."); Punishments.lockRange(targetIp, target); this.addModCommand("" + user.name + " hour-locked the " + (target.charAt(target.length - 1) === '*' ? "IP range" : "IP") + " " + targetIp + ": " + target); }, lockiphelp: ["/lockip [ip] - Globally locks this IP or IP range for an hour. Accepts wildcards to ban ranges. Existing users on the IP will not be banned. Requires: & ~"], unrangelock: 'unlockip', rangeunlock: 'unlockip', unlockip: function (target, room, user) { target = target.trim(); if (!target) { return this.parse('/help unbanip'); } if (!this.can('rangeban')) return false; if (!Punishments.ips.has(target)) { return this.errorReply("" + target + " is not a locked/banned IP or IP range."); } Punishments.ips.delete(target); this.addModCommand("" + user.name + " unlocked the " + (target.charAt(target.length - 1) === '*' ? "IP range" : "IP") + ": " + target); }, /********************************************************* * Moderating: Other *********************************************************/ mn: 'modnote', modnote: function (target, room, user, connection) { if (!target) return this.parse('/help modnote'); if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); if (target.length > MAX_REASON_LENGTH) { return this.errorReply("The note is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters."); } if (!this.can('receiveauthmessages', null, room)) return false; return this.privateModCommand("(" + user.name + " notes: " + target + ")"); }, modnotehelp: ["/modnote [note] - Adds a moderator note that can be read through modlog. Requires: % @ * # & ~"], globalpromote: 'promote', promote: function (target, room, user, connection, cmd) { if (!target) return this.parse('/help promote'); target = this.splitTarget(target, true); let targetUser = this.targetUser; let userid = toId(this.targetUsername); let name = targetUser ? targetUser.name : this.targetUsername; if (!userid) return this.parse('/help promote'); let currentGroup = ((targetUser && targetUser.group) || Users.usergroups[userid] || ' ')[0]; let nextGroup = target; if (target === 'deauth') nextGroup = Config.groupsranking[0]; if (!nextGroup) { return this.errorReply("Please specify a group such as /globalvoice or /globaldeauth"); } if (!Config.groups[nextGroup]) { return this.errorReply("Group '" + nextGroup + "' does not exist."); } if (!cmd.startsWith('global')) { let groupid = Config.groups[nextGroup].id; if (!groupid && nextGroup === Config.groupsranking[0]) groupid = 'deauth'; if (Config.groups[nextGroup].globalonly) return this.errorReply('Did you mean /global' + groupid + '"?'); return this.errorReply('Did you mean "/room' + groupid + '" or "/global' + groupid + '"?'); } if (Config.groups[nextGroup].roomonly || Config.groups[nextGroup].battleonly) { return this.errorReply("Group '" + nextGroup + "' does not exist as a global rank."); } let groupName = Config.groups[nextGroup].name || "regular user"; if (currentGroup === nextGroup) { return this.errorReply("User '" + name + "' is already a " + groupName); } if (!user.canPromote(currentGroup, nextGroup)) { return this.errorReply("/" + cmd + " - Access denied."); } if (!Users.isUsernameKnown(userid)) { return this.errorReply("/globalpromote - WARNING: '" + name + "' is offline and unrecognized. The username might be misspelled (either by you or the person or told you) or unregistered. Use /forcepromote if you're sure you want to risk it."); } if (targetUser && !targetUser.registered) { return this.errorReply("User '" + name + "' is unregistered, and so can't be promoted."); } Users.setOfflineGroup(name, nextGroup); if (Config.groups[nextGroup].rank < Config.groups[currentGroup].rank) { this.privateModCommand("(" + name + " was demoted to " + groupName + " by " + user.name + ".)"); if (targetUser) targetUser.popup("You were demoted to " + groupName + " by " + user.name + "."); } else { this.addModCommand("" + name + " was promoted to " + groupName + " by " + user.name + "."); if (targetUser) targetUser.popup("You were promoted to " + groupName + " by " + user.name + "."); } if (targetUser) targetUser.updateIdentity(); }, promotehelp: ["/promote [username], [group] - Promotes the user to the specified group. Requires: & ~"], confirmuser: function (target) { if (!target) return this.parse('/help confirmuser'); if (!this.can('promote')) return; target = this.splitTarget(target, true); let targetUser = this.targetUser; let userid = toId(this.targetUsername); let name = targetUser ? targetUser.name : this.targetUsername; if (!userid) return this.parse('/help confirmuser'); if (!targetUser) return this.errorReply("User '" + name + "' is not online."); if (targetUser.confirmed) return this.errorReply("User '" + name + "' is already confirmed."); targetUser.setGroup(Config.groupsranking[0], true); this.sendReply("User '" + name + "' is now confirmed."); }, confirmuserhelp: ["/confirmuser [username] - Confirms the user (makes them immune to locks). Requires: & ~"], globaldemote: 'demote', demote: function (target) { if (!target) return this.parse('/help demote'); this.run('promote'); }, demotehelp: ["/demote [username], [group] - Demotes the user to the specified group. Requires: & ~"], forcepromote: function (target, room, user) { // warning: never document this command in /help if (!this.can('forcepromote')) return false; target = this.splitTarget(target, true); let name = this.targetUsername; let nextGroup = target; if (!Config.groups[nextGroup]) return this.errorReply("Group '" + nextGroup + "' does not exist."); if (Users.isUsernameKnown(name)) { return this.errorReply("/forcepromote - Don't forcepromote unless you have to."); } Users.setOfflineGroup(name, nextGroup); this.addModCommand("" + name + " was promoted to " + (Config.groups[nextGroup].name || "regular user") + " by " + user.name + "."); }, devoice: 'deauth', deauth: function (target, room, user) { return this.parse('/demote ' + target + ', deauth'); }, deglobalvoice: 'globaldeauth', deglobalauth: 'globaldeauth', globaldevoice: 'globaldeauth', globaldeauth: function (target, room, user) { return this.parse('/globaldemote ' + target + ', deauth'); }, deroomvoice: 'roomdeauth', roomdevoice: 'roomdeauth', deroomauth: 'roomdeauth', roomdeauth: function (target, room, user) { return this.parse('/roomdemote ' + target + ', deauth'); }, modchat: function (target, room, user) { if (!target) return this.sendReply("Moderated chat is currently set to: " + room.modchat); if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); if (!this.can('modchat', null, room)) return false; if (room.modchat && room.modchat.length <= 1 && Config.groupsranking.indexOf(room.modchat) > 1 && !user.can('modchatall', null, room)) { return this.errorReply("/modchat - Access denied for removing a setting higher than " + Config.groupsranking[1] + "."); } if (room.requestModchat) { let error = room.requestModchat(user); if (error) return this.errorReply(error); } target = target.toLowerCase().trim(); let currentModchat = room.modchat; switch (target) { case 'off': case 'false': case 'no': room.modchat = false; break; case 'ac': case 'autoconfirmed': room.modchat = 'autoconfirmed'; break; case 'player': target = '\u2605'; /* falls through */ default: { if (!Config.groups[target]) { this.errorReply("The rank '" + target + '" was unrecognized as a modchat level.'); return this.parse('/help modchat'); } if (Config.groupsranking.indexOf(target) > 1 && !user.can('modchatall', null, room)) { return this.errorReply("/modchat - Access denied for setting higher than " + Config.groupsranking[1] + "."); } let roomGroup = (room.auth && room.isPrivate === true ? ' ' : user.group); if (room.auth && user.userid in room.auth) roomGroup = room.auth[user.userid]; if (Config.groupsranking.indexOf(target) > Math.max(1, Config.groupsranking.indexOf(roomGroup)) && !user.can('makeroom')) { return this.errorReply("/modchat - Access denied for setting higher than " + roomGroup + "."); } room.modchat = target; break; }} if (currentModchat === room.modchat) { return this.errorReply("Modchat is already set to " + currentModchat + "."); } if (!room.modchat) { this.add("|raw|<div class=\"broadcast-blue\"><b>Moderated chat was disabled!</b><br />Anyone may talk now.</div>"); } else { let modchat = Tools.escapeHTML(room.modchat); this.add("|raw|<div class=\"broadcast-red\"><b>Moderated chat was set to " + modchat + "!</b><br />Only users of rank " + modchat + " and higher can talk.</div>"); } if (room.battle && !room.modchat && !user.can('modchat')) room.requestModchat(null); this.privateModCommand("(" + user.name + " set modchat to " + room.modchat + ")"); if (room.chatRoomData) { room.chatRoomData.modchat = room.modchat; Rooms.global.writeChatRoomData(); } }, modchathelp: ["/modchat [off/autoconfirmed/+/%/@/*/#/&/~] - Set the level of moderated chat. Requires: *, @ for off/autoconfirmed/+ options, # & ~ for all the options"], slowchat: function (target, room, user) { if (!target) return this.sendReply("Slow chat is currently set to: " + (room.slowchat ? room.slowchat : false)); if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); if (!this.can('modchat', null, room)) return false; let targetInt = parseInt(target); if (target === 'off' || target === 'disable' || target === 'false') { if (!room.slowchat) return this.errorReply("Slow chat is already disabled in this room."); room.slowchat = false; this.add("|raw|<div class=\"broadcast-blue\"><b>Slow chat was disabled!</b><br />There is no longer a set minimum time between messages.</div>"); } else if (targetInt) { if (room.userCount < SLOWCHAT_USER_REQUIREMENT) return this.errorReply("This room must have at least " + SLOWCHAT_USER_REQUIREMENT + " users to set slowchat; it only has " + room.userCount + " right now."); if (room.slowchat === targetInt) return this.errorReply("Slow chat is already set for " + room.slowchat + " seconds in this room."); if (targetInt < SLOWCHAT_MINIMUM) targetInt = SLOWCHAT_MINIMUM; if (targetInt > SLOWCHAT_MAXIMUM) targetInt = SLOWCHAT_MAXIMUM; room.slowchat = targetInt; this.add("|raw|<div class=\"broadcast-red\"><b>Slow chat was enabled!</b><br />Messages must have at least " + room.slowchat + " seconds between them.</div>"); } else { return this.parse("/help slowchat"); } this.privateModCommand("(" + user.name + " set slowchat to " + room.slowchat + ")"); if (room.chatRoomData) { room.chatRoomData.slowchat = room.slowchat; Rooms.global.writeChatRoomData(); } }, slowchathelp: ["/slowchat [number] - Sets a limit on how often users in the room can send messages, between 2 and 60 seconds. Requires @ * # & ~", "/slowchat [off/disable] - Disables slowchat in the room. Requires @ * # & ~"], stretching: function (target, room, user) { if (!target) return this.sendReply("Stretching in this room is currently set to: " + (room.filterStretching ? room.filterStretching : false)); if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); if (!this.can('editroom', null, room)) return false; if (target === 'enable' || target === 'on') { if (room.filterStretching) return this.errorReply("Stretching is already enabled in this room."); room.filterStretching = true; } else if (target === 'disable' || target === 'off') { if (!room.filterStretching) return this.errorReply("Stretching is already disabled in this room."); room.filterStretching = false; } else { return this.parse("/help stretching"); } this.privateModCommand("(" + user.name + " set stretching to " + room.filterStretching + ")"); if (room.chatRoomData) { room.chatRoomData.filterStretching = room.filterStretching; Rooms.global.writeChatRoomData(); } }, stretchinghelp: ["/stretching [enable/disable] - Toggles having the server check messages containing too much stretching. Requires # & ~"], capitals: function (target, room, user) { if (!target) return this.sendReply("Capitals in this room is currently set to: " + (room.filterCaps ? room.filterCaps : false)); if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); if (!this.can('editroom', null, room)) return false; if (target === 'enable' || target === 'on') { if (room.filterCaps) return this.errorReply("Capitals is already enabled in this room."); room.filterCaps = true; } else if (target === 'disable' || target === 'off') { if (!room.filterCaps) return this.errorReply("Capitals is already disabled in this room."); room.filterCaps = false; } else { return this.parse("/help capitals"); } this.privateModCommand("(" + user.name + " set capitals to " + room.filterCaps + ")"); if (room.chatRoomData) { room.chatRoomData.filterCaps = room.filterCaps; Rooms.global.writeChatRoomData(); } }, capitalshelp: ["/capitals [enable/disable] - Toggles having the server check messages containing too many capitals. Requires # & ~"], declare: function (target, room, user) { if (!target) return this.parse('/help declare'); if (!this.can('declare', null, room)) return false; if (!this.canTalk()) return; this.add('|raw|<div class="broadcast-blue"><b>' + Tools.escapeHTML(target) + '</b></div>'); this.logModCommand(user.name + " declared " + target); }, declarehelp: ["/declare [message] - Anonymously announces a message. Requires: # * & ~"], htmldeclare: function (target, room, user) { if (!target) return this.parse('/help htmldeclare'); if (!this.can('gdeclare', null, room)) return false; if (!this.canTalk()) return; target = this.canHTML(target); if (!target) return; this.add('|raw|<div class="broadcast-blue"><b>' + target + '</b></div>'); this.logModCommand(user.name + " declared " + target); }, htmldeclarehelp: ["/htmldeclare [message] - Anonymously announces a message using safe HTML. Requires: ~"], gdeclare: 'globaldeclare', globaldeclare: function (target, room, user) { if (!target) return this.parse('/help globaldeclare'); if (!this.can('gdeclare')) return false; target = this.canHTML(target); if (!target) return; Rooms.rooms.forEach((curRoom, id) => { if (id !== 'global') curRoom.addRaw('<div class="broadcast-blue"><b>' + target + '</b></div>').update(); }); this.logModCommand(user.name + " globally declared " + target); }, globaldeclarehelp: ["/globaldeclare [message] - Anonymously announces a message to every room on the server. Requires: ~"], cdeclare: 'chatdeclare', chatdeclare: function (target, room, user) { if (!target) return this.parse('/help chatdeclare'); if (!this.can('gdeclare')) return false; target = this.canHTML(target); if (!target) return; Rooms.rooms.forEach((curRoom, id) => { if (id !== 'global' && curRoom.type !== 'battle') curRoom.addRaw('<div class="broadcast-blue"><b>' + target + '</b></div>').update(); }); this.logModCommand(user.name + " globally declared (chat level) " + target); }, chatdeclarehelp: ["/cdeclare [message] - Anonymously announces a message to all chatrooms on the server. Requires: ~"], wall: 'announce', announce: function (target, room, user) { if (!target) return this.parse('/help announce'); if (!this.can('announce', null, room)) return false; target = this.canTalk(target); if (!target) return; return '/announce ' + target; }, announcehelp: ["/announce OR /wall [message] - Makes an announcement. Requires: % @ * # & ~"], fr: 'forcerename', forcerename: function (target, room, user) { if (!target) return this.parse('/help forcerename'); let reason = this.splitTarget(target, true); let targetUser = this.targetUser; if (!targetUser) { this.splitTarget(target); if (this.targetUser) { return this.errorReply("User has already changed their name to '" + this.targetUser.name + "'."); } return this.errorReply("User '" + target + "' not found."); } if (!this.can('forcerename', targetUser)) return false; let entry = targetUser.name + " was forced to choose a new name by " + user.name + (reason ? ": " + reason : ""); this.privateModCommand("(" + entry + ")"); Rooms.global.cancelSearch(targetUser); targetUser.resetName(); targetUser.send("|nametaken||" + user.name + " considers your name inappropriate" + (reason ? ": " + reason : ".")); return true; }, forcerenamehelp: ["/forcerename OR /fr [username], [reason] - Forcibly change a user's name and shows them the [reason]. Requires: % @ * & ~"], nl: 'namelock', namelock: function (target, room, user) { if (!target) return this.parse('/help namelock'); let reason = this.splitTarget(target, true); let targetUser = this.targetUser; if (!targetUser) { return this.errorReply("User '" + this.targetUsername + "' not found."); } if (!this.can('forcerename', targetUser)) return false; if (targetUser.namelocked) return this.errorReply("User '" + target + "' is already namelocked."); this.addModCommand("" + targetUser.name + " was namelocked by " + user.name + "." + (reason ? " (" + reason + ")" : "")); this.globalModlog("NAMELOCK", targetUser, " by " + user.name + (reason ? ": " + reason : "")); Rooms.global.cancelSearch(targetUser); Punishments.namelock(targetUser, null, null, reason); targetUser.popup("|modal|" + user.name + " has locked your name and you can't change names anymore" + (reason ? ": " + reason : ".")); return true; }, namelockhelp: ["/namelock OR /nl [username], [reason] - Name locks a user and shows them the [reason]. Requires: % @ * & ~"], unl: 'unnamelock', unnamelock: function (target, room, user) { if (!target) return this.parse('/help unnamelock'); if (!this.can('forcerename')) return false; let targetUser = Users.get(target); let reason = ''; if (targetUser && targetUser.namelocked) { reason = ' (' + targetUser.namelocked + ')'; } let unlocked = Punishments.unnamelock(target); if (unlocked) { this.addModCommand(unlocked + " was unnamelocked by " + user.name + "." + reason); if (!reason) this.globalModlog("UNNAMELOCK", target, " by " + user.name); if (targetUser) targetUser.popup("" + user.name + " has unnamelocked you."); } else { this.errorReply("User '" + target + "' is not namelocked."); } }, unnamelockhelp: ["/unnamelock [username] - Unnamelocks the user. Requires: % @ * & ~"], hidetext: function (target, room, user) { if (!target) return this.parse('/help hidetext'); this.splitTarget(target); let targetUser = this.targetUser; let name = this.targetUsername; if (!targetUser) return this.errorReply("User '" + name + "' not found."); let userid = targetUser.getLastId(); let hidetype = ''; if (!user.can('lock', targetUser) && !user.can('ban', targetUser, room)) { this.errorReply("/hidetext - Access denied."); return false; } if (targetUser.locked) { hidetype = 'hide|'; } else if ((room.bannedUsers[toId(name)] && room.bannedIps[targetUser.latestIp]) || user.can('rangeban')) { hidetype = 'roomhide|'; } else { return this.errorReply("User '" + name + "' is not banned from this room or locked."); } this.addModCommand("" + targetUser.name + "'s messages were cleared from room " + room.id + " by " + user.name + "."); this.add('|unlink|' + hidetype + userid); if (userid !== toId(this.inputUsername)) this.add('|unlink|' + hidetype + toId(this.inputUsername)); }, hidetexthelp: ["/hidetext [username] - Removes a locked or banned user's messages from chat (includes users banned from the room). Requires: % (global only), @ * # & ~"], banwords: 'banword', banword: { add: function (target, room, user) { if (!target || target === ' ') return this.parse('/help banword'); if (!user.can('declare', null, room)) return; if (!room.banwords) room.banwords = []; // Most of the regex code is copied from the client. TODO: unify them? let words = target.match(/[^,]+(,\d*}[^,]*)?/g).map(word => word.replace(/\n/g, '').trim()); for (let i = 0; i < words.length; i++) { if (/[\\^$*+?()|{}[\]]/.test(words[i])) { if (!user.can('makeroom')) return this.errorReply("Regex banwords are only allowed for leaders or above."); try { let test = new RegExp(words[i]); // eslint-disable-line no-unused-vars } catch (e) { return this.errorReply(e.message.substr(0, 28) === 'Invalid regular expression: ' ? e.message : 'Invalid regular expression: /' + words[i] + '/: ' + e.message); } } if (room.banwords.indexOf(words[i]) > -1) { return this.errorReply(words[i] + ' is already a banned phrase.'); } } room.banwords = room.banwords.concat(words); room.banwordRegex = null; if (words.length > 1) { this.privateModCommand("(The banwords '" + words.join(', ') + "' were added by " + user.name + ".)"); this.sendReply("Banned phrases succesfully added. The list is currently: " + room.banwords.join(', ')); } else { this.privateModCommand("(The banword '" + words[0] + "' was added by " + user.name + ".)"); this.sendReply("Banned phrase succesfully added. The list is currently: " + room.banwords.join(', ')); } if (room.chatRoomData) { room.chatRoomData.banwords = room.banwords; Rooms.global.writeChatRoomData(); } }, delete: function (target, room, user) { if (!target) return this.parse('/help banword'); if (!user.can('declare', null, room)) return; if (!room.banwords) return this.errorReply("This room has no banned phrases."); let words = target.match(/[^,]+(,\d*}[^,]*)?/g).map(word => word.replace(/\n/g, '').trim()); for (let i = 0; i < words.length; i++) { let index = room.banwords.indexOf(words[i]); if (index < 0) return this.errorReply(words[i] + " is not a banned phrase in this room."); room.banwords.splice(index, 1); } room.banwordRegex = null; if (words.length > 1) { this.privateModCommand("(The banwords '" + words.join(', ') + "' were removed by " + user.name + ".)"); this.sendReply("Banned phrases succesfully deleted. The list is currently: " + room.banwords.join(', ')); } else { this.privateModCommand("(The banword '" + words[0] + "' was removed by " + user.name + ".)"); this.sendReply("Banned phrase succesfully deleted. The list is currently: " + room.banwords.join(', ')); } if (room.chatRoomData) { room.chatRoomData.banwords = room.banwords; Rooms.global.writeChatRoomData(); } }, list: function (target, room, user) { if (!user.can('ban', null, room)) return; if (!room.banwords) return this.sendReply("This room has no banned phrases."); return this.sendReply("Banned phrases in room " + room.id + ": " + room.banwords.join(', ')); }, "": function (target, room, user) { return this.parse("/help banword"); }, }, banwordhelp: ["/banword add [words] - Adds the comma-separated list of phrases (& or ~ can also input regex) to the banword list of the current room. Requires: # & ~", "/banword delete [words] - Removes the comma-separated list of phrases from the banword list. Requires: # & ~", "/banword list - Shows the list of banned words in the current room. Requires: @ * # & ~"], modlog: function (target, room, user, connection) { let lines = 0; // Specific case for modlog command. Room can be indicated with a comma, lines go after the comma. // Otherwise, the text is defaulted to text search in current room's modlog. let roomId = (room.id === 'staff' ? 'global' : room.id); let hideIps = !user.can('lock'); let path = require('path'); let isWin = process.platform === 'win32'; let logPath = 'logs/modlog/'; if (target.includes(',')) { let targets = target.split(','); target = targets[1].trim(); roomId = toId(targets[0]) || room.id; } // Let's check the number of lines to retrieve or if it's a word instead if (!target.match('[^0-9]')) { lines = parseInt(target || 20); if (lines > 100) lines = 100; } let wordSearch = (!lines || lines < 0); // Control if we really, really want to check all modlogs for a word. let roomNames = ''; let filename = ''; let command = ''; if (roomId === 'all' && wordSearch) { if (!this.can('modlog')) return; roomNames = "all rooms"; // Get a list of all the rooms let fileList = fs.readdirSync('logs/modlog'); for (let i = 0; i < fileList.length; ++i) { filename += path.normalize(__dirname + '/' + logPath + fileList[i]) + ' '; } } else if (roomId.startsWith('battle-') || roomId.startsWith('groupchat-')) { return this.errorReply("Battles and groupchats do not have modlogs."); } else { if (!user.can('modlog') && !this.can('modlog', null, Rooms.get(roomId))) return; roomNames = "the room " + roomId; filename = path.normalize(__dirname + '/' + logPath + 'modlog_' + roomId + '.txt'); } // Seek for all input rooms for the lines or text if (isWin) { command = path.normalize(__dirname + '/lib/winmodlog') + ' tail ' + lines + ' ' + filename; } else { command = 'tail -' + lines + ' ' + filename + ' | tac'; } let grepLimit = 100; let strictMatch = false; if (wordSearch) { // searching for a word instead let searchString = target; strictMatch = true; // search for a 1:1 match? if (searchString.match(/^["'].+["']$/)) { searchString = searchString.substring(1, searchString.length - 1); } else if (searchString.includes('_')) { // do an exact search, the approximate search fails for underscores } else if (isWin) { // ID search with RegEx isn't implemented for windows yet (feel free to add it to winmodlog.cmd) target = '"' + target + '"'; // add quotes to target so the caller knows they are getting a strict match } else { // search for ID: allow any number of non-word characters (\W*) in between the letters we have to match. // i.e. if searching for "myUsername", also match on "My User-Name". // note that this doesn't really add a lot of unwanted results, since we use \b..\b target = toId(target); searchString = '\\b' + target.split('').join('\\W*') + '\\b'; strictMatch = false; } if (isWin) { if (strictMatch) { command = path.normalize(__dirname + '/lib/winmodlog') + ' ws ' + grepLimit + ' "' + searchString.replace(/%/g, "%%").replace(/([\^"&<>\|])/g, "^$1") + '" ' + filename; } else { // doesn't happen. ID search with RegEx isn't implemented for windows yet (feel free to add it to winmodlog.cmd and call it from here) } } else { if (strictMatch) { command = "awk '{print NR,$0}' " + filename + " | sort -nr | cut -d' ' -f2- | grep -m" + grepLimit + " -i '" + searchString.replace(/\\/g, '\\\\\\\\').replace(/["'`]/g, '\'\\$&\'').replace(/[\{\}\[\]\(\)\$\^\.\?\+\-\*]/g, '[$&]') + "'"; } else { command = "awk '{print NR,$0}' " + filename + " | sort -nr | cut -d' ' -f2- | grep -m" + grepLimit + " -Ei '" + searchString + "'"; } } } // Execute the file search to see modlog require('child_process').exec(command, (error, stdout, stderr) => { if (error && stderr) { connection.popup("/modlog empty on " + roomNames + " or erred"); console.log("/modlog error: " + error); return false; } if (stdout && hideIps) { stdout = stdout.replace(/\([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\)/g, ''); } stdout = stdout.split('\n').map(line => { let bracketIndex = line.indexOf(']'); let parenIndex = line.indexOf(')'); if (bracketIndex < 0) return Tools.escapeHTML(line); const time = line.slice(1, bracketIndex); let timestamp = Tools.toTimeStamp(new Date(time), {hour12: true}); parenIndex = line.indexOf(')'); let roomid = line.slice(bracketIndex + 3, parenIndex); if (!hideIps && Config.modloglink) { let url = Config.modloglink(time, roomid); if (url) timestamp = '<a href="' + url + '">' + timestamp + '</a>'; } return '<small>[' + timestamp + '] (' + roomid + ')</small>' + Tools.escapeHTML(line.slice(parenIndex + 1)); }).join('<br />'); if (lines) { if (!stdout) { connection.popup("The modlog is empty. (Weird.)"); } else { connection.popup("|wide||html|<p>The last " + lines + " lines of the Moderator Log of " + roomNames + ".</p><p><small>[" + Tools.toTimeStamp(new Date(), {hour12: true}) + "] ← current server time</small></p>" + stdout); } } else { if (!stdout) { connection.popup("No moderator actions containing " + target + " were found on " + roomNames + "." + (strictMatch ? "" : " Add quotes to the search parameter to search for a phrase, rather than a user.")); } else { connection.popup("|wide||html|<p>The last " + grepLimit + " logged actions containing " + target + " on " + roomNames + "." + (strictMatch ? "" : " Add quotes to the search parameter to search for a phrase, rather than a user.") + "</p><p><small>[" + Tools.toTimeStamp(new Date(), {hour12: true}) + "] ← current server time</small></p>" + stdout); } } }); }, modloghelp: ["/modlog [roomid|all], [n] - Roomid defaults to current room.", "If n is a number or omitted, display the last n lines of the moderator log. Defaults to 20.", "If n is not a number, search the moderator log for 'n' on room's log [roomid]. If you set [all] as [roomid], searches for 'n' on all rooms's logs. Requires: % @ * # & ~"], /********************************************************* * Server management commands *********************************************************/ hotpatch: function (target, room, user) { if (!target) return this.parse('/help hotpatch'); if (!this.can('hotpatch')) return false; if (Monitor.hotpatchLock) return this.errorReply("Hotpatch is currently been disabled. (" + Monitor.hotpatchLock + ")"); for (let roomid of ['development', 'staff', 'upperstaff']) { let curRoom = Rooms(roomid); if (curRoom) curRoom.add("|c|~|(" + user.name + " used /hotpatch " + target + ")").update(); } try { if (target === 'chat' || target === 'commands') { if (Monitor.hotpatchLockChat) return this.errorReply("Hotpatch has been disabled for chat. (" + Monitor.hotpatchLockChat + ")"); const ProcessManagers = require('./process-manager').cache; for (let PM of ProcessManagers.keys()) { if (PM.isChatBased) { PM.unspawn(); ProcessManagers.delete(PM); } } CommandParser.uncacheTree('./command-parser'); delete require.cache[require.resolve('./commands')]; delete require.cache[require.resolve('./chat-plugins/info')]; global.CommandParser = require('./command-parser'); let runningTournaments = Tournaments.tournaments; CommandParser.uncacheTree('./tournaments'); global.Tournaments = require('./tournaments'); Tournaments.tournaments = runningTournaments; return this.sendReply("Chat commands have been hot-patched."); } else if (target === 'tournaments') { let runningTournaments = Tournaments.tournaments; CommandParser.uncacheTree('./tournaments'); global.Tournaments = require('./tournaments'); Tournaments.tournaments = runningTournaments; return this.sendReply("Tournaments have been hot-patched."); } else if (target === 'battles') { Simulator.SimulatorProcess.respawn(); return this.sendReply("Battles have been hotpatched. Any battles started after now will use the new code; however, in-progress battles will continue to use the old code."); } else if (target === 'formats') { let toolsLoaded = !!Tools.isLoaded; // uncache the tools.js dependency tree CommandParser.uncacheTree('./tools'); // reload tools.js global.Tools = require('./tools')[toolsLoaded ? 'includeData' : 'includeFormats'](); // note: this will lock up the server for a few seconds // rebuild the formats list Rooms.global.formatListText = Rooms.global.getFormatListText(); // respawn validator processes TeamValidator.PM.respawn(); // respawn simulator processes Simulator.SimulatorProcess.respawn(); // broadcast the new formats list to clients Rooms.global.send(Rooms.global.formatListText); return this.sendReply("Formats have been hotpatched."); } else if (target === 'loginserver') { fs.unwatchFile('./config/custom.css'); CommandParser.uncacheTree('./loginserver'); global.LoginServer = require('./loginserver'); return this.sendReply("The login server has been hotpatched. New login server requests will use the new code."); } else if (target === 'learnsets' || target === 'validator') { TeamValidator.PM.respawn(); return this.sendReply("The team validator has been hotpatched. Any battles started after now will have teams be validated according to the new code."); } else if (target === 'punishments') { delete require.cache[require.resolve('./punishments')]; global.Punishments = require('./punishments'); return this.sendReply("Punishments have been hotpatched."); } else if (target === 'dnsbl') { Dnsbl.loadDatacenters(); return this.sendReply("Dnsbl has been hotpatched."); } else if (target.startsWith('disablechat')) { if (Monitor.hotpatchLockChat) return this.errorReply("Hotpatch is already disabled."); let reason = target.split(', ')[1]; if (!reason) return this.errorReply("Usage: /hotpatch disablechat, [reason]"); Monitor.hotpatchLockChat = reason; return this.sendReply("You have disabled hotpatch until the next server restart."); } else if (target.startsWith('disable')) { let reason = target.split(', ')[1]; if (!reason) return this.errorReply("Usage: /hotpatch disable, [reason]"); Monitor.hotpatchLock = reason; return this.sendReply("You have disabled hotpatch until the next server restart."); } } catch (e) { return this.errorReply("Something failed while trying to hotpatch " + target + ": \n" + e.stack); } this.errorReply("Your hot-patch command was unrecognized."); }, hotpatchhelp: ["Hot-patching the game engine allows you to update parts of Showdown without interrupting currently-running battles. Requires: ~", "Hot-patching has greater memory requirements than restarting.", "/hotpatch chat - reload commands.js and the chat-plugins", "/hotpatch battles - spawn new simulator processes", "/hotpatch validator - spawn new team validator processes", "/hotpatch formats - reload the tools.js tree, rebuild and rebroad the formats list, and spawn new simulator and team validator processes", "/hotpatch dnsbl - reloads Dnsbl datacenters", "/hotpatch disable, [reason] - disables the use of hotpatch until the next server restart"], savelearnsets: function (target, room, user) { if (!this.can('hotpatch')) return false; fs.writeFile('data/learnsets.js', 'exports.BattleLearnsets = ' + JSON.stringify(Tools.data.Learnsets) + ";\n"); this.sendReply("learnsets.js saved."); }, disableladder: function (target, room, user) { if (!this.can('disableladder')) return false; if (LoginServer.disabled) { return this.errorReply("/disableladder - Ladder is already disabled."); } LoginServer.disabled = true; this.logModCommand("The ladder was disabled by " + user.name + "."); this.add("|raw|<div class=\"broadcast-red\"><b>Due to high server load, the ladder has been temporarily disabled</b><br />Rated games will no longer update the ladder. It will be back momentarily.</div>"); }, enableladder: function (target, room, user) { if (!this.can('disableladder')) return false; if (!LoginServer.disabled) { return this.errorReply("/enable - Ladder is already enabled."); } LoginServer.disabled = false; this.logModCommand("The ladder was enabled by " + user.name + "."); this.add("|raw|<div class=\"broadcast-green\"><b>The ladder is now back.</b><br />Rated games will update the ladder now.</div>"); }, lockdown: function (target, room, user) { if (!this.can('lockdown')) return false; Rooms.global.lockdown = true; Rooms.rooms.forEach((curRoom, id) => { if (id === 'global') return; curRoom.addRaw("<div class=\"broadcast-red\"><b>The server is restarting soon.</b><br />Please finish your battles quickly. No new battles can be started until the server resets in a few minutes.</div>").update(); if (curRoom.requestKickInactive && !curRoom.battle.ended) { curRoom.requestKickInactive(user, true); if (curRoom.modchat !== '+') { curRoom.modchat = '+'; curRoom.addRaw("<div class=\"broadcast-red\"><b>Moderated chat was set to +!</b><br />Only users of rank + and higher can talk.</div>").update(); } } }); this.logEntry(user.name + " used /lockdown"); }, lockdownhelp: ["/lockdown - locks down the server, which prevents new battles from starting so that the server can eventually be restarted. Requires: ~"], prelockdown: function (target, room, user) { if (!this.can('lockdown')) return false; Rooms.global.lockdown = 'pre'; this.sendReply("Tournaments have been disabled in preparation for the server restart."); this.logEntry(user.name + " used /prelockdown"); }, slowlockdown: function (target, room, user) { if (!this.can('lockdown')) return false; Rooms.global.lockdown = true; Rooms.rooms.forEach((curRoom, id) => { if (id === 'global') return; if (curRoom.battle) return; curRoom.addRaw("<div class=\"broadcast-red\"><b>The server is restarting soon.</b><br />Please finish your battles quickly. No new battles can be started until the server resets in a few minutes.</div>").update(); }); this.logEntry(user.name + " used /slowlockdown"); }, endlockdown: function (target, room, user) { if (!this.can('lockdown')) return false; if (!Rooms.global.lockdown) { return this.errorReply("We're not under lockdown right now."); } if (Rooms.global.lockdown === true) { Rooms.rooms.forEach((curRoom, id) => { if (id !== 'global') curRoom.addRaw("<div class=\"broadcast-green\"><b>The server restart was canceled.</b></div>").update(); }); } else { this.sendReply("Preparation for the server shutdown was canceled."); } Rooms.global.lockdown = false; this.logEntry(user.name + " used /endlockdown"); }, emergency: function (target, room, user) { if (!this.can('lockdown')) return false; if (Config.emergency) { return this.errorReply("We're already in emergency mode."); } Config.emergency = true; Rooms.rooms.forEach((curRoom, id) => { if (id !== 'global') curRoom.addRaw("<div class=\"broadcast-red\">The server has entered emergency mode. Some features might be disabled or limited.</div>").update(); }); this.logEntry(user.name + " used /emergency"); }, endemergency: function (target, room, user) { if (!this.can('lockdown')) return false; if (!Config.emergency) { return this.errorReply("We're not in emergency mode."); } Config.emergency = false; Rooms.rooms.forEach((curRoom, id) => { if (id !== 'global') curRoom.addRaw("<div class=\"broadcast-green\"><b>The server is no longer in emergency mode.</b></div>").update(); }); this.logEntry(user.name + " used /endemergency"); }, kill: function (target, room, user) { if (!this.can('lockdown')) return false; if (Rooms.global.lockdown !== true) { return this.errorReply("For safety reasons, /kill can only be used during lockdown."); } if (CommandParser.updateServerLock) { return this.errorReply("Wait for /updateserver to finish before using /kill."); } for (let i in Sockets.workers) { Sockets.workers[i].kill(); } if (!room.destroyLog) { process.exit(); return; } room.destroyLog(() => { room.logEntry(user.name + " used /kill"); }, () => { process.exit(); }); // Just in the case the above never terminates, kill the process // after 10 seconds. setTimeout(() => { process.exit(); }, 10000); }, killhelp: ["/kill - kills the server. Can't be done unless the server is in lockdown state. Requires: ~"], loadbanlist: function (target, room, user, connection) { if (!this.can('hotpatch')) return false; connection.sendTo(room, "Loading ipbans.txt..."); Punishments.loadBanlist().then( () => connection.sendTo(room, "ipbans.txt has been reloaded."), error => connection.sendTo(room, "Something went wrong while loading ipbans.txt: " + error) ); }, loadbanlisthelp: ["/loadbanlist - Loads the bans located at ipbans.txt. The command is executed automatically at startup. Requires: ~"], refreshpage: function (target, room, user) { if (!this.can('hotpatch')) return false; Rooms.global.send('|refresh|'); this.logEntry(user.name + " used /refreshpage"); }, updateserver: function (target, room, user, connection) { if (!user.hasConsoleAccess(connection)) { return this.errorReply("/updateserver - Access denied."); } if (CommandParser.updateServerLock) { return this.errorReply("/updateserver - Another update is already in progress."); } CommandParser.updateServerLock = true; let logQueue = []; logQueue.push(user.name + " used /updateserver"); connection.sendTo(room, "updating..."); let exec = require('child_process').exec; exec('git diff-index --quiet HEAD --', error => { let cmd = 'git pull --rebase'; if (error) { if (error.code === 1) { // The working directory or index have local changes. cmd = 'git stash && ' + cmd + ' && git stash pop'; } else { // The most likely case here is that the user does not have // `git` on the PATH (which would be error.code === 127). connection.sendTo(room, "" + error); logQueue.push("" + error); for (let line of logQueue) { room.logEntry(line); } CommandParser.updateServerLock = false; return; } } let entry = "Running `" + cmd + "`"; connection.sendTo(room, entry); logQueue.push(entry); exec(cmd, (error, stdout, stderr) => { for (let s of ("" + stdout + stderr).split("\n")) { connection.sendTo(room, s); logQueue.push(s); } for (let line of logQueue) { room.logEntry(line); } CommandParser.updateServerLock = false; }); }); }, crashfixed: function (target, room, user) { if (Rooms.global.lockdown !== true) { return this.errorReply('/crashfixed - There is no active crash.'); } if (!this.can('hotpatch')) return false; Rooms.global.lockdown = false; if (Rooms.lobby) { Rooms.lobby.modchat = false; Rooms.lobby.addRaw("<div class=\"broadcast-green\"><b>We fixed the crash without restarting the server!</b><br />You may resume talking in the lobby and starting new battles.</div>").update(); } this.logEntry(user.name + " used /crashfixed"); }, crashfixedhelp: ["/crashfixed - Ends the active lockdown caused by a crash without the need of a restart. Requires: ~"], memusage: 'memoryusage', memoryusage: function (target) { if (!this.can('hotpatch')) return false; let memUsage = process.memoryUsage(); let results = [memUsage.rss, memUsage.heapUsed, memUsage.heapTotal]; let units = ["B", "KiB", "MiB", "GiB", "TiB"]; for (let i = 0; i < results.length; i++) { let unitIndex = Math.floor(Math.log2(results[i]) / 10); // 2^10 base log results[i] = "" + (results[i] / Math.pow(2, 10 * unitIndex)).toFixed(2) + " " + units[unitIndex]; } this.sendReply("||[Main process] RSS: " + results[0] + ", Heap: " + results[1] + " / " + results[2]); }, bash: function (target, room, user, connection) { if (!user.hasConsoleAccess(connection)) { return this.errorReply("/bash - Access denied."); } connection.sendTo(room, "$ " + target); let exec = require('child_process').exec; exec(target, (error, stdout, stderr) => { connection.sendTo(room, ("" + stdout + stderr)); }); }, eval: function (target, room, user, connection) { if (!user.hasConsoleAccess(connection)) { return this.errorReply("/eval - Access denied."); } if (!this.runBroadcast()) return; if (!this.broadcasting) this.sendReply('||>> ' + target); try { /* eslint-disable no-unused-vars */ let battle = room.battle; let me = user; this.sendReply('||<< ' + eval(target)); /* eslint-enable no-unused-vars */ } catch (e) { this.sendReply('|| << ' + ('' + e.stack).replace(/\n *at CommandContext\.exports\.commands(\.[a-z0-9]+)*\.eval [\s\S]*/m, '').replace(/\n/g, '\n||')); } }, evalbattle: function (target, room, user, connection) { if (!user.hasConsoleAccess(connection)) { return this.errorReply("/evalbattle - Access denied."); } if (!this.runBroadcast()) return; if (!room.battle) { return this.errorReply("/evalbattle - This isn't a battle room."); } room.battle.send('eval', target.replace(/\n/g, '\f')); }, ebat: 'editbattle', editbattle: function (target, room, user) { if (!this.can('forcewin')) return false; if (!target) return this.parse('/help editbattle'); if (!room.battle) { this.errorReply("/editbattle - This is not a battle room."); return false; } let cmd; let spaceIndex = target.indexOf(' '); if (spaceIndex > 0) { cmd = target.substr(0, spaceIndex).toLowerCase(); target = target.substr(spaceIndex + 1); } else { cmd = target.toLowerCase(); target = ''; } if (cmd.charAt(cmd.length - 1) === ',') cmd = cmd.slice(0, -1); let targets = target.split(','); function getPlayer(input) { let player = room.battle.players[toId(input)]; if (player) return player.slot; if (input.includes('1')) return 'p1'; if (input.includes('2')) return 'p2'; return 'p3'; } function getPokemon(input) { if (/^[0-9]+$/.test(input)) { return '.pokemon[' + (parseInt(input) - 1) + ']'; } return ".pokemon.find(p => p.speciesid==='" + toId(targets[1]) + "')"; } switch (cmd) { case 'hp': case 'h': room.battle.send('eval', "let p=" + getPlayer(targets[0]) + getPokemon(targets[1]) + ";p.sethp(" + parseInt(targets[2]) + ");if (p.isActive)battle.add('-damage',p,p.getHealth);"); break; case 'status': case 's': room.battle.send('eval', "let pl=" + getPlayer(targets[0]) + ";let p=pl" + getPokemon(targets[1]) + ";p.setStatus('" + toId(targets[2]) + "');if (!p.isActive){battle.add('','please ignore the above');battle.add('-status',pl.active[0],pl.active[0].status,'[silent]');}"); break; case 'pp': room.battle.send('eval', "let pl=" + getPlayer(targets[0]) + ";let p=pl" + getPokemon(targets[1]) + ";p.moveset[p.moves.indexOf('" + toId(targets[2]) + "')].pp = " + parseInt(targets[3])); break; case 'boost': case 'b': room.battle.send('eval', "let p=" + getPlayer(targets[0]) + getPokemon(targets[1]) + ";battle.boost({" + toId(targets[2]) + ":" + parseInt(targets[3]) + "},p)"); break; case 'volatile': case 'v': room.battle.send('eval', "let p=" + getPlayer(targets[0]) + getPokemon(targets[1]) + ";p.addVolatile('" + toId(targets[2]) + "')"); break; case 'sidecondition': case 'sc': room.battle.send('eval', "let p=" + getPlayer(targets[0]) + ".addSideCondition('" + toId(targets[1]) + "')"); break; case 'fieldcondition': case 'pseudoweather': case 'fc': room.battle.send('eval', "battle.addPseudoWeather('" + toId(targets[0]) + "')"); break; case 'weather': case 'w': room.battle.send('eval', "battle.setWeather('" + toId(targets[0]) + "')"); break; case 'terrain': case 't': room.battle.send('eval', "battle.setTerrain('" + toId(targets[0]) + "')"); break; default: this.errorReply("Unknown editbattle command: " + cmd); break; } }, editbattlehelp: ["/editbattle hp [player], [pokemon], [hp]", "/editbattle status [player], [pokemon], [status]", "/editbattle pp [player], [pokemon], [move], [pp]", "/editbattle boost [player], [pokemon], [stat], [amount]", "/editbattle volatile [player], [pokemon], [volatile]", "/editbattle sidecondition [player], [sidecondition]", "/editbattle fieldcondition [fieldcondition]", "/editbattle weather [weather]", "/editbattle terrain [terrain]", "Short forms: /ebat h OR s OR pp OR b OR v OR sc OR fc OR w OR t", "[player] must be a username or number, [pokemon] must be species name or number (not nickname), [move] must be move name"], /********************************************************* * Battle commands *********************************************************/ forfeit: function (target, room, user) { if (!room.game) return this.errorReply("This room doesn't have an active game."); if (!room.game.forfeit) { return this.errorReply("This kind of game can't be forfeited."); } if (!room.game.forfeit(user)) { return this.errorReply("Forfeit failed."); } }, choose: function (target, room, user) { if (!room.game) return this.errorReply("This room doesn't have an active game."); if (!room.game.choose) return this.errorReply("This game doesn't support /choose"); room.game.choose(user, target); }, mv: 'move', attack: 'move', move: function (target, room, user) { if (!room.game) return this.errorReply("This room doesn't have an active game."); if (!room.game.choose) return this.errorReply("This game doesn't support /choose"); room.game.choose(user, 'move ' + target); }, sw: 'switch', switch: function (target, room, user) { if (!room.game) return this.errorReply("This room doesn't have an active game."); if (!room.game.choose) return this.errorReply("This game doesn't support /choose"); room.game.choose(user, 'switch ' + parseInt(target)); }, team: function (target, room, user) { if (!room.game) return this.errorReply("This room doesn't have an active game."); if (!room.game.choose) return this.errorReply("This game doesn't support /choose"); room.game.choose(user, 'team ' + target); }, undo: function (target, room, user) { if (!room.game) return this.errorReply("This room doesn't have an active game."); if (!room.game.undo) return this.errorReply("This game doesn't support /undo"); room.game.undo(user, target); }, uploadreplay: 'savereplay', savereplay: function (target, room, user, connection) { if (!room || !room.battle) return; let logidx = Tools.getFormat(room.battle.format).team ? 3 : 0; // retrieve spectator log (0) if there are set privacy concerns let data = room.getLog(logidx).join("\n"); let datahash = crypto.createHash('md5').update(data.replace(/[^(\x20-\x7F)]+/g, '')).digest('hex'); let players = room.battle.playerNames; LoginServer.request('prepreplay', { id: room.id.substr(7), loghash: datahash, p1: players[0], p2: players[1], format: room.format, hidden: room.isPrivate ? '1' : '', }, success => { if (success && success.errorip) { connection.popup("This server's request IP " + success.errorip + " is not a registered server."); return; } connection.send('|queryresponse|savereplay|' + JSON.stringify({ log: data, id: room.id.substr(7), })); }); }, addplayer: function (target, room, user) { if (!target) return this.parse('/help addplayer'); if (!room.battle) return this.errorReply("You can only do this in battle rooms."); if (room.rated) return this.errorReply("You can only add a Player to unrated battles."); target = this.splitTarget(target, true); let targetUser = this.targetUser; let name = this.targetUsername; if (!targetUser) return this.errorReply("User " + name + " not found."); if (targetUser.can('joinbattle', null, room)) { return this.sendReply("" + name + " can already join battles as a Player."); } if (!this.can('joinbattle', null, room)) return; room.auth[targetUser.userid] = '\u2605'; this.addModCommand("" + name + " was promoted to Player by " + user.name + "."); }, addplayerhelp: ["/addplayer [username] - Allow the specified user to join the battle as a player."], joinbattle: 'joingame', joingame: function (target, room, user) { if (!room.game) return this.errorReply("This room doesn't have an active game."); if (!room.game.joinGame) return this.errorReply("This game doesn't support /joingame"); room.game.joinGame(user); }, leavebattle: 'leavegame', partbattle: 'leavegame', leavegame: function (target, room, user) { if (!room.game) return this.errorReply("This room doesn't have an active game."); if (!room.game.leaveGame) return this.errorReply("This game doesn't support /leavegame"); room.game.leaveGame(user); }, kickbattle: 'kickgame', kickgame: function (target, room, user) { if (!room.battle) return this.errorReply("You can only do this in battle rooms."); if (room.battle.tour || room.battle.rated) return this.errorReply("You can only do this in unrated non-tour battles."); target = this.splitTarget(target); let targetUser = this.targetUser; if (!targetUser || !targetUser.connected) { return this.errorReply("User " + this.targetUsername + " not found."); } if (!this.can('kick', targetUser)) return false; if (room.game.leaveGame(targetUser)) { this.addModCommand("" + targetUser.name + " was kicked from a battle by " + user.name + (target ? " (" + target + ")" : "")); } else { this.errorReply("/kickbattle - User isn't in battle."); } }, kickbattlehelp: ["/kickbattle [username], [reason] - Kicks a user from a battle with reason. Requires: % @ * & ~"], kickinactive: function (target, room, user) { if (room.requestKickInactive) { room.requestKickInactive(user); } else { this.errorReply("You can only kick inactive players from inside a room."); } }, timer: function (target, room, user) { target = toId(target); if (room.requestKickInactive) { if (target === 'off' || target === 'false' || target === 'stop') { let canForceTimer = user.can('timer', null, room); if (room.resetTimer) { room.stopKickInactive(user, canForceTimer); if (canForceTimer) room.send('|inactiveoff|Timer was turned off by staff. Please do not turn it back on until our staff say it\'s okay'); } } else if (target === 'on' || target === 'true' || !target) { room.requestKickInactive(user, user.can('timer')); } else { this.errorReply("'" + target + "' is not a recognized timer state."); } } else { this.errorReply("You can only set the timer from inside a battle room."); } }, autotimer: 'forcetimer', forcetimer: function (target, room, user) { target = toId(target); if (!this.can('autotimer')) return; if (target === 'off' || target === 'false' || target === 'stop') { Config.forcetimer = false; this.addModCommand("Forcetimer is now OFF: The timer is now opt-in. (set by " + user.name + ")"); } else if (target === 'on' || target === 'true' || !target) { Config.forcetimer = true; this.addModCommand("Forcetimer is now ON: All battles will be timed. (set by " + user.name + ")"); } else { this.errorReply("'" + target + "' is not a recognized forcetimer setting."); } }, forcetie: 'forcewin', forcewin: function (target, room, user) { if (!this.can('forcewin')) return false; if (!room.battle) { this.errorReply("/forcewin - This is not a battle room."); return false; } room.battle.endType = 'forced'; if (!target) { room.battle.tie(); this.logModCommand(user.name + " forced a tie."); return false; } let targetUser = Users.getExact(target); if (!targetUser) return this.errorReply("User '" + target + "' not found."); target = targetUser ? targetUser.userid : ''; if (target) { room.battle.win(targetUser); this.logModCommand(user.name + " forced a win for " + target + "."); } }, forcewinhelp: ["/forcetie - Forces the current match to end in a tie. Requires: & ~", "/forcewin [user] - Forces the current match to end in a win for a user. Requires: & ~"], /********************************************************* * Challenging and searching commands *********************************************************/ cancelsearch: 'search', search: function (target, room, user) { if (target) { if (Config.pmmodchat) { let userGroup = user.group; if (Config.groupsranking.indexOf(userGroup) < Config.groupsranking.indexOf(Config.pmmodchat)) { let groupName = Config.groups[Config.pmmodchat].name || Config.pmmodchat; this.popupReply("Because moderated chat is set, you must be of rank " + groupName + " or higher to search for a battle."); return false; } } Rooms.global.searchBattle(user, target); } else { Rooms.global.cancelSearch(user); } }, chall: 'challenge', challenge: function (target, room, user, connection) { target = this.splitTarget(target); let targetUser = this.targetUser; if (!targetUser || !targetUser.connected) { return this.popupReply("The user '" + this.targetUsername + "' was not found."); } if (user.locked && !targetUser.locked) { return this.popupReply("You are locked and cannot challenge unlocked users."); } if (targetUser.blockChallenges && !user.can('bypassblocks', targetUser)) { return this.popupReply("The user '" + this.targetUsername + "' is not accepting challenges right now."); } if (user.challengeTo) { return this.popupReply("You're already challenging '" + user.challengeTo.to + "'. Cancel that challenge before challenging someone else."); } if (Config.pmmodchat) { let userGroup = user.group; if (Config.groupsranking.indexOf(userGroup) < Config.groupsranking.indexOf(Config.pmmodchat)) { let groupName = Config.groups[Config.pmmodchat].name || Config.pmmodchat; this.popupReply("Because moderated chat is set, you must be of rank " + groupName + " or higher to challenge users."); return false; } } user.prepBattle(Tools.getFormat(target).id, 'challenge', connection).then(result => { if (result) user.makeChallenge(targetUser, target); }); }, bch: 'blockchallenges', blockchall: 'blockchallenges', blockchalls: 'blockchallenges', blockchallenges: function (target, room, user) { if (user.blockChallenges) return this.errorReply("You are already blocking challenges!"); user.blockChallenges = true; this.sendReply("You are now blocking all incoming challenge requests."); }, blockchallengeshelp: ["/blockchallenges - Blocks challenges so no one can challenge you. Unblock them with /unblockchallenges."], unbch: 'allowchallenges', unblockchall: 'allowchallenges', unblockchalls: 'allowchallenges', unblockchallenges: 'allowchallenges', allowchallenges: function (target, room, user) { if (!user.blockChallenges) return this.errorReply("You are already available for challenges!"); user.blockChallenges = false; this.sendReply("You are available for challenges from now on."); }, allowchallengeshelp: ["/unblockchallenges - Unblocks challenges so you can be challenged again. Block them with /blockchallenges."], cchall: 'cancelChallenge', cancelchallenge: function (target, room, user) { user.cancelChallengeTo(target); }, accept: function (target, room, user, connection) { let userid = toId(target); let format = ''; if (user.challengesFrom[userid]) format = user.challengesFrom[userid].format; if (!format) { this.popupReply(target + " cancelled their challenge before you could accept it."); return false; } user.prepBattle(Tools.getFormat(format).id, 'challenge', connection).then(result => { if (result) user.acceptChallengeFrom(userid); }); }, reject: function (target, room, user) { user.rejectChallengeFrom(toId(target)); }, saveteam: 'useteam', utm: 'useteam', useteam: function (target, room, user) { user.team = target; }, vtm: function (target, room, user, connection) { if (Monitor.countPrepBattle(connection.ip, user.name)) { connection.popup("Due to high load, you are limited to 6 team validations every 3 minutes."); return; } if (!target) return this.errorReply("Provide a valid format."); let originalFormat = Tools.getFormat(target); let format = originalFormat.effectType === 'Format' ? originalFormat : Tools.getFormat('Anything Goes'); if (format.effectType !== 'Format') return this.popupReply("Please provide a valid format."); TeamValidator(format.id).prepTeam(user.team).then(result => { let matchMessage = (originalFormat === format ? "" : "The format '" + originalFormat.name + "' was not found."); if (result.charAt(0) === '1') { connection.popup("" + (matchMessage ? matchMessage + "\n\n" : "") + "Your team is valid for " + format.name + "."); } else { connection.popup("" + (matchMessage ? matchMessage + "\n\n" : "") + "Your team was rejected for the following reasons:\n\n- " + result.slice(1).replace(/\n/g, '\n- ')); } }); }, /********************************************************* * Low-level *********************************************************/ cmd: 'query', query: function (target, room, user, connection) { // Avoid guest users to use the cmd errors to ease the app-layer attacks in emergency mode let trustable = (!Config.emergency || (user.named && user.registered)); let spaceIndex = target.indexOf(' '); let cmd = target; if (spaceIndex > 0) { cmd = target.substr(0, spaceIndex); target = target.substr(spaceIndex + 1); } else { target = ''; } if (cmd === 'userdetails') { let targetUser = Users.get(target); if (!trustable || !targetUser) { connection.send('|queryresponse|userdetails|' + JSON.stringify({ userid: toId(target), rooms: false, })); return false; } let roomList = {}; targetUser.inRooms.forEach(roomid => { if (roomid === 'global') return; let targetRoom = Rooms.get(roomid); if (!targetRoom) return; // shouldn't happen let roomData = {}; if (targetRoom.isPrivate) { if (!user.inRooms.has(roomid) && !user.games.has(roomid)) return; roomData.isPrivate = true; } if (targetRoom.battle) { let battle = targetRoom.battle; roomData.p1 = battle.p1 ? ' ' + battle.p1.name : ''; roomData.p2 = battle.p2 ? ' ' + battle.p2.name : ''; } roomList[roomid] = roomData; }); if (!targetUser.connected) roomList = false; let userdetails = { userid: targetUser.userid, avatar: targetUser.avatar, group: targetUser.group, rooms: roomList, }; connection.send('|queryresponse|userdetails|' + JSON.stringify(userdetails)); } else if (cmd === 'roomlist') { if (!trustable) return false; connection.send('|queryresponse|roomlist|' + JSON.stringify({ rooms: Rooms.global.getRoomList(target), })); } else if (cmd === 'rooms') { if (!trustable) return false; connection.send('|queryresponse|rooms|' + JSON.stringify( Rooms.global.getRooms(user) )); } else if (cmd === 'laddertop') { if (!trustable) return false; Ladders(target).getTop().then(result => { connection.send('|queryresponse|laddertop|' + JSON.stringify(result)); }); } else { // default to sending null if (!trustable) return false; connection.send('|queryresponse|' + cmd + '|null'); } }, trn: function (target, room, user, connection) { let commaIndex = target.indexOf(','); let targetName = target; let targetRegistered = false; let targetToken = ''; if (commaIndex >= 0) { targetName = target.substr(0, commaIndex); target = target.substr(commaIndex + 1); commaIndex = target.indexOf(','); targetRegistered = target; if (commaIndex >= 0) { targetRegistered = !!parseInt(target.substr(0, commaIndex)); targetToken = target.substr(commaIndex + 1); } } user.rename(targetName, targetToken, targetRegistered, connection); }, a: function (target, room, user) { if (!this.can('rawpacket')) return false; // secret sysop command room.add(target); }, /********************************************************* * Help commands *********************************************************/ commands: 'help', h: 'help', '?': 'help', help: function (target, room, user) { target = target.toLowerCase(); // overall if (target === 'help' || target === 'h' || target === '?' || target === 'commands') { this.sendReply("/help OR /h OR /? - Gives you help."); } else if (!target) { this.sendReply("COMMANDS: /msg, /reply, /logout, /challenge, /search, /rating, /whois"); this.sendReply("OPTION COMMANDS: /nick, /avatar, /ignore, /away, /back, /timestamps, /highlight"); this.sendReply("INFORMATIONAL COMMANDS: /data, /dexsearch, /movesearch, /groups, /faq, /rules, /intro, /formatshelp, /othermetas, /learn, /analysis, /calc (replace / with ! to broadcast. Broadcasting requires: + % @ * # & ~)"); if (user.group !== Config.groupsranking[0]) { this.sendReply("DRIVER COMMANDS: /warn, /mute, /hourmute, /unmute, /alts, /forcerename, /modlog, /modnote, /lock, /unlock, /announce, /redirect"); this.sendReply("MODERATOR COMMANDS: /ban, /unban, /ip, /modchat"); this.sendReply("LEADER COMMANDS: /declare, /forcetie, /forcewin, /promote, /demote, /banip, /host, /unbanall"); } this.sendReply("For an overview of room commands, use /roomhelp"); this.sendReply("For details of a specific command, use something like: /help data"); } else { let altCommandHelp; let helpCmd; let targets = target.split(' '); let allCommands = CommandParser.commands; if (typeof allCommands[target] === 'string') { // If a function changes with command name, help for that command name will be searched first. altCommandHelp = target + 'help'; if (altCommandHelp in allCommands) { helpCmd = altCommandHelp; } else { helpCmd = allCommands[target] + 'help'; } } else if (targets.length > 1 && typeof allCommands[targets[0]] === 'object') { // Handle internal namespace commands let helpCmd = targets[targets.length - 1] + 'help'; let namespace = allCommands[targets[0]]; for (let i = 1; i < targets.length - 1; i++) { if (!namespace[targets[i]]) return this.errorReply("Help for the command '" + target + "' was not found. Try /help for general help"); namespace = namespace[targets[i]]; } if (typeof namespace[helpCmd] === 'object') return this.sendReply(namespace[helpCmd].join('\n')); if (typeof namespace[helpCmd] === 'function') return this.parse('/' + targets.slice(0, targets.length - 1).concat(helpCmd).join(' ')); return this.errorReply("Help for the command '" + target + "' was not found. Try /help for general help"); } else { helpCmd = target + 'help'; } if (helpCmd in allCommands) { if (typeof allCommands[helpCmd] === 'function') { // If the help command is a function, parse it instead this.parse('/' + helpCmd); } else if (Array.isArray(allCommands[helpCmd])) { this.sendReply(allCommands[helpCmd].join('\n')); } } else { this.errorReply("Help for the command '" + target + "' was not found. Try /help for general help"); } } }, }; process.nextTick(() => { CommandParser.multiLinePattern.register('>>>? '); CommandParser.multiLinePattern.register('/(room|staff)(topic|intro) '); });
commands.js
/** * System commands * Pokemon Showdown - http://pokemonshowdown.com/ * * These are system commands - commands required for Pokemon Showdown * to run. A lot of these are sent by the client. * * System commands should not be modified, added, or removed. If you'd * like to modify or add commands, add or edit files in chat-plugins/ * * For the API, see chat-plugins/COMMANDS.md * * @license MIT license */ 'use strict'; /* eslint no-else-return: "error" */ const crypto = require('crypto'); const fs = require('fs'); const MAX_REASON_LENGTH = 300; const MUTE_LENGTH = 7 * 60 * 1000; const HOURMUTE_LENGTH = 60 * 60 * 1000; const SLOWCHAT_MINIMUM = 2; const SLOWCHAT_MAXIMUM = 60; const SLOWCHAT_USER_REQUIREMENT = 10; exports.commands = { version: function (target, room, user) { if (!this.runBroadcast()) return; this.sendReplyBox("Server version: <b>" + CommandParser.package.version + "</b>"); }, auth: 'authority', stafflist: 'authority', globalauth: 'authority', authlist: 'authority', authority: function (target, room, user, connection) { if (target) { let targetRoom = Rooms.search(target); let unavailableRoom = targetRoom && (targetRoom !== room && (targetRoom.modjoin || targetRoom.staffRoom) && !user.can('makeroom')); if (targetRoom && !unavailableRoom) return this.parse('/roomauth1 ' + target); return this.parse('/userauth ' + target); } let rankLists = {}; let ranks = Object.keys(Config.groups); for (let u in Users.usergroups) { let rank = Users.usergroups[u].charAt(0); if (rank === ' ' || rank === '+') continue; // In case the usergroups.csv file is not proper, we check for the server ranks. if (ranks.includes(rank)) { let name = Users.usergroups[u].substr(1); if (!rankLists[rank]) rankLists[rank] = []; if (name) rankLists[rank].push(name); } } let buffer = Object.keys(rankLists).sort((a, b) => (Config.groups[b] || {rank: 0}).rank - (Config.groups[a] || {rank: 0}).rank ).map(r => (Config.groups[r] ? "**" + Config.groups[r].name + "s** (" + r + ")" : r) + ":\n" + rankLists[r].sort((a, b) => toId(a).localeCompare(toId(b))).join(", ") ); if (!buffer.length) return connection.popup("This server has no global authority."); connection.popup(buffer.join("\n\n")); }, authhelp: ["/auth - Show global staff for the server.", "/auth [room] - Show what roomauth a room has.", "/auth [user] - Show what global and roomauth a user has."], me: function (target, room, user, connection) { // By default, /me allows a blank message if (!target) target = ''; target = this.canTalk('/me ' + target); if (!target) return; return target; }, mee: function (target, room, user, connection) { // By default, /mee allows a blank message if (!target) target = ''; target = target.trim(); if (/[A-Za-z0-9]/.test(target.charAt(0))) { return this.errorReply("To prevent confusion, /mee can't start with a letter or number."); } target = this.canTalk('/mee ' + target); if (!target) return; return target; }, 'battle!': 'battle', battle: function (target, room, user, connection, cmd) { if (cmd === 'battle') return this.sendReply("What?! How are you not more excited to battle?! Try /battle! to show me you're ready."); if (!target) target = "randombattle"; return this.parse("/search " + target); }, avatar: function (target, room, user) { if (!target) return this.parse('/avatars'); let parts = target.split(','); let avatarid = toId(parts[0]); let avatar = 0; let avatarTable = { lucas: 1, dawn: 2, youngster: 3, lass: 4, camper: 5, picnicker: 6, bugcatcher: 7, aromalady: 8, twins: 9, hiker: 10, battlegirl: 11, fisherman: 12, cyclist: 13, cyclistf: 14, blackbelt: 15, artist: 16, pokemonbreeder: 17, pokemonbreederf: 18, cowgirl: 19, jogger: 20, pokefan: 21, pokefanf: 22, pokekid: 23, youngcouple: 24, acetrainer: 25, acetrainerf: 26, waitress: 27, veteran: 28, ninjaboy: 29, dragontamer: 30, birdkeeper: 31, doubleteam: 32, richboy: 33, lady: 34, gentleman: 35, socialite: 36, madame: 36, beauty: 37, collector: 38, policeman: 39, pokemonranger: 40, pokemonrangerf: 41, scientist: 42, swimmer: 43, swimmerf: 44, tuber: 45, tuberf: 46, sailor: 47, sisandbro: 48, ruinmaniac: 49, psychic: 50, psychicf: 51, gambler: 52, dppguitarist: 53, acetrainersnow: 54, acetrainersnowf: 55, skier: 56, skierf: 57, roughneck: 58, clown: 59, worker: 60, schoolkid: 61, schoolkidf: 62, roark: 63, barry: 64, byron: 65, aaron: 66, bertha: 67, flint: 68, lucian: 69, dppcynthia: 70, bellepa: 71, rancher: 72, mars: 73, galacticgrunt: 74, gardenia: 75, crasherwake: 76, maylene: 77, fantina: 78, candice: 79, volkner: 80, parasollady: 81, waiter: 82, interviewers: 83, cameraman: 84, oli: 84, reporter: 85, roxy: 85, idol: 86, grace: 86, cyrus: 87, jupiter: 88, saturn: 89, galacticgruntf: 90, argenta: 91, palmer: 92, thorton: 93, buck: 94, darach: 95, marley: 96, mira: 97, cheryl: 98, riley: 99, dahlia: 100, ethan: 101, lyra: 102, archer: 132, ariana: 133, proton: 134, petrel: 135, mysteryman: 136, eusine: 136, ptlucas: 137, ptdawn: 138, falkner: 141, bugsy: 142, whitney: 143, morty: 144, chuck: 145, jasmine: 146, pryce: 147, clair: 148, will: 149, koga: 150, bruno: 151, karen: 152, lance: 153, brock: 154, misty: 155, ltsurge: 156, erica: 157, janine: 158, sabrina: 159, blaine: 160, blue: 161, red2: 162, red: 163, silver: 164, giovanni: 165, unknownf: 166, unknownm: 167, unknown: 168, hilbert: 169, hilda: 170, chili: 179, cilan: 180, cress: 181, lenora: 188, burgh: 189, elesa: 190, clay: 191, skyla: 192, cheren: 206, bianca: 207, n: 209, brycen: 222, iris: 223, drayden: 224, shauntal: 246, marshal: 247, grimsley: 248, caitlin: 249, ghetsis: 250, ingo: 256, alder: 257, cynthia: 260, emmet: 261, dueldiskhilbert: 262, dueldiskhilda: 263, hugh: 264, rosa: 265, nate: 266, colress: 267, bw2beauty: 268, bw2ghetsis: 269, bw2plasmagrunt: 270, bw2plasmagruntf: 271, bw2iris: 272, brycenman: 273, shadowtriad: 274, rood: 275, zinzolin: 276, bw2cheren: 277, marlon: 278, roxie: 279, roxanne: 280, brawly: 281, wattson: 282, flannery: 283, norman: 284, winona: 285, tate: 286, liza: 287, juan: 288, guitarist: 289, steven: 290, wallace: 291, magicqueen: 292, bellelba: 292, benga: 293, bw2elesa: '#bw2elesa', teamrocket: '#teamrocket', yellow: '#yellow', zinnia: '#zinnia', clemont: '#clemont', }; if (avatarid in avatarTable) { avatar = avatarTable[avatarid]; } else { avatar = parseInt(avatarid); } if (typeof avatar === 'number' && (!avatar || avatar > 294 || avatar < 1)) { if (!parts[1]) { this.errorReply("Invalid avatar."); } return false; } user.avatar = avatar; if (!parts[1]) { this.sendReply("Avatar changed to:\n" + '|raw|<img src="//play.pokemonshowdown.com/sprites/trainers/' + (typeof avatar === 'string' ? avatar.substr(1) : avatar) + '.png" alt="" width="80" height="80" />'); } }, avatarhelp: ["/avatar [avatar number 1 to 293] - Change your trainer sprite."], signout: 'logout', logout: function (target, room, user) { user.resetName(); }, requesthelp: 'report', report: function (target, room, user) { if (room.id === 'help') { this.sendReply("Ask one of the Moderators (@) in the Help room."); } else { this.parse('/join help'); } }, r: 'reply', reply: function (target, room, user) { if (!target) return this.parse('/help reply'); if (!user.lastPM) { return this.errorReply("No one has PMed you yet."); } return this.parse('/msg ' + (user.lastPM || '') + ', ' + target); }, replyhelp: ["/reply OR /r [message] - Send a private message to the last person you received a message from, or sent a message to."], pm: 'msg', whisper: 'msg', w: 'msg', msg: function (target, room, user, connection) { if (!target) return this.parse('/help msg'); target = this.splitTarget(target); let targetUser = this.targetUser; if (!target) { this.errorReply("You forgot the comma."); return this.parse('/help msg'); } this.pmTarget = (targetUser || this.targetUsername); if (!targetUser) { this.errorReply("User " + this.targetUsername + " not found. Did you misspell their name?"); return this.parse('/help msg'); } if (!targetUser.connected) { return this.errorReply("User " + this.targetUsername + " is offline."); } if (Config.pmmodchat && !user.matchesRank(Config.pmmodchat)) { let groupName = Config.groups[Config.pmmodchat] && Config.groups[Config.pmmodchat].name || Config.pmmodchat; return this.errorReply("Because moderated chat is set, you must be of rank " + groupName + " or higher to PM users."); } if (user.locked && !targetUser.can('lock')) { return this.errorReply("You can only private message members of the global moderation team (users marked by @ or above in the Help room) when locked."); } if (targetUser.locked && !user.can('lock')) { return this.errorReply("This user is locked and cannot PM."); } if (targetUser.ignorePMs && targetUser.ignorePMs !== user.group && !user.can('lock')) { if (!targetUser.can('lock')) { return this.errorReply("This user is blocking private messages right now."); } else if (targetUser.can('bypassall')) { return this.errorReply("This admin is too busy to answer private messages right now. Please contact a different staff member."); } } if (user.ignorePMs && user.ignorePMs !== targetUser.group && !targetUser.can('lock')) { return this.errorReply("You are blocking private messages right now."); } target = this.canTalk(target, null, targetUser); if (!target) return false; let message; if (target.charAt(0) === '/' && target.charAt(1) !== '/') { // PM command let innerCmdIndex = target.indexOf(' '); let innerCmd = (innerCmdIndex >= 0 ? target.slice(1, innerCmdIndex) : target.slice(1)); let innerTarget = (innerCmdIndex >= 0 ? target.slice(innerCmdIndex + 1) : ''); switch (innerCmd) { case 'me': case 'mee': case 'announce': break; case 'ME': case 'MEE': message = '|pm|' + user.getIdentity().toUpperCase() + '|' + targetUser.getIdentity() + '|/' + innerCmd.toLowerCase() + ' ' + innerTarget; break; case 'invite': case 'inv': { let targetRoom = Rooms.search(innerTarget); if (!targetRoom || targetRoom === Rooms.global) return this.errorReply('The room "' + innerTarget + '" does not exist.'); if (targetRoom.staffRoom && !targetUser.isStaff) return this.errorReply('User "' + this.targetUsername + '" requires global auth to join room "' + targetRoom.id + '".'); if (targetRoom.modjoin) { if (targetRoom.auth && (targetRoom.isPrivate === true || targetUser.group === ' ') && !(targetUser.userid in targetRoom.auth)) { this.parse('/roomvoice ' + targetUser.name, false, targetRoom); if (!(targetUser.userid in targetRoom.auth)) { return; } } } if (targetRoom.isPrivate === true && targetRoom.modjoin && targetRoom.auth) { if (!(user.userid in targetRoom.auth)) { return this.errorReply('The room "' + innerTarget + '" does not exist.'); } if (Config.groupsranking.indexOf(targetRoom.auth[targetUser.userid] || ' ') < Config.groupsranking.indexOf(targetRoom.modjoin) && !targetUser.can('bypassall')) { return this.errorReply('The user "' + targetUser.name + '" does not have permission to join "' + innerTarget + '".'); } } if (targetRoom.auth && targetRoom.isPrivate && !(user.userid in targetRoom.auth) && !user.can('makeroom')) { return this.errorReply('You do not have permission to invite people to this room.'); } target = '/invite ' + targetRoom.id; break; } default: return this.errorReply("The command '/" + innerCmd + "' was unrecognized or unavailable in private messages. To send a message starting with '/" + innerCmd + "', type '//" + innerCmd + "'."); } } if (!message) message = '|pm|' + user.getIdentity() + '|' + targetUser.getIdentity() + '|' + target; user.send(message); if (targetUser !== user) targetUser.send(message); targetUser.lastPM = user.userid; user.lastPM = targetUser.userid; }, msghelp: ["/msg OR /whisper OR /w [username], [message] - Send a private message."], pminfobox: function (target, room, user, connection) { if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); if (!user.can('addhtml', null, room)) return false; if (!target) return this.parse("/help pminfobox"); target = this.canHTML(target); if (!target) return; target = this.splitTarget(target); let targetUser = this.targetUser; if (!targetUser || !targetUser.connected) return this.errorReply("User " + targetUser + " is not currently online."); if (!(targetUser in room.users) && !user.can('addhtml')) return this.errorReply("You do not have permission to use this command to users who are not in this room."); if (targetUser.ignorePMs) return this.errorReply("This user is currently ignoring PMs."); if (targetUser.locked) return this.errorReply("This user is currently locked, so you cannot send them a pminfobox."); // Apply the infobox to the message target = '/raw <div class="infobox">' + target + '</div>'; let message = '|pm|' + user.getIdentity() + '|' + targetUser.getIdentity() + '|' + target; user.send(message); if (targetUser !== user) targetUser.send(message); targetUser.lastPM = user.userid; user.lastPM = targetUser.userid; }, pminfoboxhelp: ["/pminfobox [user], [html]- PMs an [html] infobox to [user]. Requires * ~"], blockpm: 'ignorepms', blockpms: 'ignorepms', ignorepm: 'ignorepms', ignorepms: function (target, room, user) { if (user.ignorePMs === (target || true)) return this.errorReply("You are already blocking private messages! To unblock, use /unblockpms"); if (user.can('lock') && !user.can('bypassall')) return this.errorReply("You are not allowed to block private messages."); user.ignorePMs = true; if (target in Config.groups) { user.ignorePMs = target; return this.sendReply("You are now blocking private messages, except from staff and " + target + "."); } return this.sendReply("You are now blocking private messages, except from staff."); }, ignorepmshelp: ["/blockpms - Blocks private messages. Unblock them with /unignorepms."], unblockpm: 'unignorepms', unblockpms: 'unignorepms', unignorepm: 'unignorepms', unignorepms: function (target, room, user) { if (!user.ignorePMs) return this.errorReply("You are not blocking private messages! To block, use /blockpms"); user.ignorePMs = false; return this.sendReply("You are no longer blocking private messages."); }, unignorepmshelp: ["/unblockpms - Unblocks private messages. Block them with /blockpms."], idle: 'away', afk: 'away', away: function (target, room, user) { this.parse('/blockchallenges'); this.parse('/blockpms ' + target); }, awayhelp: ["/away - Blocks challenges and private messages. Unblock them with /back."], unaway: 'back', unafk: 'back', back: function () { this.parse('/unblockpms'); this.parse('/unblockchallenges'); }, backhelp: ["/back - Unblocks challenges and/or private messages, if either are blocked."], rank: function (target, room, user) { if (!target) target = user.name; Ladders.visualizeAll(target).then(values => { let buffer = '<div class="ladder"><table>'; buffer += '<tr><td colspan="8">User: <strong>' + Tools.escapeHTML(target) + '</strong></td></tr>'; let ratings = values.join(''); if (!ratings) { buffer += '<tr><td colspan="8"><em>This user has not played any ladder games yet.</em></td></tr>'; } else { buffer += '<tr><th>Format</th><th><abbr title="Elo rating">Elo</abbr></th><th>W</th><th>L</th><th>Total</th>'; buffer += ratings; } buffer += '</table></div>'; this.sendReply('|raw|' + buffer); }); }, makeprivatechatroom: 'makechatroom', makechatroom: function (target, room, user, connection, cmd) { if (!this.can('makeroom')) return; // `,` is a delimiter used by a lot of /commands // `|` and `[` are delimiters used by the protocol // `-` has special meaning in roomids if (target.includes(',') || target.includes('|') || target.includes('[') || target.includes('-')) { return this.errorReply("Room titles can't contain any of: ,|[-"); } let id = toId(target); if (!id) return this.parse('/help makechatroom'); // Check if the name already exists as a room or alias if (Rooms.search(id)) return this.errorReply("The room '" + target + "' already exists."); if (!Rooms.global.addChatRoom(target)) return this.errorReply("An error occurred while trying to create the room '" + target + "'."); if (cmd === 'makeprivatechatroom') { let targetRoom = Rooms.search(target); targetRoom.isPrivate = true; targetRoom.chatRoomData.isPrivate = true; Rooms.global.writeChatRoomData(); if (Rooms.get('upperstaff')) { Rooms.get('upperstaff').add('|raw|<div class="broadcast-green">Private chat room created: <b>' + Tools.escapeHTML(target) + '</b></div>').update(); } this.sendReply("The private chat room '" + target + "' was created."); } else { if (Rooms.get('staff')) { Rooms.get('staff').add('|raw|<div class="broadcast-green">Public chat room created: <b>' + Tools.escapeHTML(target) + '</b></div>').update(); } if (Rooms.get('upperstaff')) { Rooms.get('upperstaff').add('|raw|<div class="broadcast-green">Public chat room created: <b>' + Tools.escapeHTML(target) + '</b></div>').update(); } this.sendReply("The chat room '" + target + "' was created."); } }, makechatroomhelp: ["/makechatroom [roomname] - Creates a new room named [roomname]. Requires: & ~"], makegroupchat: function (target, room, user, connection, cmd) { if (!user.autoconfirmed) { return this.errorReply("You must be autoconfirmed to make a groupchat."); } if (!user.confirmed) { return this.errorReply("You must be global voice or roomdriver+ in some public room to make a groupchat."); } // if (!this.can('makegroupchat')) return false; if (target.length > 64) return this.errorReply("Title must be under 32 characters long."); let targets = target.split(',', 2); // Title defaults to a random 8-digit number. let title = targets[0].trim(); if (title.length >= 32) { return this.errorReply("Title must be under 32 characters long."); } else if (!title) { title = ('' + Math.floor(Math.random() * 100000000)); } else if (Config.chatfilter) { let filterResult = Config.chatfilter.call(this, title, user, null, connection); if (!filterResult) return; if (title !== filterResult) { return this.errorReply("Invalid title."); } } // `,` is a delimiter used by a lot of /commands // `|` and `[` are delimiters used by the protocol // `-` has special meaning in roomids if (title.includes(',') || title.includes('|') || title.includes('[') || title.includes('-')) { return this.errorReply("Room titles can't contain any of: ,|[-"); } // Even though they're different namespaces, to cut down on confusion, you // can't share names with registered chatrooms. let existingRoom = Rooms.search(toId(title)); if (existingRoom && !existingRoom.modjoin) return this.errorReply("The room '" + title + "' already exists."); // Room IDs for groupchats are groupchat-TITLEID let titleid = toId(title); if (!titleid) { titleid = '' + Math.floor(Math.random() * 100000000); } let roomid = 'groupchat-' + user.userid + '-' + titleid; // Titles must be unique. if (Rooms.search(roomid)) return this.errorReply("A group chat named '" + title + "' already exists."); // Tab title is prefixed with '[G]' to distinguish groupchats from // registered chatrooms if (Monitor.countGroupChat(connection.ip)) { this.errorReply("Due to high load, you are limited to creating 4 group chats every hour."); return; } // Privacy settings, default to hidden. let privacy = (toId(targets[1]) === 'private') ? true : 'hidden'; let groupChatLink = '<code>&lt;&lt;' + roomid + '>></code>'; let groupChatURL = ''; if (Config.serverid) { groupChatURL = 'http://' + (Config.serverid === 'showdown' ? 'psim.us' : Config.serverid + '.psim.us') + '/' + roomid; groupChatLink = '<a href="' + groupChatURL + '">' + groupChatLink + '</a>'; } let titleHTML = ''; if (/^[0-9]+$/.test(title)) { titleHTML = groupChatLink; } else { titleHTML = Tools.escapeHTML(title) + ' <small style="font-weight:normal;font-size:9pt">' + groupChatLink + '</small>'; } let targetRoom = Rooms.createChatRoom(roomid, '[G] ' + title, { isPersonal: true, isPrivate: privacy, auth: {}, introMessage: '<h2 style="margin-top:0">' + titleHTML + '</h2><p>There are several ways to invite people:<br />- in this chat: <code>/invite USERNAME</code><br />- anywhere in PS: link to <code>&lt;&lt;' + roomid + '>></code>' + (groupChatURL ? '<br />- outside of PS: link to <a href="' + groupChatURL + '">' + groupChatURL + '</a>' : '') + '</p><p>This room will expire after 40 minutes of inactivity or when the server is restarted.</p><p style="margin-bottom:0"><button name="send" value="/roomhelp">Room management</button>', }); if (targetRoom) { // The creator is RO. targetRoom.auth[user.userid] = '#'; // Join after creating room. No other response is given. user.joinRoom(targetRoom.id); return; } return this.errorReply("An unknown error occurred while trying to create the room '" + title + "'."); }, makegroupchathelp: ["/makegroupchat [roomname], [hidden|private] - Creates a group chat named [roomname]. Leave off privacy to default to hidden. Requires global voice or roomdriver+ in a public room to make a groupchat."], deregisterchatroom: function (target, room, user) { if (!this.can('makeroom')) return; this.errorReply("NOTE: You probably want to use `/deleteroom` now that it exists."); let id = toId(target); if (!id) return this.parse('/help deregisterchatroom'); let targetRoom = Rooms.search(id); if (!targetRoom) return this.errorReply("The room '" + target + "' doesn't exist."); target = targetRoom.title || targetRoom.id; if (Rooms.global.deregisterChatRoom(id)) { this.sendReply("The room '" + target + "' was deregistered."); this.sendReply("It will be deleted as of the next server restart."); return; } return this.errorReply("The room '" + target + "' isn't registered."); }, deregisterchatroomhelp: ["/deregisterchatroom [roomname] - Deletes room [roomname] after the next server restart. Requires: & ~"], deletechatroom: 'deleteroom', deletegroupchat: 'deleteroom', deleteroom: function (target, room, user) { let roomid = target.trim(); if (!roomid) return this.parse('/help deleteroom'); let targetRoom = Rooms.search(roomid); if (!targetRoom) return this.errorReply("The room '" + target + "' doesn't exist."); if (room.isPersonal) { if (!this.can('editroom', null, targetRoom)) return; } else { if (!this.can('makeroom')) return; } target = targetRoom.title || targetRoom.id; if (targetRoom.id === 'global') { return this.errorReply("This room can't be deleted."); } if (targetRoom.chatRoomData) { if (targetRoom.isPrivate) { if (Rooms.get('upperstaff')) { Rooms.get('upperstaff').add(`|raw|<div class="broadcast-red">Private chat room deleted by ${user.userid}: <b>${Tools.escapeHTML(target)}</b></div>`).update(); } } else { if (Rooms.get('staff')) { Rooms.get('staff').add('|raw|<div class="broadcast-red">Public chat room deleted: <b>' + Tools.escapeHTML(target) + '</b></div>').update(); } if (Rooms.get('upperstaff')) { Rooms.get('upperstaff').add(`|raw|<div class="broadcast-red">Public chat room deleted by ${user.userid}: <b>${Tools.escapeHTML(target)}</b></div>`).update(); } } } targetRoom.add("|raw|<div class=\"broadcast-red\"><b>This room has been deleted.</b></div>"); targetRoom.update(); // |expire| needs to be its own message targetRoom.add("|expire|This room has been deleted."); this.sendReply("The room '" + target + "' was deleted."); targetRoom.update(); targetRoom.destroy(); }, deleteroomhelp: ["/deleteroom [roomname] - Deletes room [roomname]. Requires: & ~"], hideroom: 'privateroom', hiddenroom: 'privateroom', secretroom: 'privateroom', publicroom: 'privateroom', privateroom: function (target, room, user, connection, cmd) { if (room.battle || room.isPersonal) { if (!this.can('editroom', null, room)) return; } else { // registered chatrooms show up on the room list and so require // higher permissions to modify privacy settings if (!this.can('makeroom')) return; } let setting; switch (cmd) { case 'privateroom': return this.parse('/help privateroom'); case 'publicroom': setting = false; break; case 'secretroom': setting = true; break; default: if (room.isPrivate === true && target !== 'force') { return this.sendReply(`This room is a secret room. Use "/publicroom" to make it public, or "/hiddenroom force" to force it hidden.`); } setting = 'hidden'; break; } if ((setting === true || room.isPrivate === true) && !room.isPersonal) { if (!this.can('makeroom')) return; } if (target === 'off' || !setting) { if (!room.isPrivate) { return this.errorReply(`This room is already public.`); } if (room.isPersonal) return this.errorReply(`This room can't be made public.`); if (room.privacySetter && user.can('nooverride', null, room) && !user.can('makeroom')) { if (!room.privacySetter.has(user.userid)) { const privacySetters = Array.from(room.privacySetter).join(', '); return this.errorReply(`You can't make the room public since you didn't make it private - only ${privacySetters} can.`); } room.privacySetter.delete(user.userid); if (room.privacySetter.size) { const privacySetters = Array.from(room.privacySetter).join(', '); return this.sendReply(`You are no longer forcing the room to stay private, but ${privacySetters} also need${Tools.plural(room.privacySetter, '', 's')} to use /publicroom to make the room public.`); } } delete room.isPrivate; room.privacySetter = null; this.addModCommand(`${user.name} made this room public.`); if (room.chatRoomData) { delete room.chatRoomData.isPrivate; Rooms.global.writeChatRoomData(); } } else { const settingName = (setting === true ? 'secret' : setting); if (room.isPrivate === setting) { if (room.privacySetter && !room.privacySetter.has(user.userid)) { room.privacySetter.add(user.userid); return this.sendReply(`This room is already ${settingName}, but is now forced to stay that way until you use /publicroom.`); } return this.errorReply(`This room is already ${settingName}.`); } room.isPrivate = setting; this.addModCommand(`${user.name} made this room ${settingName}.`); if (room.chatRoomData) { room.chatRoomData.isPrivate = setting; Rooms.global.writeChatRoomData(); } room.privacySetter = new Set([user.userid]); } }, privateroomhelp: ["/secretroom - Makes a room secret. Secret rooms are visible to & and up. Requires: & ~", "/hiddenroom [on/off] - Makes a room hidden. Hidden rooms are visible to % and up, and inherit global ranks. Requires: \u2605 & ~", "/publicroom - Makes a room public. Requires: \u2605 & ~"], modjoin: function (target, room, user) { if (!target) { const modjoinSetting = room.modjoin === true ? "sync" : room.modjoin || "off"; return this.sendReply(`Modjoin is currently set to: ${modjoinSetting}`); } if (room.battle || room.isPersonal) { if (!this.can('editroom', null, room)) return; } else { if (!this.can('makeroom')) return; } if (room.tour && !room.tour.modjoin) return this.errorReply(`You can't do this in tournaments where modjoin is prohibited.`); if (target === 'off' || target === 'false') { if (!room.modjoin) return this.errorReply(`Modjoin is already turned off in this room.`); delete room.modjoin; this.addModCommand(`${user.name} turned off modjoin.`); if (room.chatRoomData) { delete room.chatRoomData.modjoin; Rooms.global.writeChatRoomData(); } return; } else if (target === 'sync') { if (room.modjoin === true) return this.errorReply(`Modjoin is already set to sync modchat in this room.`); room.modjoin = true; this.addModCommand(`${user.name} set modjoin to sync with modchat.`); } else if (target in Config.groups) { if (room.battle && !this.can('makeroom')) return; if (room.isPersonal && !user.can('makeroom') && target !== '+') return this.errorReply(`/modjoin - Access denied from setting modjoin past + in group chats.`); if (room.modjoin === target) return this.errorReply(`Modjoin is already set to ${target} in this room.`); room.modjoin = target; this.addModCommand(`${user.name} set modjoin to ${target}.`); } else { this.errorReply(`Unrecognized modjoin setting.`); this.parse('/help modjoin'); return false; } if (room.chatRoomData) { room.chatRoomData.modjoin = room.modjoin; Rooms.global.writeChatRoomData(); } if (!room.modchat) this.parse('/modchat ' + Config.groupsranking[1]); if (!room.isPrivate) this.parse('/hiddenroom'); }, modjoinhelp: ["/modjoin [+|%|@|*|&|~|#|off] - Sets modjoin. Users lower than the specified rank can't join this room. Requires: # & ~", "/modjoin [sync|off] - Sets modjoin. Only users who can speak in modchat can join this room. Requires: # & ~"], officialchatroom: 'officialroom', officialroom: function (target, room, user) { if (!this.can('makeroom')) return; if (!room.chatRoomData) { return this.errorReply(`/officialroom - This room can't be made official`); } if (target === 'off') { if (!room.isOfficial) return this.errorReply(`This chat room is already unofficial.`); delete room.isOfficial; this.addModCommand(`${user.name} made this chat room unofficial.`); delete room.chatRoomData.isOfficial; Rooms.global.writeChatRoomData(); } else { if (room.isOfficial) return this.errorReply(`This chat room is already official.`); room.isOfficial = true; this.addModCommand(`${user.name} made this chat room official.`); room.chatRoomData.isOfficial = true; Rooms.global.writeChatRoomData(); } }, roomdesc: function (target, room, user) { if (!target) { if (!this.runBroadcast()) return; if (!room.desc) return this.sendReply(`This room does not have a description set.`); this.sendReplyBox(Tools.html`The room description is: ${room.desc}`); return; } if (!this.can('declare')) return false; if (target.length > 80) return this.errorReply(`Error: Room description is too long (must be at most 80 characters).`); let normalizedTarget = ' ' + target.toLowerCase().replace('[^a-zA-Z0-9]+', ' ').trim() + ' '; if (normalizedTarget.includes(' welcome ')) { return this.errorReply(`Error: Room description must not contain the word "welcome".`); } if (normalizedTarget.slice(0, 9) === ' discuss ') { return this.errorReply(`Error: Room description must not start with the word "discuss".`); } if (normalizedTarget.slice(0, 12) === ' talk about ' || normalizedTarget.slice(0, 17) === ' talk here about ') { return this.errorReply(`Error: Room description must not start with the phrase "talk about".`); } room.desc = target; this.sendReply(`(The room description is now: ${target})`); this.privateModCommand(`(${user.name} changed the roomdesc to: "${target}".)`); if (room.chatRoomData) { room.chatRoomData.desc = room.desc; Rooms.global.writeChatRoomData(); } }, topic: 'roomintro', roomintro: function (target, room, user) { if (!target) { if (!this.runBroadcast()) return; if (!room.introMessage) return this.sendReply("This room does not have an introduction set."); this.sendReply('|raw|<div class="infobox infobox-limited">' + room.introMessage.replace(/\n/g, '') + '</div>'); if (!this.broadcasting && user.can('declare', null, room)) { this.sendReply('Source:'); this.sendReplyBox( '<code>/roomintro ' + Tools.escapeHTML(room.introMessage).split('\n').map(line => { return line.replace(/^(\t+)/, (match, $1) => '&nbsp;'.repeat(4 * $1.length)).replace(/^(\s+)/, (match, $1) => '&nbsp;'.repeat($1.length)); }).join('<br />') + '</code>' ); } return; } if (!this.can('declare', null, room)) return false; target = this.canHTML(target); if (!target) return; if (!/</.test(target)) { // not HTML, do some simple URL linking let re = /(https?:\/\/(([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?))/g; target = target.replace(re, '<a href="$1">$1</a>'); } if (target.substr(0, 11) === '/roomintro ') target = target.substr(11); room.introMessage = target.replace(/\r/g, ''); this.sendReply("(The room introduction has been changed to:)"); this.sendReply('|raw|<div class="infobox infobox-limited">' + room.introMessage.replace(/\n/g, '') + '</div>'); this.privateModCommand(`(${user.name} changed the roomintro.)`); this.logEntry(room.introMessage.replace(/\n/g, '')); if (room.chatRoomData) { room.chatRoomData.introMessage = room.introMessage; Rooms.global.writeChatRoomData(); } }, deletetopic: 'deleteroomintro', deleteroomintro: function (target, room, user) { if (!this.can('declare', null, room)) return false; if (!room.introMessage) return this.errorReply("This room does not have a introduction set."); this.privateModCommand(`(${user.name} deleted the roomintro.)`); this.logEntry(target); delete room.introMessage; if (room.chatRoomData) { delete room.chatRoomData.introMessage; Rooms.global.writeChatRoomData(); } }, stafftopic: 'staffintro', staffintro: function (target, room, user) { if (!target) { if (!this.can('mute', null, room)) return false; if (!room.staffMessage) return this.sendReply("This room does not have a staff introduction set."); this.sendReply('|raw|<div class="infobox">' + room.staffMessage.replace(/\n/g, '') + '</div>'); if (user.can('ban', null, room)) { this.sendReply('Source:'); this.sendReplyBox( '<code>/staffintro ' + Tools.escapeHTML(room.staffMessage).split('\n').map(line => { return line.replace(/^(\t+)/, (match, $1) => '&nbsp;'.repeat(4 * $1.length)).replace(/^(\s+)/, (match, $1) => '&nbsp;'.repeat($1.length)); }).join('<br />') + '</code>' ); } return; } if (!this.can('ban', null, room)) return false; target = this.canHTML(target); if (!target) return; if (!/</.test(target)) { // not HTML, do some simple URL linking let re = /(https?:\/\/(([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?))/g; target = target.replace(re, '<a href="$1">$1</a>'); } if (target.substr(0, 12) === '/staffintro ') target = target.substr(12); room.staffMessage = target.replace(/\r/g, ''); this.sendReply("(The staff introduction has been changed to:)"); this.sendReply('|raw|<div class="infobox">' + target.replace(/\n/g, '') + '</div>'); this.privateModCommand(`(${user.name} changed the staffintro.)`); this.logEntry(room.staffMessage.replace(/\n/g, '')); if (room.chatRoomData) { room.chatRoomData.staffMessage = room.staffMessage; Rooms.global.writeChatRoomData(); } }, deletestafftopic: 'deletestaffintro', deletestaffintro: function (target, room, user) { if (!this.can('ban', null, room)) return false; if (!room.staffMessage) return this.errorReply("This room does not have a staff introduction set."); this.privateModCommand(`(${user.name} deleted the staffintro.)`); this.logEntry(target); delete room.staffMessage; if (room.chatRoomData) { delete room.chatRoomData.staffMessage; Rooms.global.writeChatRoomData(); } }, roomalias: function (target, room, user) { if (!target) { if (!this.runBroadcast()) return; if (!room.aliases || !room.aliases.length) return this.sendReplyBox("This room does not have any aliases."); return this.sendReplyBox("This room has the following aliases: " + room.aliases.join(", ") + ""); } if (!this.can('makeroom')) return false; let alias = toId(target); if (!alias.length) return this.errorReply("Only alphanumeric characters are valid in an alias."); if (Rooms(alias) || Rooms.aliases.has(alias)) return this.errorReply("You cannot set an alias to an existing room or alias."); if (room.isPersonal) return this.errorReply("Personal rooms can't have aliases."); Rooms.aliases.set(alias, room.id); this.privateModCommand(`(${user.name} added the room alias '${target}'.)`); if (!room.aliases) room.aliases = []; room.aliases.push(alias); if (room.chatRoomData) { room.chatRoomData.aliases = room.aliases; Rooms.global.writeChatRoomData(); } }, removeroomalias: function (target, room, user) { if (!room.aliases) return this.errorReply("This room does not have any aliases."); if (!this.can('makeroom')) return false; let alias = toId(target); if (!alias || !Rooms.aliases.has(alias)) return this.errorReply("Please specify an existing alias."); if (Rooms.aliases.get(alias) !== room.id) return this.errorReply("You may only remove an alias from the current room."); this.privateModCommand(`(${user.name} removed the room alias '${target}'.)`); let aliasIndex = room.aliases.indexOf(alias); if (aliasIndex >= 0) { room.aliases.splice(aliasIndex, 1); Rooms.aliases.delete(alias); Rooms.global.writeChatRoomData(); } }, roomowner: function (target, room, user) { if (!room.chatRoomData) { return this.sendReply("/roomowner - This room isn't designed for per-room moderation to be added"); } if (!target) return this.parse('/help roomowner'); target = this.splitTarget(target, true); let targetUser = this.targetUser; let name = this.targetUsername; let userid = toId(name); if (!Users.isUsernameKnown(userid)) { return this.errorReply(`User '${this.targetUsername}' is offline and unrecognized, and so can't be promoted.`); } if (!this.can('makeroom')) return false; if (!room.auth) room.auth = room.chatRoomData.auth = {}; room.auth[userid] = '#'; this.addModCommand(`${name} was appointed Room Owner by ${user.name}.`); if (targetUser) { targetUser.popup(`You were appointed Room Owner by ${user.name} in ${room.id}.`); room.onUpdateIdentity(targetUser); } Rooms.global.writeChatRoomData(); }, roomownerhelp: ["/roomowner [username] - Appoints [username] as a room owner. Requires: & ~"], roomdemote: 'roompromote', roompromote: function (target, room, user, connection, cmd) { if (!room.auth) { this.sendReply("/roompromote - This room isn't designed for per-room moderation"); return this.sendReply("Before setting room mods, you need to set it up with /roomowner"); } if (!target) return this.parse('/help roompromote'); target = this.splitTarget(target, true); let targetUser = this.targetUser; let userid = toId(this.targetUsername); let name = targetUser ? targetUser.name : this.targetUsername; if (!userid) return this.parse('/help roompromote'); if (!targetUser && !Users.isUsernameKnown(userid)) { return this.errorReply("User '" + name + "' is offline and unrecognized, and so can't be promoted."); } if (targetUser && !targetUser.registered) { return this.errorReply("User '" + name + "' is unregistered, and so can't be promoted."); } let currentGroup = room.getAuth({userid, group: (Users.usergroups[userid] || ' ').charAt(0)}); let nextGroup = target; if (target === 'deauth') nextGroup = Config.groupsranking[0]; if (!nextGroup) { return this.errorReply("Please specify a group such as /roomvoice or /roomdeauth"); } if (!Config.groups[nextGroup]) { return this.errorReply("Group '" + nextGroup + "' does not exist."); } if (Config.groups[nextGroup].globalonly || (Config.groups[nextGroup].battleonly && !room.battle)) { return this.errorReply("Group 'room" + Config.groups[nextGroup].id + "' does not exist as a room rank."); } let groupName = Config.groups[nextGroup].name || "regular user"; if ((room.auth[userid] || Config.groupsranking[0]) === nextGroup) { return this.errorReply("User '" + name + "' is already a " + groupName + " in this room."); } if (!user.can('makeroom')) { if (currentGroup !== ' ' && !user.can('room' + (Config.groups[currentGroup] ? Config.groups[currentGroup].id : 'voice'), null, room)) { return this.errorReply("/" + cmd + " - Access denied for promoting/demoting from " + (Config.groups[currentGroup] ? Config.groups[currentGroup].name : "an undefined group") + "."); } if (nextGroup !== ' ' && !user.can('room' + Config.groups[nextGroup].id, null, room)) { return this.errorReply("/" + cmd + " - Access denied for promoting/demoting to " + Config.groups[nextGroup].name + "."); } } if (targetUser && targetUser.locked && !room.isPrivate && !room.battle && !room.isPersonal && (nextGroup === '%' || nextGroup === '@' || nextGroup === '*')) { return this.errorReply("Locked users can't be promoted."); } if (nextGroup === ' ') { delete room.auth[userid]; } else { room.auth[userid] = nextGroup; } // Only show popup if: user is online and in the room, the room is public, and not a groupchat or a battle. let needsPopup = targetUser && room.users[targetUser.userid] && !room.isPrivate && !room.isPersonal && !room.battle; if (nextGroup in Config.groups && currentGroup in Config.groups && Config.groups[nextGroup].rank < Config.groups[currentGroup].rank) { if (targetUser && room.users[targetUser.userid] && !Config.groups[nextGroup].modlog) { // if the user can't see the demotion message (i.e. rank < %), it is shown in the chat targetUser.send(">" + room.id + "\n(You were demoted to Room " + groupName + " by " + user.name + ".)"); } this.privateModCommand("(" + name + " was demoted to Room " + groupName + " by " + user.name + ".)"); if (needsPopup) targetUser.popup("You were demoted to Room " + groupName + " by " + user.name + " in " + room.id + "."); } else if (nextGroup === '#') { this.addModCommand("" + name + " was promoted to " + groupName + " by " + user.name + "."); if (needsPopup) targetUser.popup("You were promoted to " + groupName + " by " + user.name + " in " + room.id + "."); } else { this.addModCommand("" + name + " was promoted to Room " + groupName + " by " + user.name + "."); if (needsPopup) targetUser.popup("You were promoted to Room " + groupName + " by " + user.name + " in " + room.id + "."); } if (targetUser) targetUser.updateIdentity(room.id); if (room.chatRoomData) Rooms.global.writeChatRoomData(); }, roompromotehelp: ["/roompromote OR /roomdemote [username], [group symbol] - Promotes/demotes the user to the specified room rank. Requires: @ * # & ~", "/room[group] [username] - Promotes/demotes the user to the specified room rank. Requires: @ * # & ~", "/roomdeauth [username] - Removes all room rank from the user. Requires: @ * # & ~"], roomstaff: 'roomauth', roomauth1: 'roomauth', roomauth: function (target, room, user, connection, cmd) { let userLookup = ''; if (cmd === 'roomauth1') userLookup = '\n\nTo look up auth for a user, use /userauth ' + target; let targetRoom = room; if (target) targetRoom = Rooms.search(target); let unavailableRoom = targetRoom && (targetRoom !== room && (targetRoom.modjoin || targetRoom.staffRoom) && !user.can('makeroom')); if (!targetRoom || unavailableRoom) return this.errorReply("The room '" + target + "' does not exist."); if (!targetRoom.auth) return this.sendReply("/roomauth - The room '" + (targetRoom.title ? targetRoom.title : target) + "' isn't designed for per-room moderation and therefore has no auth list." + userLookup); let rankLists = {}; for (let u in targetRoom.auth) { if (!rankLists[targetRoom.auth[u]]) rankLists[targetRoom.auth[u]] = []; rankLists[targetRoom.auth[u]].push(u); } let buffer = Object.keys(rankLists).sort((a, b) => (Config.groups[b] || {rank:0}).rank - (Config.groups[a] || {rank:0}).rank ).map(r => { let roomRankList = rankLists[r].sort(); roomRankList = roomRankList.map(s => s in targetRoom.users ? "**" + s + "**" : s); return (Config.groups[r] ? Config.groups[r].name + "s (" + r + ")" : r) + ":\n" + roomRankList.join(", "); }); if (!buffer.length) { connection.popup("The room '" + targetRoom.title + "' has no auth." + userLookup); return; } if (targetRoom !== room) buffer.unshift("" + targetRoom.title + " room auth:"); connection.popup(buffer.join("\n\n") + userLookup); }, userauth: function (target, room, user, connection) { let targetId = toId(target) || user.userid; let targetUser = Users.getExact(targetId); let targetUsername = (targetUser ? targetUser.name : target); let buffer = []; let innerBuffer = []; let group = Users.usergroups[targetId]; if (group) { buffer.push('Global auth: ' + group.charAt(0)); } Rooms.rooms.forEach((curRoom, id) => { if (!curRoom.auth || curRoom.isPrivate) return; group = curRoom.auth[targetId]; if (!group) return; innerBuffer.push(group + id); }); if (innerBuffer.length) { buffer.push('Room auth: ' + innerBuffer.join(', ')); } if (targetId === user.userid || user.can('lock')) { innerBuffer = []; Rooms.rooms.forEach((curRoom, id) => { if (!curRoom.auth || !curRoom.isPrivate) return; if (curRoom.isPrivate === true) return; let auth = curRoom.auth[targetId]; if (!auth) return; innerBuffer.push(auth + id); }); if (innerBuffer.length) { buffer.push('Hidden room auth: ' + innerBuffer.join(', ')); } } if (targetId === user.userid || user.can('makeroom')) { innerBuffer = []; for (let i = 0; i < Rooms.global.chatRooms.length; i++) { let curRoom = Rooms.global.chatRooms[i]; if (!curRoom.auth || !curRoom.isPrivate) continue; if (curRoom.isPrivate !== true) continue; let auth = curRoom.auth[targetId]; if (!auth) continue; innerBuffer.push(auth + curRoom.id); } if (innerBuffer.length) { buffer.push('Private room auth: ' + innerBuffer.join(', ')); } } if (!buffer.length) { buffer.push("No global or room auth."); } buffer.unshift("" + targetUsername + " user auth:"); connection.popup(buffer.join("\n\n")); }, rb: 'roomban', roomban: function (target, room, user, connection) { if (!target) return this.parse('/help roomban'); if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); target = this.splitTarget(target); let targetUser = this.targetUser; let name = this.targetUsername; let userid = toId(name); if (!userid || !targetUser) return this.errorReply("User '" + name + "' not found."); if (target.length > MAX_REASON_LENGTH) { return this.errorReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters."); } if (!this.can('ban', targetUser, room)) return false; if (!room.bannedUsers || !room.bannedIps) { return this.errorReply("Room bans are not meant to be used in room " + room.id + "."); } if (room.bannedUsers[userid] && room.bannedIps[targetUser.latestIp]) return this.sendReply("User " + targetUser.name + " is already banned from room " + room.id + "."); if (targetUser in room.users || user.can('lock')) { targetUser.popup( "|html|<p>" + Tools.escapeHTML(user.name) + " has banned you from the room " + room.id + ".</p>" + (target ? "<p>Reason: " + Tools.escapeHTML(target) + "</p>" : "") + "<p>To appeal the ban, PM the staff member that banned you" + (room.auth ? " or a room owner. </p><p><button name=\"send\" value=\"/roomauth " + room.id + "\">List Room Staff</button></p>" : ".</p>") ); } this.addModCommand("" + targetUser.name + " was banned from room " + room.id + " by " + user.name + "." + (target ? " (" + target + ")" : "")); let acAccount = (targetUser.autoconfirmed !== targetUser.userid && targetUser.autoconfirmed); let alts = room.roomBan(targetUser); if (!(room.isPersonal || room.isPrivate === true) || user.can('alts', targetUser)) { if (alts.length) { this.privateModCommand("(" + targetUser.name + "'s " + (acAccount ? " ac account: " + acAccount + ", " : "") + "roombanned alts: " + alts.join(", ") + ")"); for (let i = 0; i < alts.length; ++i) { this.add('|unlink|' + toId(alts[i])); } } else if (acAccount) { this.privateModCommand("(" + targetUser.name + "'s ac account: " + acAccount + ")"); } } if (targetUser.confirmed && room.chatRoomData && !room.isPrivate) { Monitor.log("[CrisisMonitor] Confirmed user " + targetUser.name + (targetUser.confirmed !== targetUser.userid ? " (" + targetUser.confirmed + ")" : "") + " was roombanned from " + room.id + " by " + user.name + ", and should probably be demoted."); } let lastid = targetUser.getLastId(); this.add('|unlink|roomhide|' + lastid); if (lastid !== toId(this.inputUsername)) this.add('|unlink|roomhide|' + toId(this.inputUsername)); }, roombanhelp: ["/roomban [username] - Bans the user from the room you are in. Requires: @ # & ~"], unroomban: 'roomunban', roomunban: function (target, room, user, connection) { if (!target) return this.parse('/help roomunban'); if (!room.bannedUsers || !room.bannedIps) { return this.errorReply("Room bans are not meant to be used in room " + room.id + "."); } if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); this.splitTarget(target, true); let targetUser = this.targetUser; let userid = room.isRoomBanned(targetUser) || toId(target); if (!userid) return this.errorReply("User '" + target + "' is an invalid username."); if (!this.can('ban', null, room)) return false; let unbannedUserid = room.unRoomBan(userid); if (!unbannedUserid) return this.errorReply("User " + userid + " is not banned from room " + room.id + "."); this.addModCommand("" + unbannedUserid + " was unbanned from room " + room.id + " by " + user.name + "."); }, roomunbanhelp: ["/roomunban [username] - Unbans the user from the room you are in. Requires: @ # & ~"], autojoin: function (target, room, user, connection) { Rooms.global.autojoinRooms(user, connection); let targets = target.split(','); let autojoins = []; if (targets.length > 11 || connection.inRooms.size > 1) return; for (let i = 0; i < targets.length; i++) { if (user.tryJoinRoom(targets[i], connection) === null) { autojoins.push(targets[i]); } } connection.autojoins = autojoins.join(','); }, joim: 'join', j: 'join', join: function (target, room, user, connection) { if (!target) return this.parse('/help join'); if (target.startsWith('http://')) target = target.slice(7); if (target.startsWith('https://')) target = target.slice(8); if (target.startsWith('play.pokemonshowdown.com/')) target = target.slice(25); if (target.startsWith('psim.us/')) target = target.slice(8); if (user.tryJoinRoom(target, connection) === null) { connection.sendTo(target, "|noinit|namerequired|The room '" + target + "' does not exist or requires a login to join."); } }, joinhelp: ["/join [roomname] - Attempt to join the room [roomname]."], leave: 'part', part: function (target, room, user, connection) { if (room.id === 'global') return false; let targetRoom = Rooms.search(target); if (target && !targetRoom) { return this.errorReply("The room '" + target + "' does not exist."); } user.leaveRoom(targetRoom || room, connection); }, /********************************************************* * Moderating: Punishments *********************************************************/ kick: 'warn', k: 'warn', warn: function (target, room, user) { if (!target) return this.parse('/help warn'); if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); if (room.isPersonal && !user.can('warn')) return this.errorReply("Warning is unavailable in group chats."); target = this.splitTarget(target); let targetUser = this.targetUser; if (!targetUser || !targetUser.connected) return this.errorReply("User '" + this.targetUsername + "' not found."); if (!(targetUser in room.users)) { return this.errorReply("User " + this.targetUsername + " is not in the room " + room.id + "."); } if (target.length > MAX_REASON_LENGTH) { return this.errorReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters."); } if (!this.can('warn', targetUser, room)) return false; this.addModCommand("" + targetUser.name + " was warned by " + user.name + "." + (target ? " (" + target + ")" : "")); targetUser.send('|c|~|/warn ' + target); let userid = targetUser.getLastId(); this.add('|unlink|' + userid); if (userid !== toId(this.inputUsername)) this.add('|unlink|' + toId(this.inputUsername)); }, warnhelp: ["/warn OR /k [username], [reason] - Warns a user showing them the Pok\u00e9mon Showdown Rules and [reason] in an overlay. Requires: % @ # & ~"], redirect: 'redir', redir: function (target, room, user, connection) { if (!target) return this.parse('/help redirect'); if (room.isPrivate || room.isPersonal) return this.errorReply("Users cannot be redirected from private or personal rooms."); target = this.splitTarget(target); let targetUser = this.targetUser; let targetRoom = Rooms.search(target); if (!targetRoom || targetRoom.modjoin) { return this.errorReply("The room '" + target + "' does not exist."); } if (!this.can('warn', targetUser, room) || !this.can('warn', targetUser, targetRoom)) return false; if (!targetUser || !targetUser.connected) { return this.errorReply("User " + this.targetUsername + " not found."); } if (targetRoom.id === "global") return this.errorReply("Users cannot be redirected to the global room."); if (targetRoom.isPrivate || targetRoom.isPersonal) { return this.parse('/msg ' + this.targetUsername + ', /invite ' + targetRoom.id); } if (targetRoom.users[targetUser.userid]) { return this.errorReply("User " + targetUser.name + " is already in the room " + targetRoom.title + "!"); } if (!room.users[targetUser.userid]) { return this.errorReply("User " + this.targetUsername + " is not in the room " + room.id + "."); } if (targetUser.joinRoom(targetRoom.id) === false) return this.errorReply("User " + targetUser.name + " could not be joined to room " + targetRoom.title + ". They could be banned from the room."); this.addModCommand("" + targetUser.name + " was redirected to room " + targetRoom.title + " by " + user.name + "."); targetUser.leaveRoom(room); }, redirhelp: ["/redirect OR /redir [username], [roomname] - Attempts to redirect the user [username] to the room [roomname]. Requires: % @ & ~"], m: 'mute', mute: function (target, room, user, connection, cmd) { if (!target) return this.parse('/help mute'); if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); target = this.splitTarget(target); let targetUser = this.targetUser; if (!targetUser) return this.errorReply("User '" + this.targetUsername + "' not found."); if (target.length > MAX_REASON_LENGTH) { return this.errorReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters."); } let muteDuration = ((cmd === 'hm' || cmd === 'hourmute') ? HOURMUTE_LENGTH : MUTE_LENGTH); if (!this.can('mute', targetUser, room)) return false; let canBeMutedFurther = ((room.getMuteTime(targetUser) || 0) <= (muteDuration * 5 / 6)); if (targetUser.locked || (room.isMuted(targetUser) && !canBeMutedFurther) || room.isRoomBanned(targetUser)) { let problem = " but was already " + (targetUser.locked ? "locked" : room.isMuted(targetUser) ? "muted" : "room banned"); if (!target) { return this.privateModCommand("(" + targetUser.name + " would be muted by " + user.name + problem + ".)"); } return this.addModCommand("" + targetUser.name + " would be muted by " + user.name + problem + "." + (target ? " (" + target + ")" : "")); } if (targetUser in room.users) targetUser.popup("|modal|" + user.name + " has muted you in " + room.id + " for " + Tools.toDurationString(muteDuration) + ". " + target); this.addModCommand("" + targetUser.name + " was muted by " + user.name + " for " + Tools.toDurationString(muteDuration) + "." + (target ? " (" + target + ")" : "")); if (targetUser.autoconfirmed && targetUser.autoconfirmed !== targetUser.userid) this.privateModCommand("(" + targetUser.name + "'s ac account: " + targetUser.autoconfirmed + ")"); let userid = targetUser.getLastId(); this.add('|unlink|' + userid); if (userid !== toId(this.inputUsername)) this.add('|unlink|' + toId(this.inputUsername)); room.mute(targetUser, muteDuration, false); }, mutehelp: ["/mute OR /m [username], [reason] - Mutes a user with reason for 7 minutes. Requires: % @ * # & ~"], hm: 'hourmute', hourmute: function (target) { if (!target) return this.parse('/help hourmute'); this.run('mute'); }, hourmutehelp: ["/hourmute OR /hm [username], [reason] - Mutes a user with reason for an hour. Requires: % @ * # & ~"], um: 'unmute', unmute: function (target, room, user) { if (!target) return this.parse('/help unmute'); target = this.splitTarget(target); if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); if (!this.can('mute', null, room)) return false; let targetUser = this.targetUser; let successfullyUnmuted = room.unmute(targetUser ? targetUser.userid : this.targetUsername, "Your mute in '" + room.title + "' has been lifted."); if (successfullyUnmuted) { this.addModCommand("" + (targetUser ? targetUser.name : successfullyUnmuted) + " was unmuted by " + user.name + "."); } else { this.errorReply("" + (targetUser ? targetUser.name : this.targetUsername) + " is not muted."); } }, unmutehelp: ["/unmute [username] - Removes mute from user. Requires: % @ * # & ~"], forcelock: 'lock', l: 'lock', ipmute: 'lock', lock: function (target, room, user, connection, cmd) { if (!target) return this.parse('/help lock'); target = this.splitTarget(target); let targetUser = this.targetUser; if (!targetUser) return this.errorReply("User '" + this.targetUsername + "' not found."); if (target.length > MAX_REASON_LENGTH) { return this.errorReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters."); } if (!this.can('lock', targetUser)) return false; let name = targetUser.getLastName(); let userid = targetUser.getLastId(); if (targetUser.locked && !target) { let problem = " but was already locked"; return this.privateModCommand("(" + name + " would be locked by " + user.name + problem + ".)"); } if (targetUser.confirmed) { if (cmd === 'forcelock') { let from = targetUser.deconfirm(); Monitor.log("[CrisisMonitor] " + name + " was locked by " + user.name + " and demoted from " + from.join(", ") + "."); this.globalModlog("CRISISDEMOTE", targetUser, " from " + from.join(", ")); } else { return this.sendReply("" + name + " is a confirmed user. If you are sure you would like to lock them use /forcelock."); } } else if (cmd === 'forcelock') { return this.errorReply("Use /lock; " + name + " is not a confirmed user."); } // Destroy personal rooms of the locked user. targetUser.inRooms.forEach(roomid => { if (roomid === 'global') return; let targetRoom = Rooms.get(roomid); if (targetRoom.isPersonal && targetRoom.auth[userid] === '#') { targetRoom.destroy(); } }); targetUser.popup("|modal|" + user.name + " has locked you from talking in chats, battles, and PMing regular users." + (target ? "\n\nReason: " + target : "") + "\n\nIf you feel that your lock was unjustified, you can still PM staff members (%, @, &, and ~) to discuss it" + (Config.appealurl ? " or you can appeal:\n" + Config.appealurl : ".") + "\n\nYour lock will expire in a few days."); this.addModCommand("" + name + " was locked from talking by " + user.name + "." + (target ? " (" + target + ")" : ""), " (" + targetUser.latestIp + ")"); let alts = targetUser.getAlts(); let acAccount = (targetUser.autoconfirmed !== userid && targetUser.autoconfirmed); if (alts.length) { this.privateModCommand("(" + name + "'s " + (acAccount ? " ac account: " + acAccount + ", " : "") + "locked alts: " + alts.join(", ") + ")"); } else if (acAccount) { this.privateModCommand("(" + name + "'s ac account: " + acAccount + ")"); } this.add('|unlink|hide|' + userid); if (userid !== toId(this.inputUsername)) this.add('|unlink|hide|' + toId(this.inputUsername)); this.globalModlog("LOCK", targetUser, " by " + user.name + (target ? ": " + target : "")); Punishments.lock(targetUser, null, null, target); return true; }, lockhelp: ["/lock OR /l [username], [reason] - Locks the user from talking in all chats. Requires: % @ * & ~"], wl: 'weeklock', weeklock: function (target, room, user, connection, cmd) { if (!target) return this.parse('/help weeklock'); target = this.splitTarget(target); let targetUser = this.targetUser; if (!targetUser) return this.errorReply("User '" + this.targetUsername + "' not found."); if (target.length > MAX_REASON_LENGTH) { return this.errorReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters."); } if (!this.can('lock', targetUser)) return false; let name = targetUser.getLastName(); let userid = targetUser.getLastId(); if (targetUser.locked && !target) { let problem = " but was already locked"; return this.privateModCommand("(" + name + " would be locked by " + user.name + problem + ".)"); } if (targetUser.confirmed) { if (cmd === 'forcelock') { let from = targetUser.deconfirm(); Monitor.log("[CrisisMonitor] " + name + " was locked by " + user.name + " and demoted from " + from.join(", ") + "."); this.globalModlog("CRISISDEMOTE", targetUser, " from " + from.join(", ")); } else { return this.sendReply("" + name + " is a confirmed user. If you are sure you would like to lock them use /forcelock."); } } else if (cmd === 'forcelock') { return this.errorReply("Use /lock; " + name + " is not a confirmed user."); } // Destroy personal rooms of the locked user. targetUser.inRooms.forEach(roomid => { if (roomid === 'global') return; let targetRoom = Rooms.get(roomid); if (targetRoom.isPersonal && targetRoom.auth[userid] === '#') { targetRoom.destroy(); } }); targetUser.popup("|modal|" + user.name + " has locked you from talking in chats, battles, and PMing regular users for a week." + (target ? "\n\nReason: " + target : "") + "\n\nIf you feel that your lock was unjustified, you can still PM staff members (%, @, &, and ~) to discuss it" + (Config.appealurl ? " or you can appeal:\n" + Config.appealurl : ".") + "\n\nYour lock will expire in a few days."); this.addModCommand("" + name + " was locked from talking for a week by " + user.name + "." + (target ? " (" + target + ")" : ""), " (" + targetUser.latestIp + ")"); let alts = targetUser.getAlts(); let acAccount = (targetUser.autoconfirmed !== userid && targetUser.autoconfirmed); if (alts.length) { this.privateModCommand("(" + name + "'s " + (acAccount ? " ac account: " + acAccount + ", " : "") + "locked alts: " + alts.join(", ") + ")"); } else if (acAccount) { this.privateModCommand("(" + name + "'s ac account: " + acAccount + ")"); } this.add('|unlink|hide|' + userid); if (userid !== toId(this.inputUsername)) this.add('|unlink|hide|' + toId(this.inputUsername)); this.globalModlog("WEEKLOCK", targetUser, " by " + user.name + (target ? ": " + target : "")); Punishments.lock(targetUser, Date.now() + 7 * 24 * 60 * 60 * 1000, null, target); return true; }, weeklockhelp: ["/weeklock OR /wl [username], [reason] - Locks the user from talking in all chats for one week. Requires: % @ * & ~"], unlock: function (target, room, user) { if (!target) return this.parse('/help unlock'); if (!this.can('lock')) return false; let targetUser = Users.get(target); if (targetUser && targetUser.namelocked) { return this.errorReply(`User ${targetUser.name} is namelocked, not locked. Use /unnamelock to unnamelock them.`); } let reason = ''; if (targetUser && targetUser.locked && targetUser.locked.charAt(0) === '#') { reason = ' (' + targetUser.locked + ')'; } let unlocked = Punishments.unlock(target); if (unlocked) { this.addModCommand(unlocked.join(", ") + " " + ((unlocked.length > 1) ? "were" : "was") + " unlocked by " + user.name + "." + reason); if (!reason) this.globalModlog("UNLOCK", target, " by " + user.name); if (targetUser) targetUser.popup("" + user.name + " has unlocked you."); } else { this.errorReply("User '" + target + "' is not locked."); } }, unlockhelp: ["/unlock [username] - Unlocks the user. Requires: % @ * & ~"], forceban: 'ban', b: 'ban', ban: function (target, room, user, connection, cmd) { if (!target) return this.parse('/help ban'); target = this.splitTarget(target); let targetUser = this.targetUser; if (!targetUser) return this.errorReply("User '" + this.targetUsername + "' not found."); if (target.length > MAX_REASON_LENGTH) { return this.errorReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters."); } if (!this.can('ban', targetUser)) return false; let name = targetUser.getLastName(); let userid = targetUser.getLastId(); if (Punishments.getPunishType(userid) === 'BANNED' && !target && !targetUser.connected) { let problem = " but was already banned"; return this.privateModCommand("(" + name + " would be banned by " + user.name + problem + ".)"); } if (targetUser.confirmed) { if (cmd === 'forceban') { let from = targetUser.deconfirm(); Monitor.log("[CrisisMonitor] " + name + " was banned by " + user.name + " and demoted from " + from.join(", ") + "."); this.globalModlog("CRISISDEMOTE", targetUser, " from " + from.join(", ")); } else { return this.sendReply("" + name + " is a confirmed user. If you are sure you would like to ban them use /forceban."); } } else if (cmd === 'forceban') { return this.errorReply("Use /ban; " + name + " is not a confirmed user."); } // Destroy personal rooms of the banned user. targetUser.inRooms.forEach(roomid => { if (roomid === 'global') return; let targetRoom = Rooms.get(roomid); if (targetRoom.isPersonal && targetRoom.auth[userid] === '#') { targetRoom.destroy(); } }); targetUser.popup("|modal|" + user.name + " has banned you." + (target ? "\n\nReason: " + target : "") + (Config.appealurl ? "\n\nIf you feel that your ban was unjustified, you can appeal:\n" + Config.appealurl : "") + "\n\nYour ban will expire in a few days."); this.addModCommand("" + name + " was banned by " + user.name + "." + (target ? " (" + target + ")" : ""), " (" + targetUser.latestIp + ")"); let alts = targetUser.getAlts(); let acAccount = (targetUser.autoconfirmed !== userid && targetUser.autoconfirmed); if (alts.length) { let guests = alts.length; alts = alts.filter(alt => alt.substr(0, 7) !== '[Guest '); guests -= alts.length; this.privateModCommand("(" + name + "'s " + (acAccount ? " ac account: " + acAccount + ", " : "") + "banned alts: " + alts.join(", ") + (guests ? " [" + guests + " guests]" : "") + ")"); for (let i = 0; i < alts.length; ++i) { this.add('|unlink|' + toId(alts[i])); } } else if (acAccount) { this.privateModCommand("(" + name + "'s ac account: " + acAccount + ")"); } this.add('|unlink|hide|' + userid); if (userid !== toId(this.inputUsername)) this.add('|unlink|hide|' + toId(this.inputUsername)); Punishments.ban(targetUser, null, null, target); this.globalModlog("BAN", targetUser, " by " + user.name + (target ? ": " + target : "")); return true; }, banhelp: ["/ban OR /b [username], [reason] - Kick user from all rooms and ban user's IP address with reason. Requires: @ * & ~"], unban: function (target, room, user) { if (!target) return this.parse('/help unban'); if (!this.can('ban')) return false; let name = Punishments.unban(target); if (name) { this.addModCommand("" + name + " was unbanned by " + user.name + "."); this.globalModlog("UNBAN", name, " by " + user.name); } else { this.errorReply("User '" + target + "' is not banned."); } }, unbanhelp: ["/unban [username] - Unban a user. Requires: @ * & ~"], unbanall: function (target, room, user) { if (!this.can('rangeban')) return false; if (!target) { user.lastCommand = '/unbanall'; this.errorReply("THIS WILL UNBAN AND UNLOCK ALL USERS."); this.errorReply("To confirm, use: /unbanall confirm"); return; } if (user.lastCommand !== '/unbanall' || target !== 'confirm') { return this.parse('/help unbanall'); } // we have to do this the hard way since it's no longer a global let punishKeys = ['bannedIps', 'bannedUsers', 'lockedIps', 'lockedUsers', 'lockedRanges', 'rangeLockedUsers']; for (let i = 0; i < punishKeys.length; i++) { let dict = Punishments[punishKeys[i]]; for (let entry in dict) delete dict[entry]; } this.addModCommand("All bans and locks have been lifted by " + user.name + "."); }, unbanallhelp: ["/unbanall - Unban all IP addresses. Requires: & ~"], deroomvoiceall: function (target, room, user) { if (!this.can('editroom', null, room)) return false; if (!room.auth) return this.errorReply("Room does not have roomauth."); if (!target) { user.lastCommand = '/deroomvoiceall'; this.errorReply("THIS WILL DEROOMVOICE ALL ROOMVOICED USERS."); this.errorReply("To confirm, use: /deroomvoiceall confirm"); return; } if (user.lastCommand !== '/deroomvoiceall' || target !== 'confirm') { return this.parse('/help deroomvoiceall'); } let count = 0; for (let userid in room.auth) { if (room.auth[userid] === '+') { delete room.auth[userid]; if (userid in room.users) room.users[userid].updateIdentity(room.id); count++; } } if (!count) { return this.sendReply("(This room has zero roomvoices)"); } if (room.chatRoomData) { Rooms.global.writeChatRoomData(); } this.addModCommand("All " + count + " roomvoices have been cleared by " + user.name + "."); }, deroomvoiceallhelp: ["/deroomvoiceall - Devoice all roomvoiced users. Requires: # & ~"], rangeban: 'banip', banip: function (target, room, user) { target = this.splitTargetText(target); let targetIp = this.targetUsername.trim(); if (!targetIp || !/^[0-9.*]+$/.test(targetIp)) return this.parse('/help banip'); if (!target) return this.errorReply("/banip requires a ban reason"); if (!this.can('rangeban')) return false; Punishments.ipSearch(targetIp); if (Punishments.ips.has(targetIp)) return this.errorReply("The IP " + (targetIp.charAt(targetIp.length - 1) === '*' ? "range " : "") + targetIp + " has already been temporarily locked/banned."); Punishments.banRange(targetIp, target); this.addModCommand("" + user.name + " hour-banned the " + (target.charAt(target.length - 1) === '*' ? "IP range" : "IP") + " " + targetIp + ": " + target); }, baniphelp: ["/banip [ip] - Globally bans this IP or IP range for an hour. Accepts wildcards to ban ranges. Existing users on the IP will not be banned. Requires: & ~"], unrangeban: 'unbanip', unbanip: function (target, room, user) { target = target.trim(); if (!target) { return this.parse('/help unbanip'); } if (!this.can('rangeban')) return false; if (!Punishments.ips.has(target)) { return this.errorReply("" + target + " is not a locked/banned IP or IP range."); } Punishments.ips.delete(target); this.addModCommand("" + user.name + " unbanned the " + (target.charAt(target.length - 1) === '*' ? "IP range" : "IP") + ": " + target); }, unbaniphelp: ["/unbanip [ip] - Unbans. Accepts wildcards to ban ranges. Requires: & ~"], rangelock: 'lockip', lockip: function (target, room, user) { target = this.splitTargetText(target); let targetIp = this.targetUsername.trim(); if (!targetIp || !/^[0-9.*]+$/.test(targetIp)) return this.parse('/help lockip'); if (!target) return this.errorReply("/lockip requires a lock reason"); if (!this.can('rangeban')) return false; Punishments.ipSearch(targetIp); if (Punishments.ips.has(targetIp)) return this.sendReply("The IP " + (targetIp.charAt(targetIp.length - 1) === '*' ? "range " : "") + targetIp + " has already been temporarily locked/banned."); Punishments.lockRange(targetIp, target); this.addModCommand("" + user.name + " hour-locked the " + (target.charAt(target.length - 1) === '*' ? "IP range" : "IP") + " " + targetIp + ": " + target); }, lockiphelp: ["/lockip [ip] - Globally locks this IP or IP range for an hour. Accepts wildcards to ban ranges. Existing users on the IP will not be banned. Requires: & ~"], unrangelock: 'unlockip', rangeunlock: 'unlockip', unlockip: function (target, room, user) { target = target.trim(); if (!target) { return this.parse('/help unbanip'); } if (!this.can('rangeban')) return false; if (!Punishments.ips.has(target)) { return this.errorReply("" + target + " is not a locked/banned IP or IP range."); } Punishments.ips.delete(target); this.addModCommand("" + user.name + " unlocked the " + (target.charAt(target.length - 1) === '*' ? "IP range" : "IP") + ": " + target); }, /********************************************************* * Moderating: Other *********************************************************/ mn: 'modnote', modnote: function (target, room, user, connection) { if (!target) return this.parse('/help modnote'); if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); if (target.length > MAX_REASON_LENGTH) { return this.errorReply("The note is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters."); } if (!this.can('receiveauthmessages', null, room)) return false; return this.privateModCommand("(" + user.name + " notes: " + target + ")"); }, modnotehelp: ["/modnote [note] - Adds a moderator note that can be read through modlog. Requires: % @ * # & ~"], globalpromote: 'promote', promote: function (target, room, user, connection, cmd) { if (!target) return this.parse('/help promote'); target = this.splitTarget(target, true); let targetUser = this.targetUser; let userid = toId(this.targetUsername); let name = targetUser ? targetUser.name : this.targetUsername; if (!userid) return this.parse('/help promote'); let currentGroup = ((targetUser && targetUser.group) || Users.usergroups[userid] || ' ')[0]; let nextGroup = target; if (target === 'deauth') nextGroup = Config.groupsranking[0]; if (!nextGroup) { return this.errorReply("Please specify a group such as /globalvoice or /globaldeauth"); } if (!Config.groups[nextGroup]) { return this.errorReply("Group '" + nextGroup + "' does not exist."); } if (!cmd.startsWith('global')) { let groupid = Config.groups[nextGroup].id; if (!groupid && nextGroup === Config.groupsranking[0]) groupid = 'deauth'; if (Config.groups[nextGroup].globalonly) return this.errorReply('Did you mean /global' + groupid + '"?'); return this.errorReply('Did you mean "/room' + groupid + '" or "/global' + groupid + '"?'); } if (Config.groups[nextGroup].roomonly || Config.groups[nextGroup].battleonly) { return this.errorReply("Group '" + nextGroup + "' does not exist as a global rank."); } let groupName = Config.groups[nextGroup].name || "regular user"; if (currentGroup === nextGroup) { return this.errorReply("User '" + name + "' is already a " + groupName); } if (!user.canPromote(currentGroup, nextGroup)) { return this.errorReply("/" + cmd + " - Access denied."); } if (!Users.isUsernameKnown(userid)) { return this.errorReply("/globalpromote - WARNING: '" + name + "' is offline and unrecognized. The username might be misspelled (either by you or the person or told you) or unregistered. Use /forcepromote if you're sure you want to risk it."); } if (targetUser && !targetUser.registered) { return this.errorReply("User '" + name + "' is unregistered, and so can't be promoted."); } Users.setOfflineGroup(name, nextGroup); if (Config.groups[nextGroup].rank < Config.groups[currentGroup].rank) { this.privateModCommand("(" + name + " was demoted to " + groupName + " by " + user.name + ".)"); if (targetUser) targetUser.popup("You were demoted to " + groupName + " by " + user.name + "."); } else { this.addModCommand("" + name + " was promoted to " + groupName + " by " + user.name + "."); if (targetUser) targetUser.popup("You were promoted to " + groupName + " by " + user.name + "."); } if (targetUser) targetUser.updateIdentity(); }, promotehelp: ["/promote [username], [group] - Promotes the user to the specified group. Requires: & ~"], confirmuser: function (target) { if (!target) return this.parse('/help confirmuser'); if (!this.can('promote')) return; target = this.splitTarget(target, true); let targetUser = this.targetUser; let userid = toId(this.targetUsername); let name = targetUser ? targetUser.name : this.targetUsername; if (!userid) return this.parse('/help confirmuser'); if (!targetUser) return this.errorReply("User '" + name + "' is not online."); if (targetUser.confirmed) return this.errorReply("User '" + name + "' is already confirmed."); targetUser.setGroup(Config.groupsranking[0], true); this.sendReply("User '" + name + "' is now confirmed."); }, confirmuserhelp: ["/confirmuser [username] - Confirms the user (makes them immune to locks). Requires: & ~"], globaldemote: 'demote', demote: function (target) { if (!target) return this.parse('/help demote'); this.run('promote'); }, demotehelp: ["/demote [username], [group] - Demotes the user to the specified group. Requires: & ~"], forcepromote: function (target, room, user) { // warning: never document this command in /help if (!this.can('forcepromote')) return false; target = this.splitTarget(target, true); let name = this.targetUsername; let nextGroup = target; if (!Config.groups[nextGroup]) return this.errorReply("Group '" + nextGroup + "' does not exist."); if (Users.isUsernameKnown(name)) { return this.errorReply("/forcepromote - Don't forcepromote unless you have to."); } Users.setOfflineGroup(name, nextGroup); this.addModCommand("" + name + " was promoted to " + (Config.groups[nextGroup].name || "regular user") + " by " + user.name + "."); }, devoice: 'deauth', deauth: function (target, room, user) { return this.parse('/demote ' + target + ', deauth'); }, deglobalvoice: 'globaldeauth', deglobalauth: 'globaldeauth', globaldevoice: 'globaldeauth', globaldeauth: function (target, room, user) { return this.parse('/globaldemote ' + target + ', deauth'); }, deroomvoice: 'roomdeauth', roomdevoice: 'roomdeauth', deroomauth: 'roomdeauth', roomdeauth: function (target, room, user) { return this.parse('/roomdemote ' + target + ', deauth'); }, modchat: function (target, room, user) { if (!target) return this.sendReply("Moderated chat is currently set to: " + room.modchat); if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); if (!this.can('modchat', null, room)) return false; if (room.modchat && room.modchat.length <= 1 && Config.groupsranking.indexOf(room.modchat) > 1 && !user.can('modchatall', null, room)) { return this.errorReply("/modchat - Access denied for removing a setting higher than " + Config.groupsranking[1] + "."); } if (room.requestModchat) { let error = room.requestModchat(user); if (error) return this.errorReply(error); } target = target.toLowerCase().trim(); let currentModchat = room.modchat; switch (target) { case 'off': case 'false': case 'no': room.modchat = false; break; case 'ac': case 'autoconfirmed': room.modchat = 'autoconfirmed'; break; case 'player': target = '\u2605'; /* falls through */ default: { if (!Config.groups[target]) { this.errorReply("The rank '" + target + '" was unrecognized as a modchat level.'); return this.parse('/help modchat'); } if (Config.groupsranking.indexOf(target) > 1 && !user.can('modchatall', null, room)) { return this.errorReply("/modchat - Access denied for setting higher than " + Config.groupsranking[1] + "."); } let roomGroup = (room.auth && room.isPrivate === true ? ' ' : user.group); if (room.auth && user.userid in room.auth) roomGroup = room.auth[user.userid]; if (Config.groupsranking.indexOf(target) > Math.max(1, Config.groupsranking.indexOf(roomGroup)) && !user.can('makeroom')) { return this.errorReply("/modchat - Access denied for setting higher than " + roomGroup + "."); } room.modchat = target; break; }} if (currentModchat === room.modchat) { return this.errorReply("Modchat is already set to " + currentModchat + "."); } if (!room.modchat) { this.add("|raw|<div class=\"broadcast-blue\"><b>Moderated chat was disabled!</b><br />Anyone may talk now.</div>"); } else { let modchat = Tools.escapeHTML(room.modchat); this.add("|raw|<div class=\"broadcast-red\"><b>Moderated chat was set to " + modchat + "!</b><br />Only users of rank " + modchat + " and higher can talk.</div>"); } if (room.battle && !room.modchat && !user.can('modchat')) room.requestModchat(null); this.privateModCommand("(" + user.name + " set modchat to " + room.modchat + ")"); if (room.chatRoomData) { room.chatRoomData.modchat = room.modchat; Rooms.global.writeChatRoomData(); } }, modchathelp: ["/modchat [off/autoconfirmed/+/%/@/*/#/&/~] - Set the level of moderated chat. Requires: *, @ for off/autoconfirmed/+ options, # & ~ for all the options"], slowchat: function (target, room, user) { if (!target) return this.sendReply("Slow chat is currently set to: " + (room.slowchat ? room.slowchat : false)); if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); if (!this.can('editroom', null, room)) return false; let targetInt = parseInt(target); if (target === 'off' || target === 'disable' || target === 'false') { if (!room.slowchat) return this.errorReply("Slow chat is already disabled in this room."); room.slowchat = false; this.add("|raw|<div class=\"broadcast-blue\"><b>Slow chat was disabled!</b><br />There is no longer a set minimum time between messages.</div>"); } else if (targetInt) { if (room.userCount < SLOWCHAT_USER_REQUIREMENT) return this.errorReply("This room must have at least " + SLOWCHAT_USER_REQUIREMENT + " users to set slowchat; it only has " + room.userCount + " right now."); if (room.slowchat === targetInt) return this.errorReply("Slow chat is already set for " + room.slowchat + " seconds in this room."); if (targetInt < SLOWCHAT_MINIMUM) targetInt = SLOWCHAT_MINIMUM; if (targetInt > SLOWCHAT_MAXIMUM) targetInt = SLOWCHAT_MAXIMUM; room.slowchat = targetInt; this.add("|raw|<div class=\"broadcast-red\"><b>Slow chat was enabled!</b><br />Messages must have at least " + room.slowchat + " seconds between them.</div>"); } else { return this.parse("/help slowchat"); } this.privateModCommand("(" + user.name + " set slowchat to " + room.slowchat + ")"); if (room.chatRoomData) { room.chatRoomData.slowchat = room.slowchat; Rooms.global.writeChatRoomData(); } }, slowchathelp: ["/slowchat [number] - Sets a limit on how often users in the room can send messages, between 2 and 60 seconds. Requires @ * # & ~", "/slowchat [off/disable] - Disables slowchat in the room. Requires @ * # & ~"], stretching: function (target, room, user) { if (!target) return this.sendReply("Stretching in this room is currently set to: " + (room.filterStretching ? room.filterStretching : false)); if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); if (!this.can('editroom', null, room)) return false; if (target === 'enable' || target === 'on') { if (room.filterStretching) return this.errorReply("Stretching is already enabled in this room."); room.filterStretching = true; } else if (target === 'disable' || target === 'off') { if (!room.filterStretching) return this.errorReply("Stretching is already disabled in this room."); room.filterStretching = false; } else { return this.parse("/help stretching"); } this.privateModCommand("(" + user.name + " set stretching to " + room.filterStretching + ")"); if (room.chatRoomData) { room.chatRoomData.filterStretching = room.filterStretching; Rooms.global.writeChatRoomData(); } }, stretchinghelp: ["/stretching [enable/disable] - Toggles having the server check messages containing too much stretching. Requires # & ~"], capitals: function (target, room, user) { if (!target) return this.sendReply("Capitals in this room is currently set to: " + (room.filterCaps ? room.filterCaps : false)); if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); if (!this.can('editroom', null, room)) return false; if (target === 'enable' || target === 'on') { if (room.filterCaps) return this.errorReply("Capitals is already enabled in this room."); room.filterCaps = true; } else if (target === 'disable' || target === 'off') { if (!room.filterCaps) return this.errorReply("Capitals is already disabled in this room."); room.filterCaps = false; } else { return this.parse("/help capitals"); } this.privateModCommand("(" + user.name + " set capitals to " + room.filterCaps + ")"); if (room.chatRoomData) { room.chatRoomData.filterCaps = room.filterCaps; Rooms.global.writeChatRoomData(); } }, capitalshelp: ["/capitals [enable/disable] - Toggles having the server check messages containing too many capitals. Requires # & ~"], declare: function (target, room, user) { if (!target) return this.parse('/help declare'); if (!this.can('declare', null, room)) return false; if (!this.canTalk()) return; this.add('|raw|<div class="broadcast-blue"><b>' + Tools.escapeHTML(target) + '</b></div>'); this.logModCommand(user.name + " declared " + target); }, declarehelp: ["/declare [message] - Anonymously announces a message. Requires: # * & ~"], htmldeclare: function (target, room, user) { if (!target) return this.parse('/help htmldeclare'); if (!this.can('gdeclare', null, room)) return false; if (!this.canTalk()) return; target = this.canHTML(target); if (!target) return; this.add('|raw|<div class="broadcast-blue"><b>' + target + '</b></div>'); this.logModCommand(user.name + " declared " + target); }, htmldeclarehelp: ["/htmldeclare [message] - Anonymously announces a message using safe HTML. Requires: ~"], gdeclare: 'globaldeclare', globaldeclare: function (target, room, user) { if (!target) return this.parse('/help globaldeclare'); if (!this.can('gdeclare')) return false; target = this.canHTML(target); if (!target) return; Rooms.rooms.forEach((curRoom, id) => { if (id !== 'global') curRoom.addRaw('<div class="broadcast-blue"><b>' + target + '</b></div>').update(); }); this.logModCommand(user.name + " globally declared " + target); }, globaldeclarehelp: ["/globaldeclare [message] - Anonymously announces a message to every room on the server. Requires: ~"], cdeclare: 'chatdeclare', chatdeclare: function (target, room, user) { if (!target) return this.parse('/help chatdeclare'); if (!this.can('gdeclare')) return false; target = this.canHTML(target); if (!target) return; Rooms.rooms.forEach((curRoom, id) => { if (id !== 'global' && curRoom.type !== 'battle') curRoom.addRaw('<div class="broadcast-blue"><b>' + target + '</b></div>').update(); }); this.logModCommand(user.name + " globally declared (chat level) " + target); }, chatdeclarehelp: ["/cdeclare [message] - Anonymously announces a message to all chatrooms on the server. Requires: ~"], wall: 'announce', announce: function (target, room, user) { if (!target) return this.parse('/help announce'); if (!this.can('announce', null, room)) return false; target = this.canTalk(target); if (!target) return; return '/announce ' + target; }, announcehelp: ["/announce OR /wall [message] - Makes an announcement. Requires: % @ * # & ~"], fr: 'forcerename', forcerename: function (target, room, user) { if (!target) return this.parse('/help forcerename'); let reason = this.splitTarget(target, true); let targetUser = this.targetUser; if (!targetUser) { this.splitTarget(target); if (this.targetUser) { return this.errorReply("User has already changed their name to '" + this.targetUser.name + "'."); } return this.errorReply("User '" + target + "' not found."); } if (!this.can('forcerename', targetUser)) return false; let entry = targetUser.name + " was forced to choose a new name by " + user.name + (reason ? ": " + reason : ""); this.privateModCommand("(" + entry + ")"); Rooms.global.cancelSearch(targetUser); targetUser.resetName(); targetUser.send("|nametaken||" + user.name + " considers your name inappropriate" + (reason ? ": " + reason : ".")); return true; }, forcerenamehelp: ["/forcerename OR /fr [username], [reason] - Forcibly change a user's name and shows them the [reason]. Requires: % @ * & ~"], nl: 'namelock', namelock: function (target, room, user) { if (!target) return this.parse('/help namelock'); let reason = this.splitTarget(target, true); let targetUser = this.targetUser; if (!targetUser) { return this.errorReply("User '" + this.targetUsername + "' not found."); } if (!this.can('forcerename', targetUser)) return false; if (targetUser.namelocked) return this.errorReply("User '" + target + "' is already namelocked."); this.addModCommand("" + targetUser.name + " was namelocked by " + user.name + "." + (reason ? " (" + reason + ")" : "")); this.globalModlog("NAMELOCK", targetUser, " by " + user.name + (reason ? ": " + reason : "")); Rooms.global.cancelSearch(targetUser); Punishments.namelock(targetUser, null, null, reason); targetUser.popup("|modal|" + user.name + " has locked your name and you can't change names anymore" + (reason ? ": " + reason : ".")); return true; }, namelockhelp: ["/namelock OR /nl [username], [reason] - Name locks a user and shows them the [reason]. Requires: % @ * & ~"], unl: 'unnamelock', unnamelock: function (target, room, user) { if (!target) return this.parse('/help unnamelock'); if (!this.can('forcerename')) return false; let targetUser = Users.get(target); let reason = ''; if (targetUser && targetUser.namelocked) { reason = ' (' + targetUser.namelocked + ')'; } let unlocked = Punishments.unnamelock(target); if (unlocked) { this.addModCommand(unlocked + " was unnamelocked by " + user.name + "." + reason); if (!reason) this.globalModlog("UNNAMELOCK", target, " by " + user.name); if (targetUser) targetUser.popup("" + user.name + " has unnamelocked you."); } else { this.errorReply("User '" + target + "' is not namelocked."); } }, unnamelockhelp: ["/unnamelock [username] - Unnamelocks the user. Requires: % @ * & ~"], hidetext: function (target, room, user) { if (!target) return this.parse('/help hidetext'); this.splitTarget(target); let targetUser = this.targetUser; let name = this.targetUsername; if (!targetUser) return this.errorReply("User '" + name + "' not found."); let userid = targetUser.getLastId(); let hidetype = ''; if (!user.can('lock', targetUser) && !user.can('ban', targetUser, room)) { this.errorReply("/hidetext - Access denied."); return false; } if (targetUser.locked) { hidetype = 'hide|'; } else if ((room.bannedUsers[toId(name)] && room.bannedIps[targetUser.latestIp]) || user.can('rangeban')) { hidetype = 'roomhide|'; } else { return this.errorReply("User '" + name + "' is not banned from this room or locked."); } this.addModCommand("" + targetUser.name + "'s messages were cleared from room " + room.id + " by " + user.name + "."); this.add('|unlink|' + hidetype + userid); if (userid !== toId(this.inputUsername)) this.add('|unlink|' + hidetype + toId(this.inputUsername)); }, hidetexthelp: ["/hidetext [username] - Removes a locked or banned user's messages from chat (includes users banned from the room). Requires: % (global only), @ * # & ~"], banwords: 'banword', banword: { add: function (target, room, user) { if (!target || target === ' ') return this.parse('/help banword'); if (!user.can('declare', null, room)) return; if (!room.banwords) room.banwords = []; // Most of the regex code is copied from the client. TODO: unify them? let words = target.match(/[^,]+(,\d*}[^,]*)?/g).map(word => word.replace(/\n/g, '').trim()); for (let i = 0; i < words.length; i++) { if (/[\\^$*+?()|{}[\]]/.test(words[i])) { if (!user.can('makeroom')) return this.errorReply("Regex banwords are only allowed for leaders or above."); try { let test = new RegExp(words[i]); // eslint-disable-line no-unused-vars } catch (e) { return this.errorReply(e.message.substr(0, 28) === 'Invalid regular expression: ' ? e.message : 'Invalid regular expression: /' + words[i] + '/: ' + e.message); } } if (room.banwords.indexOf(words[i]) > -1) { return this.errorReply(words[i] + ' is already a banned phrase.'); } } room.banwords = room.banwords.concat(words); room.banwordRegex = null; if (words.length > 1) { this.privateModCommand("(The banwords '" + words.join(', ') + "' were added by " + user.name + ".)"); this.sendReply("Banned phrases succesfully added. The list is currently: " + room.banwords.join(', ')); } else { this.privateModCommand("(The banword '" + words[0] + "' was added by " + user.name + ".)"); this.sendReply("Banned phrase succesfully added. The list is currently: " + room.banwords.join(', ')); } if (room.chatRoomData) { room.chatRoomData.banwords = room.banwords; Rooms.global.writeChatRoomData(); } }, delete: function (target, room, user) { if (!target) return this.parse('/help banword'); if (!user.can('declare', null, room)) return; if (!room.banwords) return this.errorReply("This room has no banned phrases."); let words = target.match(/[^,]+(,\d*}[^,]*)?/g).map(word => word.replace(/\n/g, '').trim()); for (let i = 0; i < words.length; i++) { let index = room.banwords.indexOf(words[i]); if (index < 0) return this.errorReply(words[i] + " is not a banned phrase in this room."); room.banwords.splice(index, 1); } room.banwordRegex = null; if (words.length > 1) { this.privateModCommand("(The banwords '" + words.join(', ') + "' were removed by " + user.name + ".)"); this.sendReply("Banned phrases succesfully deleted. The list is currently: " + room.banwords.join(', ')); } else { this.privateModCommand("(The banword '" + words[0] + "' was removed by " + user.name + ".)"); this.sendReply("Banned phrase succesfully deleted. The list is currently: " + room.banwords.join(', ')); } if (room.chatRoomData) { room.chatRoomData.banwords = room.banwords; Rooms.global.writeChatRoomData(); } }, list: function (target, room, user) { if (!user.can('ban', null, room)) return; if (!room.banwords) return this.sendReply("This room has no banned phrases."); return this.sendReply("Banned phrases in room " + room.id + ": " + room.banwords.join(', ')); }, "": function (target, room, user) { return this.parse("/help banword"); }, }, banwordhelp: ["/banword add [words] - Adds the comma-separated list of phrases (& or ~ can also input regex) to the banword list of the current room. Requires: # & ~", "/banword delete [words] - Removes the comma-separated list of phrases from the banword list. Requires: # & ~", "/banword list - Shows the list of banned words in the current room. Requires: @ * # & ~"], modlog: function (target, room, user, connection) { let lines = 0; // Specific case for modlog command. Room can be indicated with a comma, lines go after the comma. // Otherwise, the text is defaulted to text search in current room's modlog. let roomId = (room.id === 'staff' ? 'global' : room.id); let hideIps = !user.can('lock'); let path = require('path'); let isWin = process.platform === 'win32'; let logPath = 'logs/modlog/'; if (target.includes(',')) { let targets = target.split(','); target = targets[1].trim(); roomId = toId(targets[0]) || room.id; } // Let's check the number of lines to retrieve or if it's a word instead if (!target.match('[^0-9]')) { lines = parseInt(target || 20); if (lines > 100) lines = 100; } let wordSearch = (!lines || lines < 0); // Control if we really, really want to check all modlogs for a word. let roomNames = ''; let filename = ''; let command = ''; if (roomId === 'all' && wordSearch) { if (!this.can('modlog')) return; roomNames = "all rooms"; // Get a list of all the rooms let fileList = fs.readdirSync('logs/modlog'); for (let i = 0; i < fileList.length; ++i) { filename += path.normalize(__dirname + '/' + logPath + fileList[i]) + ' '; } } else if (roomId.startsWith('battle-') || roomId.startsWith('groupchat-')) { return this.errorReply("Battles and groupchats do not have modlogs."); } else { if (!user.can('modlog') && !this.can('modlog', null, Rooms.get(roomId))) return; roomNames = "the room " + roomId; filename = path.normalize(__dirname + '/' + logPath + 'modlog_' + roomId + '.txt'); } // Seek for all input rooms for the lines or text if (isWin) { command = path.normalize(__dirname + '/lib/winmodlog') + ' tail ' + lines + ' ' + filename; } else { command = 'tail -' + lines + ' ' + filename + ' | tac'; } let grepLimit = 100; let strictMatch = false; if (wordSearch) { // searching for a word instead let searchString = target; strictMatch = true; // search for a 1:1 match? if (searchString.match(/^["'].+["']$/)) { searchString = searchString.substring(1, searchString.length - 1); } else if (searchString.includes('_')) { // do an exact search, the approximate search fails for underscores } else if (isWin) { // ID search with RegEx isn't implemented for windows yet (feel free to add it to winmodlog.cmd) target = '"' + target + '"'; // add quotes to target so the caller knows they are getting a strict match } else { // search for ID: allow any number of non-word characters (\W*) in between the letters we have to match. // i.e. if searching for "myUsername", also match on "My User-Name". // note that this doesn't really add a lot of unwanted results, since we use \b..\b target = toId(target); searchString = '\\b' + target.split('').join('\\W*') + '\\b'; strictMatch = false; } if (isWin) { if (strictMatch) { command = path.normalize(__dirname + '/lib/winmodlog') + ' ws ' + grepLimit + ' "' + searchString.replace(/%/g, "%%").replace(/([\^"&<>\|])/g, "^$1") + '" ' + filename; } else { // doesn't happen. ID search with RegEx isn't implemented for windows yet (feel free to add it to winmodlog.cmd and call it from here) } } else { if (strictMatch) { command = "awk '{print NR,$0}' " + filename + " | sort -nr | cut -d' ' -f2- | grep -m" + grepLimit + " -i '" + searchString.replace(/\\/g, '\\\\\\\\').replace(/["'`]/g, '\'\\$&\'').replace(/[\{\}\[\]\(\)\$\^\.\?\+\-\*]/g, '[$&]') + "'"; } else { command = "awk '{print NR,$0}' " + filename + " | sort -nr | cut -d' ' -f2- | grep -m" + grepLimit + " -Ei '" + searchString + "'"; } } } // Execute the file search to see modlog require('child_process').exec(command, (error, stdout, stderr) => { if (error && stderr) { connection.popup("/modlog empty on " + roomNames + " or erred"); console.log("/modlog error: " + error); return false; } if (stdout && hideIps) { stdout = stdout.replace(/\([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\)/g, ''); } stdout = stdout.split('\n').map(line => { let bracketIndex = line.indexOf(']'); let parenIndex = line.indexOf(')'); if (bracketIndex < 0) return Tools.escapeHTML(line); const time = line.slice(1, bracketIndex); let timestamp = Tools.toTimeStamp(new Date(time), {hour12: true}); parenIndex = line.indexOf(')'); let roomid = line.slice(bracketIndex + 3, parenIndex); if (!hideIps && Config.modloglink) { let url = Config.modloglink(time, roomid); if (url) timestamp = '<a href="' + url + '">' + timestamp + '</a>'; } return '<small>[' + timestamp + '] (' + roomid + ')</small>' + Tools.escapeHTML(line.slice(parenIndex + 1)); }).join('<br />'); if (lines) { if (!stdout) { connection.popup("The modlog is empty. (Weird.)"); } else { connection.popup("|wide||html|<p>The last " + lines + " lines of the Moderator Log of " + roomNames + ".</p><p><small>[" + Tools.toTimeStamp(new Date(), {hour12: true}) + "] ← current server time</small></p>" + stdout); } } else { if (!stdout) { connection.popup("No moderator actions containing " + target + " were found on " + roomNames + "." + (strictMatch ? "" : " Add quotes to the search parameter to search for a phrase, rather than a user.")); } else { connection.popup("|wide||html|<p>The last " + grepLimit + " logged actions containing " + target + " on " + roomNames + "." + (strictMatch ? "" : " Add quotes to the search parameter to search for a phrase, rather than a user.") + "</p><p><small>[" + Tools.toTimeStamp(new Date(), {hour12: true}) + "] ← current server time</small></p>" + stdout); } } }); }, modloghelp: ["/modlog [roomid|all], [n] - Roomid defaults to current room.", "If n is a number or omitted, display the last n lines of the moderator log. Defaults to 20.", "If n is not a number, search the moderator log for 'n' on room's log [roomid]. If you set [all] as [roomid], searches for 'n' on all rooms's logs. Requires: % @ * # & ~"], /********************************************************* * Server management commands *********************************************************/ hotpatch: function (target, room, user) { if (!target) return this.parse('/help hotpatch'); if (!this.can('hotpatch')) return false; if (Monitor.hotpatchLock) return this.errorReply("Hotpatch is currently been disabled. (" + Monitor.hotpatchLock + ")"); for (let roomid of ['development', 'staff', 'upperstaff']) { let curRoom = Rooms(roomid); if (curRoom) curRoom.add("|c|~|(" + user.name + " used /hotpatch " + target + ")").update(); } try { if (target === 'chat' || target === 'commands') { if (Monitor.hotpatchLockChat) return this.errorReply("Hotpatch has been disabled for chat. (" + Monitor.hotpatchLockChat + ")"); const ProcessManagers = require('./process-manager').cache; for (let PM of ProcessManagers.keys()) { if (PM.isChatBased) { PM.unspawn(); ProcessManagers.delete(PM); } } CommandParser.uncacheTree('./command-parser'); delete require.cache[require.resolve('./commands')]; delete require.cache[require.resolve('./chat-plugins/info')]; global.CommandParser = require('./command-parser'); let runningTournaments = Tournaments.tournaments; CommandParser.uncacheTree('./tournaments'); global.Tournaments = require('./tournaments'); Tournaments.tournaments = runningTournaments; return this.sendReply("Chat commands have been hot-patched."); } else if (target === 'tournaments') { let runningTournaments = Tournaments.tournaments; CommandParser.uncacheTree('./tournaments'); global.Tournaments = require('./tournaments'); Tournaments.tournaments = runningTournaments; return this.sendReply("Tournaments have been hot-patched."); } else if (target === 'battles') { Simulator.SimulatorProcess.respawn(); return this.sendReply("Battles have been hotpatched. Any battles started after now will use the new code; however, in-progress battles will continue to use the old code."); } else if (target === 'formats') { let toolsLoaded = !!Tools.isLoaded; // uncache the tools.js dependency tree CommandParser.uncacheTree('./tools'); // reload tools.js global.Tools = require('./tools')[toolsLoaded ? 'includeData' : 'includeFormats'](); // note: this will lock up the server for a few seconds // rebuild the formats list Rooms.global.formatListText = Rooms.global.getFormatListText(); // respawn validator processes TeamValidator.PM.respawn(); // respawn simulator processes Simulator.SimulatorProcess.respawn(); // broadcast the new formats list to clients Rooms.global.send(Rooms.global.formatListText); return this.sendReply("Formats have been hotpatched."); } else if (target === 'loginserver') { fs.unwatchFile('./config/custom.css'); CommandParser.uncacheTree('./loginserver'); global.LoginServer = require('./loginserver'); return this.sendReply("The login server has been hotpatched. New login server requests will use the new code."); } else if (target === 'learnsets' || target === 'validator') { TeamValidator.PM.respawn(); return this.sendReply("The team validator has been hotpatched. Any battles started after now will have teams be validated according to the new code."); } else if (target === 'punishments') { delete require.cache[require.resolve('./punishments')]; global.Punishments = require('./punishments'); return this.sendReply("Punishments have been hotpatched."); } else if (target === 'dnsbl') { Dnsbl.loadDatacenters(); return this.sendReply("Dnsbl has been hotpatched."); } else if (target.startsWith('disablechat')) { if (Monitor.hotpatchLockChat) return this.errorReply("Hotpatch is already disabled."); let reason = target.split(', ')[1]; if (!reason) return this.errorReply("Usage: /hotpatch disablechat, [reason]"); Monitor.hotpatchLockChat = reason; return this.sendReply("You have disabled hotpatch until the next server restart."); } else if (target.startsWith('disable')) { let reason = target.split(', ')[1]; if (!reason) return this.errorReply("Usage: /hotpatch disable, [reason]"); Monitor.hotpatchLock = reason; return this.sendReply("You have disabled hotpatch until the next server restart."); } } catch (e) { return this.errorReply("Something failed while trying to hotpatch " + target + ": \n" + e.stack); } this.errorReply("Your hot-patch command was unrecognized."); }, hotpatchhelp: ["Hot-patching the game engine allows you to update parts of Showdown without interrupting currently-running battles. Requires: ~", "Hot-patching has greater memory requirements than restarting.", "/hotpatch chat - reload commands.js and the chat-plugins", "/hotpatch battles - spawn new simulator processes", "/hotpatch validator - spawn new team validator processes", "/hotpatch formats - reload the tools.js tree, rebuild and rebroad the formats list, and spawn new simulator and team validator processes", "/hotpatch dnsbl - reloads Dnsbl datacenters", "/hotpatch disable, [reason] - disables the use of hotpatch until the next server restart"], savelearnsets: function (target, room, user) { if (!this.can('hotpatch')) return false; fs.writeFile('data/learnsets.js', 'exports.BattleLearnsets = ' + JSON.stringify(Tools.data.Learnsets) + ";\n"); this.sendReply("learnsets.js saved."); }, disableladder: function (target, room, user) { if (!this.can('disableladder')) return false; if (LoginServer.disabled) { return this.errorReply("/disableladder - Ladder is already disabled."); } LoginServer.disabled = true; this.logModCommand("The ladder was disabled by " + user.name + "."); this.add("|raw|<div class=\"broadcast-red\"><b>Due to high server load, the ladder has been temporarily disabled</b><br />Rated games will no longer update the ladder. It will be back momentarily.</div>"); }, enableladder: function (target, room, user) { if (!this.can('disableladder')) return false; if (!LoginServer.disabled) { return this.errorReply("/enable - Ladder is already enabled."); } LoginServer.disabled = false; this.logModCommand("The ladder was enabled by " + user.name + "."); this.add("|raw|<div class=\"broadcast-green\"><b>The ladder is now back.</b><br />Rated games will update the ladder now.</div>"); }, lockdown: function (target, room, user) { if (!this.can('lockdown')) return false; Rooms.global.lockdown = true; Rooms.rooms.forEach((curRoom, id) => { if (id === 'global') return; curRoom.addRaw("<div class=\"broadcast-red\"><b>The server is restarting soon.</b><br />Please finish your battles quickly. No new battles can be started until the server resets in a few minutes.</div>").update(); if (curRoom.requestKickInactive && !curRoom.battle.ended) { curRoom.requestKickInactive(user, true); if (curRoom.modchat !== '+') { curRoom.modchat = '+'; curRoom.addRaw("<div class=\"broadcast-red\"><b>Moderated chat was set to +!</b><br />Only users of rank + and higher can talk.</div>").update(); } } }); this.logEntry(user.name + " used /lockdown"); }, lockdownhelp: ["/lockdown - locks down the server, which prevents new battles from starting so that the server can eventually be restarted. Requires: ~"], prelockdown: function (target, room, user) { if (!this.can('lockdown')) return false; Rooms.global.lockdown = 'pre'; this.sendReply("Tournaments have been disabled in preparation for the server restart."); this.logEntry(user.name + " used /prelockdown"); }, slowlockdown: function (target, room, user) { if (!this.can('lockdown')) return false; Rooms.global.lockdown = true; Rooms.rooms.forEach((curRoom, id) => { if (id === 'global') return; if (curRoom.battle) return; curRoom.addRaw("<div class=\"broadcast-red\"><b>The server is restarting soon.</b><br />Please finish your battles quickly. No new battles can be started until the server resets in a few minutes.</div>").update(); }); this.logEntry(user.name + " used /slowlockdown"); }, endlockdown: function (target, room, user) { if (!this.can('lockdown')) return false; if (!Rooms.global.lockdown) { return this.errorReply("We're not under lockdown right now."); } if (Rooms.global.lockdown === true) { Rooms.rooms.forEach((curRoom, id) => { if (id !== 'global') curRoom.addRaw("<div class=\"broadcast-green\"><b>The server restart was canceled.</b></div>").update(); }); } else { this.sendReply("Preparation for the server shutdown was canceled."); } Rooms.global.lockdown = false; this.logEntry(user.name + " used /endlockdown"); }, emergency: function (target, room, user) { if (!this.can('lockdown')) return false; if (Config.emergency) { return this.errorReply("We're already in emergency mode."); } Config.emergency = true; Rooms.rooms.forEach((curRoom, id) => { if (id !== 'global') curRoom.addRaw("<div class=\"broadcast-red\">The server has entered emergency mode. Some features might be disabled or limited.</div>").update(); }); this.logEntry(user.name + " used /emergency"); }, endemergency: function (target, room, user) { if (!this.can('lockdown')) return false; if (!Config.emergency) { return this.errorReply("We're not in emergency mode."); } Config.emergency = false; Rooms.rooms.forEach((curRoom, id) => { if (id !== 'global') curRoom.addRaw("<div class=\"broadcast-green\"><b>The server is no longer in emergency mode.</b></div>").update(); }); this.logEntry(user.name + " used /endemergency"); }, kill: function (target, room, user) { if (!this.can('lockdown')) return false; if (Rooms.global.lockdown !== true) { return this.errorReply("For safety reasons, /kill can only be used during lockdown."); } if (CommandParser.updateServerLock) { return this.errorReply("Wait for /updateserver to finish before using /kill."); } for (let i in Sockets.workers) { Sockets.workers[i].kill(); } if (!room.destroyLog) { process.exit(); return; } room.destroyLog(() => { room.logEntry(user.name + " used /kill"); }, () => { process.exit(); }); // Just in the case the above never terminates, kill the process // after 10 seconds. setTimeout(() => { process.exit(); }, 10000); }, killhelp: ["/kill - kills the server. Can't be done unless the server is in lockdown state. Requires: ~"], loadbanlist: function (target, room, user, connection) { if (!this.can('hotpatch')) return false; connection.sendTo(room, "Loading ipbans.txt..."); Punishments.loadBanlist().then( () => connection.sendTo(room, "ipbans.txt has been reloaded."), error => connection.sendTo(room, "Something went wrong while loading ipbans.txt: " + error) ); }, loadbanlisthelp: ["/loadbanlist - Loads the bans located at ipbans.txt. The command is executed automatically at startup. Requires: ~"], refreshpage: function (target, room, user) { if (!this.can('hotpatch')) return false; Rooms.global.send('|refresh|'); this.logEntry(user.name + " used /refreshpage"); }, updateserver: function (target, room, user, connection) { if (!user.hasConsoleAccess(connection)) { return this.errorReply("/updateserver - Access denied."); } if (CommandParser.updateServerLock) { return this.errorReply("/updateserver - Another update is already in progress."); } CommandParser.updateServerLock = true; let logQueue = []; logQueue.push(user.name + " used /updateserver"); connection.sendTo(room, "updating..."); let exec = require('child_process').exec; exec('git diff-index --quiet HEAD --', error => { let cmd = 'git pull --rebase'; if (error) { if (error.code === 1) { // The working directory or index have local changes. cmd = 'git stash && ' + cmd + ' && git stash pop'; } else { // The most likely case here is that the user does not have // `git` on the PATH (which would be error.code === 127). connection.sendTo(room, "" + error); logQueue.push("" + error); for (let line of logQueue) { room.logEntry(line); } CommandParser.updateServerLock = false; return; } } let entry = "Running `" + cmd + "`"; connection.sendTo(room, entry); logQueue.push(entry); exec(cmd, (error, stdout, stderr) => { for (let s of ("" + stdout + stderr).split("\n")) { connection.sendTo(room, s); logQueue.push(s); } for (let line of logQueue) { room.logEntry(line); } CommandParser.updateServerLock = false; }); }); }, crashfixed: function (target, room, user) { if (Rooms.global.lockdown !== true) { return this.errorReply('/crashfixed - There is no active crash.'); } if (!this.can('hotpatch')) return false; Rooms.global.lockdown = false; if (Rooms.lobby) { Rooms.lobby.modchat = false; Rooms.lobby.addRaw("<div class=\"broadcast-green\"><b>We fixed the crash without restarting the server!</b><br />You may resume talking in the lobby and starting new battles.</div>").update(); } this.logEntry(user.name + " used /crashfixed"); }, crashfixedhelp: ["/crashfixed - Ends the active lockdown caused by a crash without the need of a restart. Requires: ~"], memusage: 'memoryusage', memoryusage: function (target) { if (!this.can('hotpatch')) return false; let memUsage = process.memoryUsage(); let results = [memUsage.rss, memUsage.heapUsed, memUsage.heapTotal]; let units = ["B", "KiB", "MiB", "GiB", "TiB"]; for (let i = 0; i < results.length; i++) { let unitIndex = Math.floor(Math.log2(results[i]) / 10); // 2^10 base log results[i] = "" + (results[i] / Math.pow(2, 10 * unitIndex)).toFixed(2) + " " + units[unitIndex]; } this.sendReply("||[Main process] RSS: " + results[0] + ", Heap: " + results[1] + " / " + results[2]); }, bash: function (target, room, user, connection) { if (!user.hasConsoleAccess(connection)) { return this.errorReply("/bash - Access denied."); } connection.sendTo(room, "$ " + target); let exec = require('child_process').exec; exec(target, (error, stdout, stderr) => { connection.sendTo(room, ("" + stdout + stderr)); }); }, eval: function (target, room, user, connection) { if (!user.hasConsoleAccess(connection)) { return this.errorReply("/eval - Access denied."); } if (!this.runBroadcast()) return; if (!this.broadcasting) this.sendReply('||>> ' + target); try { /* eslint-disable no-unused-vars */ let battle = room.battle; let me = user; this.sendReply('||<< ' + eval(target)); /* eslint-enable no-unused-vars */ } catch (e) { this.sendReply('|| << ' + ('' + e.stack).replace(/\n *at CommandContext\.exports\.commands(\.[a-z0-9]+)*\.eval [\s\S]*/m, '').replace(/\n/g, '\n||')); } }, evalbattle: function (target, room, user, connection) { if (!user.hasConsoleAccess(connection)) { return this.errorReply("/evalbattle - Access denied."); } if (!this.runBroadcast()) return; if (!room.battle) { return this.errorReply("/evalbattle - This isn't a battle room."); } room.battle.send('eval', target.replace(/\n/g, '\f')); }, ebat: 'editbattle', editbattle: function (target, room, user) { if (!this.can('forcewin')) return false; if (!target) return this.parse('/help editbattle'); if (!room.battle) { this.errorReply("/editbattle - This is not a battle room."); return false; } let cmd; let spaceIndex = target.indexOf(' '); if (spaceIndex > 0) { cmd = target.substr(0, spaceIndex).toLowerCase(); target = target.substr(spaceIndex + 1); } else { cmd = target.toLowerCase(); target = ''; } if (cmd.charAt(cmd.length - 1) === ',') cmd = cmd.slice(0, -1); let targets = target.split(','); function getPlayer(input) { let player = room.battle.players[toId(input)]; if (player) return player.slot; if (input.includes('1')) return 'p1'; if (input.includes('2')) return 'p2'; return 'p3'; } function getPokemon(input) { if (/^[0-9]+$/.test(input)) { return '.pokemon[' + (parseInt(input) - 1) + ']'; } return ".pokemon.find(p => p.speciesid==='" + toId(targets[1]) + "')"; } switch (cmd) { case 'hp': case 'h': room.battle.send('eval', "let p=" + getPlayer(targets[0]) + getPokemon(targets[1]) + ";p.sethp(" + parseInt(targets[2]) + ");if (p.isActive)battle.add('-damage',p,p.getHealth);"); break; case 'status': case 's': room.battle.send('eval', "let pl=" + getPlayer(targets[0]) + ";let p=pl" + getPokemon(targets[1]) + ";p.setStatus('" + toId(targets[2]) + "');if (!p.isActive){battle.add('','please ignore the above');battle.add('-status',pl.active[0],pl.active[0].status,'[silent]');}"); break; case 'pp': room.battle.send('eval', "let pl=" + getPlayer(targets[0]) + ";let p=pl" + getPokemon(targets[1]) + ";p.moveset[p.moves.indexOf('" + toId(targets[2]) + "')].pp = " + parseInt(targets[3])); break; case 'boost': case 'b': room.battle.send('eval', "let p=" + getPlayer(targets[0]) + getPokemon(targets[1]) + ";battle.boost({" + toId(targets[2]) + ":" + parseInt(targets[3]) + "},p)"); break; case 'volatile': case 'v': room.battle.send('eval', "let p=" + getPlayer(targets[0]) + getPokemon(targets[1]) + ";p.addVolatile('" + toId(targets[2]) + "')"); break; case 'sidecondition': case 'sc': room.battle.send('eval', "let p=" + getPlayer(targets[0]) + ".addSideCondition('" + toId(targets[1]) + "')"); break; case 'fieldcondition': case 'pseudoweather': case 'fc': room.battle.send('eval', "battle.addPseudoWeather('" + toId(targets[0]) + "')"); break; case 'weather': case 'w': room.battle.send('eval', "battle.setWeather('" + toId(targets[0]) + "')"); break; case 'terrain': case 't': room.battle.send('eval', "battle.setTerrain('" + toId(targets[0]) + "')"); break; default: this.errorReply("Unknown editbattle command: " + cmd); break; } }, editbattlehelp: ["/editbattle hp [player], [pokemon], [hp]", "/editbattle status [player], [pokemon], [status]", "/editbattle pp [player], [pokemon], [move], [pp]", "/editbattle boost [player], [pokemon], [stat], [amount]", "/editbattle volatile [player], [pokemon], [volatile]", "/editbattle sidecondition [player], [sidecondition]", "/editbattle fieldcondition [fieldcondition]", "/editbattle weather [weather]", "/editbattle terrain [terrain]", "Short forms: /ebat h OR s OR pp OR b OR v OR sc OR fc OR w OR t", "[player] must be a username or number, [pokemon] must be species name or number (not nickname), [move] must be move name"], /********************************************************* * Battle commands *********************************************************/ forfeit: function (target, room, user) { if (!room.game) return this.errorReply("This room doesn't have an active game."); if (!room.game.forfeit) { return this.errorReply("This kind of game can't be forfeited."); } if (!room.game.forfeit(user)) { return this.errorReply("Forfeit failed."); } }, choose: function (target, room, user) { if (!room.game) return this.errorReply("This room doesn't have an active game."); if (!room.game.choose) return this.errorReply("This game doesn't support /choose"); room.game.choose(user, target); }, mv: 'move', attack: 'move', move: function (target, room, user) { if (!room.game) return this.errorReply("This room doesn't have an active game."); if (!room.game.choose) return this.errorReply("This game doesn't support /choose"); room.game.choose(user, 'move ' + target); }, sw: 'switch', switch: function (target, room, user) { if (!room.game) return this.errorReply("This room doesn't have an active game."); if (!room.game.choose) return this.errorReply("This game doesn't support /choose"); room.game.choose(user, 'switch ' + parseInt(target)); }, team: function (target, room, user) { if (!room.game) return this.errorReply("This room doesn't have an active game."); if (!room.game.choose) return this.errorReply("This game doesn't support /choose"); room.game.choose(user, 'team ' + target); }, undo: function (target, room, user) { if (!room.game) return this.errorReply("This room doesn't have an active game."); if (!room.game.undo) return this.errorReply("This game doesn't support /undo"); room.game.undo(user, target); }, uploadreplay: 'savereplay', savereplay: function (target, room, user, connection) { if (!room || !room.battle) return; let logidx = Tools.getFormat(room.battle.format).team ? 3 : 0; // retrieve spectator log (0) if there are set privacy concerns let data = room.getLog(logidx).join("\n"); let datahash = crypto.createHash('md5').update(data.replace(/[^(\x20-\x7F)]+/g, '')).digest('hex'); let players = room.battle.playerNames; LoginServer.request('prepreplay', { id: room.id.substr(7), loghash: datahash, p1: players[0], p2: players[1], format: room.format, hidden: room.isPrivate ? '1' : '', }, success => { if (success && success.errorip) { connection.popup("This server's request IP " + success.errorip + " is not a registered server."); return; } connection.send('|queryresponse|savereplay|' + JSON.stringify({ log: data, id: room.id.substr(7), })); }); }, addplayer: function (target, room, user) { if (!target) return this.parse('/help addplayer'); if (!room.battle) return this.errorReply("You can only do this in battle rooms."); if (room.rated) return this.errorReply("You can only add a Player to unrated battles."); target = this.splitTarget(target, true); let targetUser = this.targetUser; let name = this.targetUsername; if (!targetUser) return this.errorReply("User " + name + " not found."); if (targetUser.can('joinbattle', null, room)) { return this.sendReply("" + name + " can already join battles as a Player."); } if (!this.can('joinbattle', null, room)) return; room.auth[targetUser.userid] = '\u2605'; this.addModCommand("" + name + " was promoted to Player by " + user.name + "."); }, addplayerhelp: ["/addplayer [username] - Allow the specified user to join the battle as a player."], joinbattle: 'joingame', joingame: function (target, room, user) { if (!room.game) return this.errorReply("This room doesn't have an active game."); if (!room.game.joinGame) return this.errorReply("This game doesn't support /joingame"); room.game.joinGame(user); }, leavebattle: 'leavegame', partbattle: 'leavegame', leavegame: function (target, room, user) { if (!room.game) return this.errorReply("This room doesn't have an active game."); if (!room.game.leaveGame) return this.errorReply("This game doesn't support /leavegame"); room.game.leaveGame(user); }, kickbattle: 'kickgame', kickgame: function (target, room, user) { if (!room.battle) return this.errorReply("You can only do this in battle rooms."); if (room.battle.tour || room.battle.rated) return this.errorReply("You can only do this in unrated non-tour battles."); target = this.splitTarget(target); let targetUser = this.targetUser; if (!targetUser || !targetUser.connected) { return this.errorReply("User " + this.targetUsername + " not found."); } if (!this.can('kick', targetUser)) return false; if (room.game.leaveGame(targetUser)) { this.addModCommand("" + targetUser.name + " was kicked from a battle by " + user.name + (target ? " (" + target + ")" : "")); } else { this.errorReply("/kickbattle - User isn't in battle."); } }, kickbattlehelp: ["/kickbattle [username], [reason] - Kicks a user from a battle with reason. Requires: % @ * & ~"], kickinactive: function (target, room, user) { if (room.requestKickInactive) { room.requestKickInactive(user); } else { this.errorReply("You can only kick inactive players from inside a room."); } }, timer: function (target, room, user) { target = toId(target); if (room.requestKickInactive) { if (target === 'off' || target === 'false' || target === 'stop') { let canForceTimer = user.can('timer', null, room); if (room.resetTimer) { room.stopKickInactive(user, canForceTimer); if (canForceTimer) room.send('|inactiveoff|Timer was turned off by staff. Please do not turn it back on until our staff say it\'s okay'); } } else if (target === 'on' || target === 'true' || !target) { room.requestKickInactive(user, user.can('timer')); } else { this.errorReply("'" + target + "' is not a recognized timer state."); } } else { this.errorReply("You can only set the timer from inside a battle room."); } }, autotimer: 'forcetimer', forcetimer: function (target, room, user) { target = toId(target); if (!this.can('autotimer')) return; if (target === 'off' || target === 'false' || target === 'stop') { Config.forcetimer = false; this.addModCommand("Forcetimer is now OFF: The timer is now opt-in. (set by " + user.name + ")"); } else if (target === 'on' || target === 'true' || !target) { Config.forcetimer = true; this.addModCommand("Forcetimer is now ON: All battles will be timed. (set by " + user.name + ")"); } else { this.errorReply("'" + target + "' is not a recognized forcetimer setting."); } }, forcetie: 'forcewin', forcewin: function (target, room, user) { if (!this.can('forcewin')) return false; if (!room.battle) { this.errorReply("/forcewin - This is not a battle room."); return false; } room.battle.endType = 'forced'; if (!target) { room.battle.tie(); this.logModCommand(user.name + " forced a tie."); return false; } let targetUser = Users.getExact(target); if (!targetUser) return this.errorReply("User '" + target + "' not found."); target = targetUser ? targetUser.userid : ''; if (target) { room.battle.win(targetUser); this.logModCommand(user.name + " forced a win for " + target + "."); } }, forcewinhelp: ["/forcetie - Forces the current match to end in a tie. Requires: & ~", "/forcewin [user] - Forces the current match to end in a win for a user. Requires: & ~"], /********************************************************* * Challenging and searching commands *********************************************************/ cancelsearch: 'search', search: function (target, room, user) { if (target) { if (Config.pmmodchat) { let userGroup = user.group; if (Config.groupsranking.indexOf(userGroup) < Config.groupsranking.indexOf(Config.pmmodchat)) { let groupName = Config.groups[Config.pmmodchat].name || Config.pmmodchat; this.popupReply("Because moderated chat is set, you must be of rank " + groupName + " or higher to search for a battle."); return false; } } Rooms.global.searchBattle(user, target); } else { Rooms.global.cancelSearch(user); } }, chall: 'challenge', challenge: function (target, room, user, connection) { target = this.splitTarget(target); let targetUser = this.targetUser; if (!targetUser || !targetUser.connected) { return this.popupReply("The user '" + this.targetUsername + "' was not found."); } if (user.locked && !targetUser.locked) { return this.popupReply("You are locked and cannot challenge unlocked users."); } if (targetUser.blockChallenges && !user.can('bypassblocks', targetUser)) { return this.popupReply("The user '" + this.targetUsername + "' is not accepting challenges right now."); } if (user.challengeTo) { return this.popupReply("You're already challenging '" + user.challengeTo.to + "'. Cancel that challenge before challenging someone else."); } if (Config.pmmodchat) { let userGroup = user.group; if (Config.groupsranking.indexOf(userGroup) < Config.groupsranking.indexOf(Config.pmmodchat)) { let groupName = Config.groups[Config.pmmodchat].name || Config.pmmodchat; this.popupReply("Because moderated chat is set, you must be of rank " + groupName + " or higher to challenge users."); return false; } } user.prepBattle(Tools.getFormat(target).id, 'challenge', connection).then(result => { if (result) user.makeChallenge(targetUser, target); }); }, bch: 'blockchallenges', blockchall: 'blockchallenges', blockchalls: 'blockchallenges', blockchallenges: function (target, room, user) { if (user.blockChallenges) return this.errorReply("You are already blocking challenges!"); user.blockChallenges = true; this.sendReply("You are now blocking all incoming challenge requests."); }, blockchallengeshelp: ["/blockchallenges - Blocks challenges so no one can challenge you. Unblock them with /unblockchallenges."], unbch: 'allowchallenges', unblockchall: 'allowchallenges', unblockchalls: 'allowchallenges', unblockchallenges: 'allowchallenges', allowchallenges: function (target, room, user) { if (!user.blockChallenges) return this.errorReply("You are already available for challenges!"); user.blockChallenges = false; this.sendReply("You are available for challenges from now on."); }, allowchallengeshelp: ["/unblockchallenges - Unblocks challenges so you can be challenged again. Block them with /blockchallenges."], cchall: 'cancelChallenge', cancelchallenge: function (target, room, user) { user.cancelChallengeTo(target); }, accept: function (target, room, user, connection) { let userid = toId(target); let format = ''; if (user.challengesFrom[userid]) format = user.challengesFrom[userid].format; if (!format) { this.popupReply(target + " cancelled their challenge before you could accept it."); return false; } user.prepBattle(Tools.getFormat(format).id, 'challenge', connection).then(result => { if (result) user.acceptChallengeFrom(userid); }); }, reject: function (target, room, user) { user.rejectChallengeFrom(toId(target)); }, saveteam: 'useteam', utm: 'useteam', useteam: function (target, room, user) { user.team = target; }, vtm: function (target, room, user, connection) { if (Monitor.countPrepBattle(connection.ip, user.name)) { connection.popup("Due to high load, you are limited to 6 team validations every 3 minutes."); return; } if (!target) return this.errorReply("Provide a valid format."); let originalFormat = Tools.getFormat(target); let format = originalFormat.effectType === 'Format' ? originalFormat : Tools.getFormat('Anything Goes'); if (format.effectType !== 'Format') return this.popupReply("Please provide a valid format."); TeamValidator(format.id).prepTeam(user.team).then(result => { let matchMessage = (originalFormat === format ? "" : "The format '" + originalFormat.name + "' was not found."); if (result.charAt(0) === '1') { connection.popup("" + (matchMessage ? matchMessage + "\n\n" : "") + "Your team is valid for " + format.name + "."); } else { connection.popup("" + (matchMessage ? matchMessage + "\n\n" : "") + "Your team was rejected for the following reasons:\n\n- " + result.slice(1).replace(/\n/g, '\n- ')); } }); }, /********************************************************* * Low-level *********************************************************/ cmd: 'query', query: function (target, room, user, connection) { // Avoid guest users to use the cmd errors to ease the app-layer attacks in emergency mode let trustable = (!Config.emergency || (user.named && user.registered)); let spaceIndex = target.indexOf(' '); let cmd = target; if (spaceIndex > 0) { cmd = target.substr(0, spaceIndex); target = target.substr(spaceIndex + 1); } else { target = ''; } if (cmd === 'userdetails') { let targetUser = Users.get(target); if (!trustable || !targetUser) { connection.send('|queryresponse|userdetails|' + JSON.stringify({ userid: toId(target), rooms: false, })); return false; } let roomList = {}; targetUser.inRooms.forEach(roomid => { if (roomid === 'global') return; let targetRoom = Rooms.get(roomid); if (!targetRoom) return; // shouldn't happen let roomData = {}; if (targetRoom.isPrivate) { if (!user.inRooms.has(roomid) && !user.games.has(roomid)) return; roomData.isPrivate = true; } if (targetRoom.battle) { let battle = targetRoom.battle; roomData.p1 = battle.p1 ? ' ' + battle.p1.name : ''; roomData.p2 = battle.p2 ? ' ' + battle.p2.name : ''; } roomList[roomid] = roomData; }); if (!targetUser.connected) roomList = false; let userdetails = { userid: targetUser.userid, avatar: targetUser.avatar, group: targetUser.group, rooms: roomList, }; connection.send('|queryresponse|userdetails|' + JSON.stringify(userdetails)); } else if (cmd === 'roomlist') { if (!trustable) return false; connection.send('|queryresponse|roomlist|' + JSON.stringify({ rooms: Rooms.global.getRoomList(target), })); } else if (cmd === 'rooms') { if (!trustable) return false; connection.send('|queryresponse|rooms|' + JSON.stringify( Rooms.global.getRooms(user) )); } else if (cmd === 'laddertop') { if (!trustable) return false; Ladders(target).getTop().then(result => { connection.send('|queryresponse|laddertop|' + JSON.stringify(result)); }); } else { // default to sending null if (!trustable) return false; connection.send('|queryresponse|' + cmd + '|null'); } }, trn: function (target, room, user, connection) { let commaIndex = target.indexOf(','); let targetName = target; let targetRegistered = false; let targetToken = ''; if (commaIndex >= 0) { targetName = target.substr(0, commaIndex); target = target.substr(commaIndex + 1); commaIndex = target.indexOf(','); targetRegistered = target; if (commaIndex >= 0) { targetRegistered = !!parseInt(target.substr(0, commaIndex)); targetToken = target.substr(commaIndex + 1); } } user.rename(targetName, targetToken, targetRegistered, connection); }, a: function (target, room, user) { if (!this.can('rawpacket')) return false; // secret sysop command room.add(target); }, /********************************************************* * Help commands *********************************************************/ commands: 'help', h: 'help', '?': 'help', help: function (target, room, user) { target = target.toLowerCase(); // overall if (target === 'help' || target === 'h' || target === '?' || target === 'commands') { this.sendReply("/help OR /h OR /? - Gives you help."); } else if (!target) { this.sendReply("COMMANDS: /msg, /reply, /logout, /challenge, /search, /rating, /whois"); this.sendReply("OPTION COMMANDS: /nick, /avatar, /ignore, /away, /back, /timestamps, /highlight"); this.sendReply("INFORMATIONAL COMMANDS: /data, /dexsearch, /movesearch, /groups, /faq, /rules, /intro, /formatshelp, /othermetas, /learn, /analysis, /calc (replace / with ! to broadcast. Broadcasting requires: + % @ * # & ~)"); if (user.group !== Config.groupsranking[0]) { this.sendReply("DRIVER COMMANDS: /warn, /mute, /hourmute, /unmute, /alts, /forcerename, /modlog, /modnote, /lock, /unlock, /announce, /redirect"); this.sendReply("MODERATOR COMMANDS: /ban, /unban, /ip, /modchat"); this.sendReply("LEADER COMMANDS: /declare, /forcetie, /forcewin, /promote, /demote, /banip, /host, /unbanall"); } this.sendReply("For an overview of room commands, use /roomhelp"); this.sendReply("For details of a specific command, use something like: /help data"); } else { let altCommandHelp; let helpCmd; let targets = target.split(' '); let allCommands = CommandParser.commands; if (typeof allCommands[target] === 'string') { // If a function changes with command name, help for that command name will be searched first. altCommandHelp = target + 'help'; if (altCommandHelp in allCommands) { helpCmd = altCommandHelp; } else { helpCmd = allCommands[target] + 'help'; } } else if (targets.length > 1 && typeof allCommands[targets[0]] === 'object') { // Handle internal namespace commands let helpCmd = targets[targets.length - 1] + 'help'; let namespace = allCommands[targets[0]]; for (let i = 1; i < targets.length - 1; i++) { if (!namespace[targets[i]]) return this.errorReply("Help for the command '" + target + "' was not found. Try /help for general help"); namespace = namespace[targets[i]]; } if (typeof namespace[helpCmd] === 'object') return this.sendReply(namespace[helpCmd].join('\n')); if (typeof namespace[helpCmd] === 'function') return this.parse('/' + targets.slice(0, targets.length - 1).concat(helpCmd).join(' ')); return this.errorReply("Help for the command '" + target + "' was not found. Try /help for general help"); } else { helpCmd = target + 'help'; } if (helpCmd in allCommands) { if (typeof allCommands[helpCmd] === 'function') { // If the help command is a function, parse it instead this.parse('/' + helpCmd); } else if (Array.isArray(allCommands[helpCmd])) { this.sendReply(allCommands[helpCmd].join('\n')); } } else { this.errorReply("Help for the command '" + target + "' was not found. Try /help for general help"); } } }, }; process.nextTick(() => { CommandParser.multiLinePattern.register('>>>? '); CommandParser.multiLinePattern.register('/(room|staff)(topic|intro) '); });
Change slowchat requirements to mod+
commands.js
Change slowchat requirements to mod+
<ide><path>ommands.js <ide> slowchat: function (target, room, user) { <ide> if (!target) return this.sendReply("Slow chat is currently set to: " + (room.slowchat ? room.slowchat : false)); <ide> if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); <del> if (!this.can('editroom', null, room)) return false; <add> if (!this.can('modchat', null, room)) return false; <ide> <ide> let targetInt = parseInt(target); <ide> if (target === 'off' || target === 'disable' || target === 'false') {
JavaScript
mit
345fec11307bddaf61839cb2c4976f9657fb9537
0
jbaicoianu/elation-engine
elation.require(['utils.workerpool', 'engine.external.three.three', 'engine.external.libgif'], function() { THREE.Cache.enabled = true; // TODO - submit pull request to add these to three.js THREE.SBSTexture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { THREE.Texture.call( this, image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); this.repeat.x = 0.5; } THREE.SBSTexture.prototype = Object.create( THREE.Texture.prototype ); THREE.SBSTexture.prototype.constructor = THREE.SBSTexture; THREE.SBSTexture.prototype.setEye = function(eye) { if (eye == 'left') { this.offset.x = (this.reverse ? 0.5 : 0); } else { this.offset.x = (this.reverse ? 0 : 0.5); } this.eye = eye; } THREE.SBSTexture.prototype.swap = function() { if (this.eye == 'right') { this.setEye('left'); } else { this.setEye('right'); } } THREE.SBSVideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { THREE.VideoTexture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); this.repeat.x = 0.5; this.reverse = false; } THREE.SBSVideoTexture.prototype = Object.create( THREE.SBSTexture.prototype ); THREE.SBSVideoTexture.prototype.constructor = THREE.SBSVideoTexture; THREE.SBSVideoTexture.prototype = Object.assign( Object.create( THREE.Texture.prototype ), { constructor: THREE.SBSVideoTexture, isVideoTexture: true, update: function () { var video = this.image; if ( video.readyState >= video.HAVE_CURRENT_DATA ) { this.needsUpdate = true; } }, setEye: function(eye) { if (eye == 'left') { this.offset.x = (this.reverse ? 0.5 : 0); } else { this.offset.x = (this.reverse ? 0 : 0.5); } this.eye = eye; } } ); elation.extend('engine.assets', { assets: {}, types: {}, corsproxy: '', placeholders: {}, init: function(dummy) { var corsproxy = elation.config.get('engine.assets.corsproxy', ''); //THREE.Loader.Handlers.add(/.*/i, corsproxy); //THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() ); if (corsproxy != '') { this.setCORSProxy(corsproxy, dummy); } }, loadAssetPack: function(url, baseurl) { this.assetroot = new elation.engine.assets.pack({name: url, src: url, baseurl: baseurl}); return this.assetroot; }, loadJSON: function(json, baseurl) { var assetpack = new elation.engine.assets.pack({name: "asdf", baseurl: baseurl, json: json}); return assetpack; }, get: function(asset) { if (!ENV_IS_BROWSER) return; var type = asset.assettype || 'base'; var assetclass = elation.engine.assets[type] || elation.engine.assets.unknown; var assetobj = new assetclass(asset); if (!elation.engine.assets.types[type]) elation.engine.assets.types[type] = {}; if (assetobj.name) { elation.engine.assets.assets[assetobj.name] = assetobj; elation.engine.assets.types[type][assetobj.name] = assetobj; } return assetobj; }, find: function(type, name, raw) { if (!ENV_IS_BROWSER) return; var asset; if (elation.engine.assets.types[type]) { asset = elation.engine.assets.types[type][name]; } //console.log(asset, type, name, elation.engine.assets.types[type]); if (raw) { return asset; } if (asset) { return asset.getInstance(); } else { asset = elation.engine.assets.get({assettype: type, name: name}); return asset.getInstance(); } return undefined; }, setCORSProxy: function(proxy, dummy) { elation.engine.assets.corsproxy = proxy; var loader = new elation.engine.assets.corsproxyloader(proxy, undefined, dummy); elation.engine.assetdownloader.setCORSProxy(proxy); THREE.Loader.Handlers.add(/.*/i, loader); if (!elation.env.isWorker && elation.engine.assets.loaderpool) { elation.engine.assets.loaderpool.sendMessage('setcorsproxy', proxy); } }, setPlaceholder: function(type, name) { this.placeholders[type] = this.find(type, name); }, loaderpool: false }); elation.extend('engine.assetdownloader', new function() { this.corsproxy = ''; this.queue = {}; this.setCORSProxy = function(proxy) { this.corsproxy = proxy; } this.isUrlInQueue = function(url) { var fullurl = url; if (this.corsproxy && fullurl.indexOf(this.corsproxy) != 0) fullurl = this.corsproxy + fullurl; return fullurl in this.queue; } this.fetchURLs = function(urls, progress) { var promises = [], queue = this.queue; for (var i = 0; i < urls.length; i++) { let subpromise = this.fetchURL(urls[i], progress); promises.push(subpromise); } return Promise.all(promises); } this.fetchURL = function(url, progress) { var corsproxy = this.corsproxy; let agent = this.getAgentForURL(url); return agent.fetch(url, progress); } this.getAgentForURL = function(url) { let urlparts = elation.utils.parseURL(url); let agentname = urlparts.scheme; // Check if we have a handler for this URL protocol, if we don't then fall back to the default 'xhr' agent if (!elation.engine.assetloader.agent[agentname]) { agentname = 'xhr'; } return elation.engine.assetloader.agent[agentname]; } }); elation.extend('engine.assetloader.agent.xhr', new function() { this.getFullURL = function(url) { } this.fetch = function(url, progress) { return new Promise(function(resolve, reject) { if (!this.queue) this.queue = {}; var fullurl = url; let corsproxy = elation.engine.assetdownloader.corsproxy; if (corsproxy && fullurl.indexOf(corsproxy) != 0 && fullurl.indexOf('blob:') != 0 && fullurl.indexOf('data:') != 0 && fullurl.indexOf(self.location.origin) != 0) { fullurl = corsproxy + fullurl; } if (!this.queue[fullurl]) { var xhr = this.queue[fullurl] = elation.net.get(fullurl, null, { responseType: 'arraybuffer', onload: (ev) => { delete this.queue[fullurl]; var status = ev.target.status; if (status == 200) { resolve(ev); } else { reject(); } }, onerror: () => { delete this.queue[fullurl]; reject(); }, onprogress: progress, headers: { 'X-Requested-With': 'Elation Engine asset loader' } }); } else { var xhr = this.queue[fullurl]; if (xhr.readyState == 4) { setTimeout(function() { resolve({target: xhr}); }, 0); } else { elation.events.add(xhr, 'load', resolve); elation.events.add(xhr, 'error', reject); elation.events.add(xhr, 'progress', progress); } } }); } }); elation.extend('engine.assetloader.agent.dat', new function() { this.fetch = function(url) { return new Promise((resolve, reject) => { if (typeof DatArchive == 'undefined') { console.warn('DatArchive not supported in this browser'); reject(); return; } let urlparts = elation.utils.parseURL(url); if (urlparts.host) { this.getArchive(urlparts.host).then(archive => { let path = urlparts.path; if (path[path.length-1] == '/') { path += 'index.html'; } archive.readFile(path, 'binary').then(file => { // FIXME - we're emulating an XHR object here, because the asset loader was initially written for XHR and uses some of the convenience functions resolve({ target: { responseURL: url, data: file, response: file, getResponseHeader(header) { if (header.toLowerCase() == 'content-type') { // FIXME - We should implement mime type detection at a lower level, and avoid the need to access the XHR object in calling code return 'application/octet-stream'; } } }, }); }); }); } }); } this.getArchive = function(daturl) { return new Promise((resolve, reject) => { if (!this.archives) this.archives = {}; if (this.archives[daturl]) { resolve(this.archives[daturl]); } else { DatArchive.load(daturl).then(archive => { this.archives[daturl] = archive; resolve(this.archives[daturl]); }); } }); } }); elation.extend('engine.assetcache', new function() { this.queued = []; this.open = function(name) { this.cachename = name; caches.open(name).then(elation.bind(this, this.setCache)); } this.setCache = function(cache) { this.cache = cache; // If we queued any cache lookups before the cache opened, resolve them return Promises.all(this.queued); } this.get = function(key) { if (this.cache) { return new Promise(elation.bind(function(resolve, reject) { var req = (key instanceof Request ? key : new Request(key)); this.cache.get(req).then(resolve); })); } else { // TODO - queue it! console.log('AssetCache warning: cache not open yet, cant get', key, this.cachename); } } this.set = function(key, value) { if (this.cache) { return new Promise(elation.bind(function(resolve, reject) { var req = (key instanceof Request ? key : new Request(key)); this.cache.get(req).then(resolve); })); } else { // TODO - queue it! console.log('AssetCache warning: cache not open yet, cant set', key, value, this.cachename); } } }); elation.define('engine.assets.corsproxyloader', { _construct: function(corsproxy, manager, dummy) { this.corsproxy = corsproxy || ''; this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; this.uuidmap = {}; this.dummy = dummy; }, load: function ( url, onLoad, onProgress, onError ) { var fullurl = url; if (this.corsproxy != '' && url.indexOf(this.corsproxy) != 0 && url.indexOf('blob:') != 0 && url.indexOf('data:') != 0 && url.indexOf(self.location.origin) != 0) { fullurl = this.corsproxy + url; } if (!this.dummy) { return THREE.TextureLoader.prototype.load.call(this, fullurl, onLoad, onProgress, onError); } return this.getDummyTexture(fullurl, onLoad); }, getDummyTexture: function(url, onLoad) { var texture = new THREE.Texture(); var uuid = this.uuidmap[url]; if (!uuid) { uuid = this.uuidmap[url] = THREE.Math.generateUUID(); } var img = { uuid: uuid, src: url, toDataURL: function() { return url; } }; texture.image = img; if (onLoad) { setTimeout(onLoad.bind(img, texture), 0); } return texture; } }, THREE.TextureLoader); elation.define('engine.assets.base', { assettype: 'base', name: '', description: '', license: 'unknown', author: 'unknown', sourceurl: false, size: false, loaded: false, preview: false, baseurl: '', src: false, proxy: true, preload: false, instances: [], _construct: function(args) { elation.class.call(this, args); this.init(); }, init: function() { this.instances = []; if (this.preload && this.preload !== 'false') { this.load(); } }, load: function() { console.log('engine.assets.base load() should not be called directly', this); }, isURLRelative: function(src) { if (src && src.match(/^(https?:)?\/\//) || src[0] == '/') { return false; } return true; }, isURLAbsolute: function(src) { return (src[0] == '/' && src[1] != '/'); }, isURLLocal: function(src) { if (this.isURLBlob(src) || this.isURLData(src)) { return true; } if (src.match(/^(https?:)?\/\//i)) { return (src.indexOf(self.location.origin) == 0); } return ( (src[0] == '/' && src[1] != '/') || (src[0] != '/') ); }, isURLData: function(url) { if (!url) return false; return url.indexOf('data:') == 0; }, isURLBlob: function(url) { if (!url) return false; return url.indexOf('blob:') == 0; }, isURLProxied: function(url) { if (!url || !elation.engine.assets.corsproxy) return false; return url.indexOf(elation.engine.assets.corsproxy) == 0; }, getFullURL: function(url, baseurl) { if (!url) url = this.src; if (!url) url = ''; if (!baseurl) baseurl = this.baseurl; var fullurl = url; if (!this.isURLBlob(fullurl) && !this.isURLData(fullurl)) { if (this.isURLRelative(fullurl) && fullurl.substr(0, baseurl.length) != baseurl) { fullurl = baseurl + fullurl; } else if (this.isURLProxied(fullurl)) { fullurl = fullurl.replace(elation.engine.assets.corsproxy, ''); } else if (this.isURLAbsolute(fullurl)) { fullurl = self.location.origin + fullurl; } } return fullurl; }, getProxiedURL: function(url, baseurl) { var proxiedurl = this.getFullURL(url, baseurl); if (this.proxy && this.proxy != 'false' && proxiedurl && elation.engine.assets.corsproxy && !this.isURLLocal(proxiedurl) && proxiedurl.indexOf(elation.engine.assets.corsproxy) == -1) { var re = /:\/\/([^\/\@]+@)/; var m = proxiedurl.match(re); // Check it asset has authentication info, and pass it through if it does if (m) { proxiedurl = elation.engine.assets.corsproxy.replace(':\/\/', ':\/\/' + m[1]) + proxiedurl.replace(m[1], ''); } else { proxiedurl = elation.engine.assets.corsproxy + proxiedurl; } } return proxiedurl; }, getBaseURL: function(url) { var url = url || this.getFullURL(); var parts = url.split('/'); parts.pop(); return parts.join('/') + '/'; }, getInstance: function(args) { return undefined; }, executeWhenLoaded: function(callback) { if (this.loaded) { // We've already loaded the asset, so execute the callback asynchronously setTimeout(callback, 0); } else { // Asset isn't loaded yet, set up a local callback that can self-remove, so our callback only executes once let cb = (ev) => { elation.events.remove(this, 'asset_load', cb); callback(); }; elation.events.add(this, 'asset_load', cb); } } }, elation.class); elation.define('engine.assets.unknown', { assettype: 'unknown', load: function() { }, _construct: function(args) { console.log('Unknown asset type: ', args.assettype, args); elation.engine.assets.base.call(this, args); } }, elation.engine.assets.base); elation.define('engine.assets.image', { assettype: 'image', src: false, canvas: false, sbs3d: false, ou3d: false, reverse3d: false, texture: false, frames: false, flipy: true, invert: false, imagetype: '', tex_linear: true, hasalpha: null, rawimage: null, preload: true, maxsize: null, load: function() { if (this.texture) { this._texture = this.texture; } else if (this.src) { var fullurl = this.getFullURL(this.src); var texture; if (this.sbs3d) { texture = this._texture = new THREE.SBSTexture(); texture.reverse = this.reverse3d; } else { texture = this._texture = new THREE.Texture(); } texture.image = this.canvas = this.getCanvas(); texture.image.originalSrc = this.src; texture.sourceFile = this.src; texture.needsUpdate = true; texture.flipY = (this.flipy === true || this.flipy === 'true'); if (this.isURLData(fullurl)) { this.loadImageByURL(); } else { elation.engine.assetdownloader.fetchURLs([fullurl], elation.bind(this, this.handleProgress)).then( elation.bind(this, function(events) { var xhr = events[0].target; var type = this.contenttype = xhr.getResponseHeader('content-type') if (typeof createImageBitmap == 'function' && type != 'image/gif') { var blob = new Blob([xhr.response], {type: type}); createImageBitmap(blob).then(elation.bind(this, this.handleLoad), elation.bind(this, this.handleBitmapError)); } else { this.loadImageByURL(); } this.state = 'processing'; elation.events.fire({element: this, type: 'asset_load_processing'}); }), elation.bind(this, function(error) { this.state = 'error'; elation.events.fire({element: this, type: 'asset_error'}); }) ); elation.events.fire({element: this, type: 'asset_load_queued'}); } } else if (this.canvas) { var texture = this._texture = new THREE.Texture(); texture.image = this.canvas; texture.image.originalSrc = ''; texture.sourceFile = ''; texture.needsUpdate = true; texture.flipY = this.flipy; elation.events.add(this.canvas, 'update', () => texture.needsUpdate = true); this.sendLoadEvents(); } }, loadImageByURL: function() { var proxiedurl = this.getProxiedURL(this.src); var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' ); elation.events.add(image, 'load', elation.bind(this, this.handleLoad, image)); elation.events.add(image, 'error', elation.bind(this, this.handleError)); image.crossOrigin = 'anonymous'; image.src = proxiedurl; return image; }, getCanvas: function() { if (!this.canvas) { var canvas = document.createElement('canvas'); var size = 32, gridcount = 4, gridsize = size / gridcount; canvas.width = size; canvas.height = size; var ctx = canvas.getContext('2d'); ctx.fillStyle = '#cccccc'; ctx.fillRect(0,0,size,size); ctx.fillStyle = '#666666'; for (var i = 0; i < gridcount*gridcount; i += 1) { var x = i % gridcount; var y = Math.floor(i / gridcount); if ((x + y) % 2 == 0) { ctx.fillRect(x * gridsize, y * gridsize, gridsize, gridsize); } } this.canvas = canvas; } return this.canvas; }, handleLoad: function(image) { //console.log('loaded image', this, image); this.rawimage = image; var texture = this._texture; texture.image = this.processImage(image); texture.needsUpdate = true; texture.wrapS = texture.wrapT = THREE.RepeatWrapping; texture.anisotropy = elation.config.get('engine.assets.image.anisotropy', 4); this.loaded = true; this.uploaded = false; this.sendLoadEvents(); }, sendLoadEvents: function() { elation.events.fire({type: 'asset_load', element: this._texture}); elation.events.fire({type: 'asset_load', element: this}); elation.events.fire({element: this, type: 'asset_load_complete'}); }, handleProgress: function(ev) { var progress = { src: ev.target.responseURL, loaded: ev.loaded, total: ev.total }; this.size = ev.total; //console.log('image progress', progress); elation.events.fire({element: this, type: 'asset_load_progress', data: progress}); }, handleBitmapError: function(src, ev) { console.log('Error loading image via createImageBitmap, fall back on normal image'); this.loadImageByURL(); }, handleError: function(ev) { console.log('image error!', this, this._texture.image, ev); var canvas = this.getCanvas(); var size = 16; canvas.width = canvas.height = size; var ctx = canvas.getContext('2d'); ctx.fillStyle = '#f0f'; ctx.fillRect(0,0,size,size); this._texture.image = canvas; this._texture.needsUpdate = true; this._texture.generateMipmaps = false; elation.events.fire({type: 'asset_error', element: this._texture}); }, getInstance: function(args) { if (!this._texture) { this.load(); } return this._texture; }, processImage: function(image) { this.imagetype = this.detectImageType(); if (this.imagetype == 'gif') { this.hasalpha = true; // FIXME - if we're cracking the gif open already, we should be able to tell if it has alpha or not return this.convertGif(image); } else { //if (!elation.engine.materials.isPowerOfTwo(image.width) || !elation.engine.materials.isPowerOfTwo(image.height)) { // Scale up the texture to the next highest power of two dimensions. var canvas = this.canvas; canvas.src = this.src; canvas.originalSrc = this.src; var imagemax = elation.utils.any(this.maxsize, elation.config.get('engine.assets.image.maxsize', Infinity)); canvas.width = Math.min(imagemax, this.nextHighestPowerOfTwo(image.width)); canvas.height = Math.min(imagemax, this.nextHighestPowerOfTwo(image.height)); var ctx = canvas.getContext("2d"); ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height); if (this.hasalpha === null) { if (!this.src.match(/\.jpg$/i)) { this.hasalpha = this.canvasHasAlpha(canvas); } else { this.hasalpha = false; } } this._texture.generateMipmaps = elation.config.get('engine.assets.image.mipmaps', true); if (this.invert) { this.invertImage(canvas); } return canvas; //} else { // return image; } }, convertGif: function(image) { var gif = new SuperGif({gif: image, draw_while_loading: true, loop_mode: false, auto_play: false}); // Decode gif frames into a series of canvases, then swap between canvases to animate the texture // This could be made more efficient by uploading each frame to the GPU as a separate texture, and // swapping the texture handle each frame instead of re-uploading the frame. This is hard to do // with the way Three.js handles Texture objects, but it might be possible to fiddle with // renderer.properties[texture].__webglTexture directly // It could also be made more efficient by moving the gif decoding into a worker, and just passing // back messages with decoded frame data. var getCanvas = () => { var newcanvas = document.createElement('canvas'); newcanvas.width = this.nextHighestPowerOfTwo(image.width); newcanvas.height = this.nextHighestPowerOfTwo(image.height); return newcanvas; } var newcanvas = getCanvas(); var mainctx = newcanvas.getContext('2d'); var texture = this._texture; texture.minFilter = THREE.NearestFilter; texture.magFilter = THREE.NearestFilter; //texture.generateMipmaps = false; var frames = []; var frametextures = this.frames = []; var framedelays = []; var framenum = -1; var lastframe = texture; gif.load(function() { var canvas = gif.get_canvas(); var doGIFFrame = function(isstatic) { framenum = (framenum + 1) % gif.get_length(); var frame = frames[framenum]; if (!frame) { gif.move_to(framenum); var gifframe = gif.get_frame(framenum); if (gifframe) { frame = frames[framenum] = { framenum: framenum, delay: gifframe.delay, image: getCanvas() }; ctx = frame.image.getContext('2d'); newcanvas.width = canvas.width; newcanvas.height = canvas.height; //mainctx.putImageData(gifframe.data, 0, 0, 0, 0, canvas.width, canvas.height); ctx.drawImage(canvas, 0, 0, canvas.width, canvas.height, 0, 0, frame.image.width, frame.image.height); texture.minFilter = texture.magFilter = THREE.NearestFilter; // FIXME - should this be hardcoded for all gifs? frametextures[framenum] = new THREE.Texture(frame.image); frametextures[framenum].minFilter = frametextures[framenum].magFilter = THREE.NearestFilter; // FIXME - should this be hardcoded for all gifs? frametextures[framenum].wrapS = frametextures[framenum].wrapT = THREE.RepeatWrapping; frametextures[framenum].needsUpdate = true; } } if (frame && frame.image) { /* texture.image = frame.image; texture.needsUpdate = true; elation.events.fire({type: 'update', element: texture}); */ var frametex = frametextures[framenum] || lastframe; if (frametex !== lastframe) { lastframe = frametex; } elation.events.fire({element: texture, type: 'asset_update', data: frametex}); } if (!isstatic) { var delay = (frame && frame.delay > 0 ? frame.delay : 10); setTimeout(doGIFFrame, delay * 10); } } doGIFFrame(gif.get_length() == 1); }); return newcanvas; }, detectImageType: function() { // FIXME - really we should be cracking open the file and looking at magic number to determine this // We might also be able to get hints from the XHR loader about the image's MIME type var type = 'jpg'; if (this.contenttype) { var map = { 'image/jpeg': 'jpg', 'image/png': 'png', 'image/gif': 'gif', }; type = map[this.contenttype]; } else if (this.src.match(/\.(.*?)$/)) { var parts = this.src.split('.'); type = parts.pop(); } return type; }, canvasHasAlpha: function(canvas) { if (!(this.imagetype == 'gif' || this.imagetype == 'png')) { return false; } // This could be made more efficient by doing the work on the gpu. We could make a scene with the // texture and an orthographic camera, and a shader which returns alpha=0 for any alpha value < 1 // We could then perform a series of downsamples until the texture is (1,1) in size, and read back // that pixel value with readPixels(). If there was any alpha in the original image, this final // pixel should also be transparent. var width = Math.min(64, canvas.width), height = Math.min(64, canvas.height); if (!this._scratchcanvas) { this._scratchcanvas = document.createElement('canvas'); this._scratchcanvasctx = this._scratchcanvas.getContext('2d'); } var checkcanvas = this._scratchcanvas, ctx = this._scratchcanvasctx; checkcanvas.width = width; checkcanvas.height = height; ctx.drawImage(canvas, 0, 0, canvas.width, canvas.height, 0, 0, width, height); var pixeldata = ctx.getImageData(0, 0, width, height); var hasalpha = false; for (var i = 0; i < pixeldata.data.length; i+=4) { if (pixeldata.data[i+3] != 255) { return true; } } return false; }, invertImage: function(canvas) { var ctx = canvas.getContext('2d'); var pixeldata = ctx.getImageData(0, 0, canvas.width, canvas.height); for (var i = 0; i < pixeldata.data.length; i+=4) { pixeldata.data[i] = 255 - pixeldata.data[i]; pixeldata.data[i+1] = 255 - pixeldata.data[i+1]; pixeldata.data[i+2] = 255 - pixeldata.data[i+2]; } ctx.putImageData(pixeldata, 0, 0); }, nextHighestPowerOfTwo: function(num) { num--; for (var i = 1; i < 32; i <<= 1) { num = num | num >> i; } return num + 1; } }, elation.engine.assets.base); elation.define('engine.assets.video', { assettype: 'video', src: false, sbs3d: false, ou3d: false, reverse3d: false, auto_play: false, texture: false, load: function() { var url = this.getProxiedURL(this.src); var video = document.createElement('video'); video.muted = false; video.src = url; video.crossOrigin = 'anonymous'; this._video = video; if (this.sbs3d) { this._texture = new THREE.SBSVideoTexture(video); this._texture.reverse = this.reverse3d; } else { this._texture = new THREE.VideoTexture(video); } this._texture.minFilter = THREE.LinearFilter; elation.events.add(video, 'loadeddata', elation.bind(this, this.handleLoad)); elation.events.add(video, 'error', elation.bind(this, this.handleError)); if (this.auto_play) { // FIXME - binding for easy event removal later. This should happen at a lower level this.handleAutoplayStart = elation.bind(this, this.handleAutoplayStart); // Bind on next tick to avoid time-ou firing prematurely due to load-time lag setTimeout(elation.bind(this, function() { elation.events.add(video, 'playing', this.handleAutoplayStart); this._autoplaytimeout = setTimeout(elation.bind(this, this.handleAutoplayTimeout), 1000); }), 0); var promise = video.play(); if (promise) { promise.then(elation.bind(this, function() { this.handleAutoplayStart(); })).catch(elation.bind(this, function(err) { // If autoplay failed, retry with muted video var strerr = err.toString(); if (strerr.indexOf('NotAllowedError') == 0) { video.muted = true; video.play().catch(elation.bind(this, this.handleAutoplayError)); } else if (strerr.indexOf('NotSupportedError') == 0) { this.initHLS(); } })); } } }, handleLoad: function() { this.loaded = true; elation.events.fire({element: this, type: 'asset_load'}); elation.events.fire({element: this, type: 'asset_load_complete'}); }, handleProgress: function(ev) { //console.log('image progress!', ev); var progress = { src: ev.target.responseURL, loaded: ev.loaded, total: ev.total }; this.size = ev.total; elation.events.fire({element: this, type: 'asset_load_progress', data: progress}); }, handleError: function(ev) { //console.log('video uh oh!', ev); //this._texture = false; //console.log('Video failed to load, try HLS'); }, handleAutoplayStart: function(ev) { if (this._autoplaytimeout) { clearTimeout(this._autoplaytimeout); } elation.events.remove(this._video, 'playing', this.handleAutoplayStart); elation.events.fire({element: this._texture, type: 'autoplaystart'}); }, handleAutoplayTimeout: function(ev) { elation.events.fire({element: this._texture, type: 'autoplaytimeout'}); }, handleAutoplayFail: function(ev) { elation.events.fire({element: this._texture, type: 'autoplayfail'}); }, getInstance: function(args) { if (!this._texture) { this.load(); } return this._texture; }, initHLS: function() { if (typeof Hls != 'function') { elation.file.get('js', 'https://cdn.jsdelivr.net/npm/hls.js@latest', elation.bind(this, this.initHLS)); return; } var hls = new Hls(); hls.loadSource(this.getProxiedURL()); hls.attachMedia(this._video); if (this.auto_play) { var video = this._video; hls.on(Hls.Events.MANIFEST_PARSED, function() { video.play(); }); } } }, elation.engine.assets.base); elation.define('engine.assets.material', { assettype: 'material', color: null, map: null, normalMap: null, specularMap: null, load: function() { var matargs = {}; if (this.color) matargs.color = new THREE.Color(this.color); if (this.map) matargs.map = elation.engine.assets.find('image', this.map); if (this.normalMap) matargs.normalMap = elation.engine.assets.find('image', this.normalMap); if (this.specularMap) matargs.specularMap = elation.engine.assets.find('image', this.normalMap); this._material = new THREE.MeshPhongMaterial(matargs); console.log('new material!', this._material); }, getInstance: function(args) { if (!this._material) { this.load(); } return this._material; }, handleLoad: function(data) { console.log('loaded image', data); this._texture = data; }, handleProgress: function(ev) { }, handleError: function(ev) { console.log('image uh oh!', ev); this._texture = false; } }, elation.engine.assets.base); elation.define('engine.assets.sound', { assettype: 'sound', src: false, load: function() { if (this.src) { //this._sound = new THREE.Audio(this.src); } }, handleLoad: function(data) { console.log('loaded sound', data); this._sound = data; this.loaded = true; }, handleProgress: function(ev) { console.log('sound progress!', ev); this.size = ev.total; }, handleError: function(ev) { console.log('sound uh oh!', ev); this._sound = false; }, getInstance: function(args) { return this; /* if (!this._sound) { this.load(); } return this._sound; */ } }, elation.engine.assets.base); elation.define('engine.assets.model', { assettype: 'model', src: false, mtl: false, tex: false, tex0: false, tex1: false, tex2: false, tex3: false, tex_linear: true, color: false, modeltype: '', compression: 'none', object: false, loadworkers: [ ], getInstance: function(args) { var group = new THREE.Group(); if (!this._model) { if (!this.loading) { this.load(); } var mesh; if (elation.engine.assets.placeholders.model) { mesh = elation.engine.assets.placeholders.model.clone(); } else { mesh = this.createPlaceholder(); } group.add(mesh); } else { //group.add(this._model.clone()); this.fillGroup(group, this._model); //group = this._model.clone(); this.assignTextures(group, args); setTimeout(function() { elation.events.fire({type: 'asset_load', element: group}); elation.events.fire({type: 'asset_load', element: this}); }, 0); } this.instances.push(group); return group; }, fillGroup: function(group, source) { if (!source) source = this._model; if (source) { /* group.position.copy(source.position); group.quaternion.copy(source.quaternion); //group.scale.copy(source.scale); if (source.children) { source.children.forEach(function(n) { group.add(n.clone()); }); } */ var newguy = source.clone(); group.add(newguy); newguy.updateMatrix(true); newguy.updateMatrixWorld(true); newguy.traverse(function(n) { if (n instanceof THREE.SkinnedMesh) { //n.rebindByName(newguy); } }); } return group; }, copyMaterial: function(oldmat) { var m = new THREE.MeshPhongMaterial(); m.anisotropy = elation.config.get('engine.assets.image.anisotropy', 4); m.name = oldmat.name; m.map = oldmat.map; m.normalMap = oldmat.normalMap; m.lightMap = oldmat.lightMap; m.color.copy(oldmat.color); m.transparent = oldmat.transparent; m.alphaTest = oldmat.alphaTest; return m; }, assignTextures: function(group, args) { var minFilter = (this.tex_linear && this.tex_linear != 'false' ? THREE.LinearMipMapLinearFilter : THREE.NearestFilter); var magFilter = (this.tex_linear && this.tex_linear != 'false' ? THREE.LinearFilter : THREE.NearestFilter); if (this.tex) this.tex0 = this.tex; if (this.tex0) { var tex0 = elation.engine.assets.find('image', this.tex0); if (!tex0) { var asset = elation.engine.assets.get({ assettype: 'image', name: this.tex0, src: this.tex0, baseurl: this.baseurl }); tex0 = asset.getInstance(); } } group.traverse(function(n) { if (n.material) { var materials = (elation.utils.isArray(n.material) ? n.material : [n.material]); materials.forEach(function(m) { if (tex0) { //m.transparent = true; m.alphaTest = 0.1; m.map = tex0; } if (m.map) { m.map.minFilter = minFilter; m.map.magFilter = magFilter; } m.needsUpdate = true; //if (m.color) m.color.setHex(0xffffff); }); } }); }, createPlaceholder: function() { /* var geo = new THREE.TextGeometry('loading...', { size: 1, height: .1, font: 'helvetiker' }); var font = elation.engine.assets.find('font', 'helvetiker'); var geo = new THREE.TextGeometry( 'loading...', { size: 1, height: 0.1, font: font, }); */ /* var geo = new THREE.SphereGeometry(0.25); //geo.applyMatrix(new THREE.Matrix4().makeScale(1,1,.1)); var mat = new THREE.MeshPhongMaterial({color: 0x999900, emissive: 0x333333, opacity: 0.5, transparent: true}); this.placeholder = new THREE.Mesh(geo, mat); */ this.placeholder = new THREE.Object3D(); return this.placeholder; }, load: function() { if (this.object) { this.loading = false; this.loaded = true; this.state = 'complete'; this._model = new THREE.Group(); setTimeout(() => this.complete(this.object), 0); } else if (this.src) { this.loading = true; this.loaded = false; this.state = 'loading'; var loadargs = {src: this.getFullURL()}; if (this.mtl) loadargs.mtl = this.getFullURL(this.mtl, this.getBaseURL(loadargs.src)); this.queueForDownload(loadargs); } else { this.removePlaceholders(); } }, detectType: function(url) { var parts = url.split('.'); var extension = parts.pop(); if (extension == 'gz') { extension = parts.pop(); this.extension = extension; this.compression = 'gzip'; } return extension.toLowerCase(); }, queueForDownload: function(jobdata) { var urls = [jobdata.src]; if (jobdata.mtl) urls.push(jobdata.mtl); this.state = 'queued'; var progressfunc = elation.bind(this, function(progress) { if (this.state == 'queued') { this.state = 'downloading'; elation.events.fire({element: this, type: 'asset_load_start'}); } this.handleLoadProgress(progress); }); elation.engine.assetdownloader.fetchURLs(urls, progressfunc).then( elation.bind(this, function(events) { var files = []; events.forEach(function(ev) { var url = ev.target.responseURL, data = ev.target.response; if (url == jobdata.src) { jobdata.srcdata = data; } else if (url == jobdata.mtl) { jobdata.mtldata = data; } }); this.state = 'processing'; this.loadWithWorker(jobdata); elation.events.fire({element: this, type: 'asset_load_processing'}); }), elation.bind(this, function(error) { this.state = 'error'; elation.events.fire({element: this, type: 'asset_error'}); }) ); elation.events.fire({element: this, type: 'asset_load_queued'}); }, loadWithWorker: function(jobdata) { this._model = new THREE.Group(); this._model.userData.loaded = false; if (!elation.engine.assets.loaderpool) { var numworkers = elation.config.get('engine.assets.workers', 'auto'); // default to 'auto' unless otherwise specified if (numworkers == 'auto') { // 'auto' means use all cores, minus one for the main thread let numcores = navigator.hardwareConcurrency || 2; // Safari returns NaN for navigator.hardwareConcurrency unless you enable a dev flag. Fall back 2 cores, which is what iOS would cap this value at anyway numworkers = Math.max(1, numcores - 1); // We need at least one worker, even on single-core systems } elation.engine.assets.loaderpool = new elation.utils.workerpool({component: 'engine.assetworker', scriptsuffix: 'assetworker', num: numworkers}); } elation.engine.assets.loaderpool.addJob(jobdata) .then( elation.bind(this, this.handleLoadJSON), elation.bind(this, this.handleLoadError) //elation.bind(this, this.handleLoadProgress) ); }, complete: function(object) { this.removePlaceholders(); this._model.userData.loaded = true; //this._model.add(scene); this.fillGroup(this._model, object); this.extractTextures(object); //this.assignTextures(scene); this.instances.forEach(elation.bind(this, function(n) { if (!n.userData.loaded) { n.userData.loaded = true; //n.add(scene.clone()); this.fillGroup(n, object); //this.assignTextures(n); elation.events.fire({type: 'asset_load', element: n}); //elation.events.fire({type: 'asset_load_complete', element: this}); } })); this.state = 'complete'; elation.events.fire({element: this, type: 'asset_load_processed'}); elation.events.fire({type: 'asset_load', element: this}); }, handleLoadJSON: function(json) { if (json) { this.loaded = true; var parser = new THREE.ObjectLoader(); parser.setCrossOrigin('anonymous'); var scene = parser.parse(json); this.complete(scene); } else { // no model data, error! elation.events.fire({type: 'asset_error', element: this}); } }, handleLoadError: function(e) { console.log('Error loading model', this, e); this.state = 'error'; var errorgeo = new THREE.SphereGeometry(0.25); var error = new THREE.Mesh(errorgeo, new THREE.MeshBasicMaterial({color: 0xff0000, transparent: true, opacity: .5, transparent: true, opacity: .51})); this.fillGroup(this._model, error); this.instances.forEach(elation.bind(this, function(n) { if (!n.userData.loaded) { n.userData.loaded = true; //n.add(scene.clone()); this.fillGroup(n, error); elation.events.fire({type: 'asset_load', element: n}); } })); elation.events.fire({type: 'asset_error', element: this}); }, handleLoadProgress: function(progress) { //console.log('Model loading progress', this, progress.loaded, progress.total, progress); var progressdata = { src: progress.target.responseURL, loaded: progress.loaded, total: progress.total, }; this.size = (progress.total >= progress.loaded ? progress.total : progress.loaded); elation.events.fire({element: this, type: 'asset_load_progress', data: progressdata}); }, extractTextures: function(scene) { var types = ['map', 'bumpMap', 'lightMap', 'normalMap', 'specularMap', 'aoMap']; var textures = {}; var texturepromises = []; var minFilter = (this.tex_linear && this.tex_linear != 'false' ? THREE.LinearMipMapLinearFilter : THREE.NearestFilter); var magFilter = (this.tex_linear && this.tex_linear != 'false' ? THREE.LinearFilter : THREE.NearestFilter); scene.traverse(elation.bind(this, function(n) { if (n instanceof THREE.Mesh) { var materials = elation.utils.isArray(n.material) ? n.material : [n.material]; materials.forEach(elation.bind(this, function(material) { types.forEach(elation.bind(this, function(texname) { var tex = material[texname]; if (tex) { // && tex.image instanceof HTMLImageElement) { var img = tex.image; var src = img.originalSrc || img.src; if (!textures[src]) { //elation.engine.assets.loadJSON([{"assettype": "image", name: src, "src": src}], this.baseurl); //tex = elation.engine.assets.find('image', src); var asset = elation.engine.assets.find('image', src, true); if (!asset) { asset = elation.engine.assets.get({ assettype: 'image', name: src, src: src, hasalpha: (texname == 'map' ? null : false), // We only care about alpha channel for our diffuse map. (null means autodetect) baseurl: this.baseurl, flipy: tex.flipY, invert: (texname == 'specularMap') }); } if (!asset.loaded) { texturepromises.push(new Promise(elation.bind(this, function(resolve, reject) { elation.events.add(asset, 'asset_load_complete', resolve); elation.events.add(asset, 'asset_error', reject); }))); elation.events.fire({element: this, type: 'asset_load_dependency', data: asset}); } tex = asset.getInstance(); material[texname] = textures[src] = tex; } else { tex = material[texname] = textures[src]; } } })); })); } for (var k in textures) { var tex = textures[k]; if (tex) { //tex.minFilter = minFilter; //tex.magFilter = magFilter; } } })); if (texturepromises.length > 0) { var total = texturepromises.length, finished = 0; // Send the completed event when all textures this model references are loaded var completed = function() { if (++finished >= total) { elation.events.fire({element: this, type: 'asset_load_complete'}); } }; for (var i = 0; i < texturepromises.length; i++) { texturepromises[i].then(elation.bind(this, completed), elation.bind(this, completed)); } } else { setTimeout(elation.bind(this, function() { elation.events.fire({element: this, type: 'asset_load_complete'}); }), 0); } }, extractAnimations: function(scene) { var animations = []; if (!scene) scene = this._model; scene.traverse(function(n) { if (n.animations) { console.log('ANIMATIONS:', n); //animations[n.name] = n; animations.push.apply(animations, n.animations); } }); return animations; }, extractSkeleton: function(scene) { var skeleton = false; scene.traverse(function(n) { if (n.skeleton && !skeleton) { console.log('SKELETON:', n.skeleton); skeleton = n.skeleton; } }); return skeleton; }, handleProgress: function(ev) { //console.log('model progress!', ev); }, handleError: function(ev) { console.log('model uh oh!', ev); if (this.placeholder) { var placeholder = this.placeholder; var mat = new THREE.MeshPhongMaterial({color: 0x990000, emissive: 0x333333}); var errorholder = new THREE.Mesh(new THREE.SphereGeometry(1), mat); this.instances.forEach(function(n) { n.remove(placeholder); n.add(errorholder); }); } }, removePlaceholders: function() { if (this.placeholder) { var placeholder = this.placeholder; this.instances.forEach(function(n) { n.remove(placeholder); }); if (this._model) { this._model.remove(placeholder); } } }, stats: function(stats) { var obj = this._model; if (!stats) { stats = { objects: 0, faces: 0, materials: 0 }; } obj.traverse((n) => { if (n instanceof THREE.Mesh) { stats.objects++; var geo = n.geometry; if (geo instanceof THREE.BufferGeometry) { stats.faces += geo.attributes.position.count / 3; } else { stats.faces += geofaces.length; } if (n.material instanceof THREE.Material) { stats.materials++; } else if (elation.utils.isArray(n.material)) { stats.materials += n.material.length; } } }); return stats; } }, elation.engine.assets.base); elation.define('engine.assets.pack', { assettype: 'pack', src: false, json: false, assets: null, assetmap: null, init: function() { this.assets = []; this.assetmap = {}; this.load(); }, load: function() { elation.events.fire({element: this, type: 'asset_load_queued'}); if (this.json) { this.loadJSON(this.json); } else if (this.src) { var url = this.getFullURL(); this.loadURL(url); } }, loadURL: function(url) { console.log('load:', url); elation.net.get(url, null, { callback: elation.bind(this, function(data) { //console.log('got it', this, data); console.log('loaded:', url); this.loadJSON(JSON.parse(data)); }), }); }, loadJSON: function(json) { //this.json = json; elation.events.fire({element: this, type: 'asset_load_processing'}); var baseurl = (this.baseurl && this.baseurl.length > 0 ? this.baseurl : this.getBaseURL()); if (!this.assets) this.assets = []; for (var i = 0; i < json.length; i++) { var assetdef = json[i]; assetdef.baseurl = baseurl; var existing = elation.utils.arrayget(this.assetmap, assetdef.assettype + '.' + assetdef.name); //elation.engine.assets.find(assetdef.assettype, assetdef.name, true); if (!existing) { var asset = elation.engine.assets.get(assetdef); this.assets.push(asset); if (!this.assetmap[asset.assettype]) this.assetmap[asset.assettype] = {}; this.assetmap[asset.assettype][asset.name] = asset; } //asset.load(); } this.loaded = true; elation.events.fire({element: this, type: 'asset_load'}); }, get: function(type, name, create) { if (this.assetmap[type] && this.assetmap[type][name]) { return this.assetmap[type][name]; } if (create) { // If requested, create a new asset if it doesn't exist yet // FIXME - right now we're assuming the name is a url, which sometimes leads to 404s var assetargs = {assettype: type, name: name, src: name}; if (typeof create == 'object') { elation.utils.merge(create, assetargs); } this.loadJSON([assetargs]); return this.assetmap[type][name]; } return; }, _construct: function(args) { elation.engine.assets.base.call(this, args); if (!this.name) { this.name = this.getFullURL(); } } }, elation.engine.assets.base); elation.define('engine.assets.font', { assettype: 'font', src: false, _font: false, _construct: function(args) { elation.class.call(this, args); this.load(); }, load: function() { var loader = new THREE.FontLoader(); if (this.src) { loader.load(this.src, elation.bind(this, this.handleLoad), elation.bind(this, this.handleProgress), elation.bind(this, this.handleError)); } }, handleLoad: function(data) { this._font = data; }, getInstance: function(args) { if (!this._font) { this.load(); } return this._font; } }, elation.engine.assets.base); elation.define('engine.assets.labelgen', { assettype: 'label', text: '', canvas: false, font: 'sans-serif', fontSize: 64, color: '#ffffff', outline: 'rgba(0,0,0,0.5)', outlineSize: 1, aspect: 1, _texture: false, _construct: function(args) { elation.class.call(this, args); this.cache = {}; this.canvas = document.createElement('canvas'); this.ctx = this.canvas.getContext('2d'); this.load(); }, getNextPOT: function(x) { return Math.pow(2, Math.ceil(Math.log(x) / Math.log(2))); }, load: function() { }, getLabel: function(text) { if (!this.cache[text]) { var canvas = this.canvas, ctx = this.ctx; var fontSize = this.fontSize, color = this.color, outlineSize = this.outlineSize, outline = this.outline, font = this.font; ctx.font = fontSize + 'px ' + font; ctx.lineWidth = outlineSize + 'px '; ctx.strokeStyle = outline; var size = ctx.measureText(text); var w = size.width, h = fontSize; canvas.width = w; canvas.height = h; ctx.textBaseline = 'top'; ctx.font = fontSize + 'px ' + font; ctx.lineWidth = outlineSize + 'px '; ctx.strokeStyle = outline; ctx.fillStyle = 'rgba(0,0,0,0)'; ctx.fillRect(0, 0, w, h); ctx.fillStyle = color; this.aspect = size.width / fontSize; ctx.fillText(text, 0, 0); ctx.strokeText(text, 0, 0); var scaledcanvas = document.createElement('canvas'); var scaledctx = scaledcanvas.getContext('2d'); scaledcanvas.width = this.getNextPOT(w); scaledcanvas.height = this.getNextPOT(h); scaledctx.drawImage(canvas, 0, 0, scaledcanvas.width, scaledcanvas.height); this.cache[text] = new THREE.Texture(scaledcanvas); this.cache[text].needsUpdate = true; } return this.cache[text]; }, getAspectRatio: function(text) { var ctx = this.ctx, font = this.font, fontSize = this.fontSize; ctx.font = fontSize + 'px ' + font; var size = ctx.measureText(text); return size.width / fontSize; }, getInstance: function(args) { if (!this._texture) { this.load(); } return this._texture; } }, elation.engine.assets.base); /* assetpack = [ { name: 'grass-diffuse', 'assettype: 'image', src: '/textures/grass/diffuse.jpg' }, { name: 'grass-normal', 'assettype: 'image', src: '/textures/grass/normal.png' }, { name: 'grass', 'assettype: 'material', materialtype: 'phong', map: 'grass-diffuse', normalMap: 'grass-normal'}, { name: 'house', assettype: 'model', modeltype: 'collada', src: '/models/house.dae' }, { name: 'tree', assettype: 'model', modeltype: 'collada', src: '/models/tree.dae' } ] */ elation.define('engine.assets.script', { assettype: 'script', src: false, code: false, _construct: function(args) { elation.class.call(this, args); //this.load(); }, load: function() { this._script = document.createElement('script'); if (this.code) { setTimeout(elation.bind(this, function() { this.parse(this.code); }), 0); } else if (this.src) { var url = this.getProxiedURL(this.src); elation.engine.assetdownloader.fetchURL(url).then(ev => { let decoder = new TextDecoder('utf-8'); this.parse(decoder.decode(ev.target.response)); }); } }, parse: function(data) { //var blob = new Blob(['(function(window) {\n' + data + '\n})(self)'], {type: 'application/javascript'}); var blob = new Blob(['\n' + data + '\n'], {type: 'application/javascript'}); var bloburl = URL.createObjectURL(blob); this._script.src = bloburl; elation.events.fire({type: 'asset_load', element: this._script}); elation.events.fire({type: 'asset_load', element: this}); }, handleProgress: function(ev) { }, handleError: function(ev) { this._script = false; }, getInstance: function(args) { if (!this._script) { this.load(); } return this._script; } }, elation.engine.assets.base); elation.define('engine.assets.file', { assettype: 'file', src: false, content: false, load: function() { if (this.src) { var fullurl = this.getFullURL(this.src); if (!elation.engine.assetdownloader.isUrlInQueue(fullurl)) { elation.engine.assetdownloader.fetchURLs([fullurl], elation.bind(this, this.handleProgress)).then( elation.bind(this, function(events) { var xhr = events[0].target; var type = this.contenttype = xhr.getResponseHeader('content-type') this.state = 'processing'; elation.events.fire({element: this, type: 'asset_load_processing'}); this.content = xhr.response; elation.events.fire({element: this, type: 'asset_load'}); }), elation.bind(this, function(error) { this.state = 'error'; elation.events.fire({element: this, type: 'asset_error'}); }) ); elation.events.fire({element: this, type: 'asset_load_queued'}); } } }, getInstance: function(args) { if (!this.content) { this.load(); } return this.arrayToString(this.content); }, arrayToString: function(arr) { var str = ''; var bytes = new Uint8Array(arr); for (var i = 0; i < bytes.length; i++) { str += String.fromCharCode(bytes[i]); } return str; } }, elation.engine.assets.base); elation.define('engine.assets.shader', { assettype: 'shader', fragment_src: false, vertex_src: false, uniforms: {}, _construct: function(args) { elation.class.call(this, args); //this.load(); }, load: function() { this._material = new THREE.ShaderMaterial(); if (this.fragment_src || this.vertex_src) { if (this.fragment_src) { elation.engine.assetdownloader.fetchURL(this.getProxiedURL(this.fragment_src)).then(ev => { let decoder = new TextDecoder('utf-8'); this._material.fragmentShader = decoder.decode(ev.target.response); this._material.needsUpdate = true; }); } if (this.vertex_src) { elation.engine.assetdownloader.fetchURL(this.getProxiedURL(this.vertex_src)).then(ev => { let decoder = new TextDecoder('utf-8'); this._material.vertexShader = decoder.decode(ev.target.response); this._material.needsUpdate = true; }); } } if (this.uniforms) { this._material.uniforms = this.parseUniforms(this.uniforms); } this.complete(); }, complete: function(data) { elation.events.fire({type: 'asset_load', element: this._material}); elation.events.fire({type: 'asset_load', element: this}); elation.events.fire({element: this, type: 'asset_load_complete'}); }, parseUniforms(uniforms) { let matuniforms = {}; uniforms.forEach(u => { matuniforms[u.name] = { value: u.value }; }); return matuniforms; }, handleProgress: function(ev) { }, handleError: function(ev) { this._material = false; }, getInstance: function(args) { if (!this._material) { this.load(); } return this._material; } }, elation.engine.assets.base); });
scripts/assets.js
elation.require(['utils.workerpool', 'engine.external.three.three', 'engine.external.libgif'], function() { THREE.Cache.enabled = true; // TODO - submit pull request to add these to three.js THREE.SBSTexture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { THREE.Texture.call( this, image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); this.repeat.x = 0.5; } THREE.SBSTexture.prototype = Object.create( THREE.Texture.prototype ); THREE.SBSTexture.prototype.constructor = THREE.SBSTexture; THREE.SBSTexture.prototype.setEye = function(eye) { if (eye == 'left') { this.offset.x = (this.reverse ? 0.5 : 0); } else { this.offset.x = (this.reverse ? 0 : 0.5); } this.eye = eye; } THREE.SBSTexture.prototype.swap = function() { if (this.eye == 'right') { this.setEye('left'); } else { this.setEye('right'); } } THREE.SBSVideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { THREE.VideoTexture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); this.repeat.x = 0.5; this.reverse = false; } THREE.SBSVideoTexture.prototype = Object.create( THREE.SBSTexture.prototype ); THREE.SBSVideoTexture.prototype.constructor = THREE.SBSVideoTexture; THREE.SBSVideoTexture.prototype = Object.assign( Object.create( THREE.Texture.prototype ), { constructor: THREE.SBSVideoTexture, isVideoTexture: true, update: function () { var video = this.image; if ( video.readyState >= video.HAVE_CURRENT_DATA ) { this.needsUpdate = true; } }, setEye: function(eye) { if (eye == 'left') { this.offset.x = (this.reverse ? 0.5 : 0); } else { this.offset.x = (this.reverse ? 0 : 0.5); } this.eye = eye; } } ); elation.extend('engine.assets', { assets: {}, types: {}, corsproxy: '', placeholders: {}, init: function(dummy) { var corsproxy = elation.config.get('engine.assets.corsproxy', ''); //THREE.Loader.Handlers.add(/.*/i, corsproxy); //THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() ); if (corsproxy != '') { this.setCORSProxy(corsproxy, dummy); } }, loadAssetPack: function(url, baseurl) { this.assetroot = new elation.engine.assets.pack({name: url, src: url, baseurl: baseurl}); return this.assetroot; }, loadJSON: function(json, baseurl) { var assetpack = new elation.engine.assets.pack({name: "asdf", baseurl: baseurl, json: json}); return assetpack; }, get: function(asset) { if (!ENV_IS_BROWSER) return; var type = asset.assettype || 'base'; var assetclass = elation.engine.assets[type] || elation.engine.assets.unknown; var assetobj = new assetclass(asset); if (!elation.engine.assets.types[type]) elation.engine.assets.types[type] = {}; if (assetobj.name) { elation.engine.assets.assets[assetobj.name] = assetobj; elation.engine.assets.types[type][assetobj.name] = assetobj; } return assetobj; }, find: function(type, name, raw) { if (!ENV_IS_BROWSER) return; var asset; if (elation.engine.assets.types[type]) { asset = elation.engine.assets.types[type][name]; } //console.log(asset, type, name, elation.engine.assets.types[type]); if (raw) { return asset; } if (asset) { return asset.getInstance(); } else { asset = elation.engine.assets.get({assettype: type, name: name}); return asset.getInstance(); } return undefined; }, setCORSProxy: function(proxy, dummy) { elation.engine.assets.corsproxy = proxy; var loader = new elation.engine.assets.corsproxyloader(proxy, undefined, dummy); elation.engine.assetdownloader.setCORSProxy(proxy); THREE.Loader.Handlers.add(/.*/i, loader); if (!elation.env.isWorker && elation.engine.assets.loaderpool) { elation.engine.assets.loaderpool.sendMessage('setcorsproxy', proxy); } }, setPlaceholder: function(type, name) { this.placeholders[type] = this.find(type, name); }, loaderpool: false }); elation.extend('engine.assetdownloader', new function() { this.corsproxy = ''; this.queue = {}; this.setCORSProxy = function(proxy) { this.corsproxy = proxy; } this.isUrlInQueue = function(url) { var fullurl = url; if (this.corsproxy && fullurl.indexOf(this.corsproxy) != 0) fullurl = this.corsproxy + fullurl; return fullurl in this.queue; } this.fetchURLs = function(urls, progress) { var promises = [], queue = this.queue; for (var i = 0; i < urls.length; i++) { let subpromise = this.fetchURL(urls[i], progress); promises.push(subpromise); } return Promise.all(promises); } this.fetchURL = function(url, progress) { var corsproxy = this.corsproxy; let agent = this.getAgentForURL(url); return agent.fetch(url, progress); } this.getAgentForURL = function(url) { let urlparts = elation.utils.parseURL(url); let agentname = urlparts.scheme; // Check if we have a handler for this URL protocol, if we don't then fall back to the default 'xhr' agent if (!elation.engine.assetloader.agent[agentname]) { agentname = 'xhr'; } return elation.engine.assetloader.agent[agentname]; } }); elation.extend('engine.assetloader.agent.xhr', new function() { this.getFullURL = function(url) { } this.fetch = function(url, progress) { return new Promise(function(resolve, reject) { if (!this.queue) this.queue = {}; var fullurl = url; let corsproxy = elation.engine.assetdownloader.corsproxy; if (corsproxy && fullurl.indexOf(corsproxy) != 0 && fullurl.indexOf('blob:') != 0 && fullurl.indexOf('data:') != 0 && fullurl.indexOf(self.location.origin) != 0) { fullurl = corsproxy + fullurl; } if (!this.queue[fullurl]) { var xhr = this.queue[fullurl] = elation.net.get(fullurl, null, { responseType: 'arraybuffer', onload: (ev) => { delete this.queue[fullurl]; var status = ev.target.status; if (status == 200) { resolve(ev); } else { reject(); } }, onerror: () => { delete this.queue[fullurl]; reject(); }, onprogress: progress, headers: { 'X-Requested-With': 'Elation Engine asset loader' } }); } else { var xhr = this.queue[fullurl]; if (xhr.readyState == 4) { setTimeout(function() { resolve({target: xhr}); }, 0); } else { elation.events.add(xhr, 'load', resolve); elation.events.add(xhr, 'error', reject); elation.events.add(xhr, 'progress', progress); } } }); } }); elation.extend('engine.assetloader.agent.dat', new function() { this.fetch = function(url) { return new Promise((resolve, reject) => { if (typeof DatArchive == 'undefined') { console.warn('DatArchive not supported in this browser'); reject(); return; } let urlparts = elation.utils.parseURL(url); if (urlparts.host) { this.getArchive(urlparts.host).then(archive => { let path = urlparts.path; if (path[path.length-1] == '/') { path += 'index.html'; } archive.readFile(path, 'binary').then(file => { // FIXME - we're emulating an XHR object here, because the asset loader was initially written for XHR and uses some of the convenience functions resolve({ target: { responseURL: url, data: file, response: file, getResponseHeader(header) { if (header.toLowerCase() == 'content-type') { // FIXME - We should implement mime type detection at a lower level, and avoid the need to access the XHR object in calling code return 'application/octet-stream'; } } }, }); }); }); } }); } this.getArchive = function(daturl) { return new Promise((resolve, reject) => { if (!this.archives) this.archives = {}; if (this.archives[daturl]) { resolve(this.archives[daturl]); } else { DatArchive.load(daturl).then(archive => { this.archives[daturl] = archive; resolve(this.archives[daturl]); }); } }); } }); elation.extend('engine.assetcache', new function() { this.queued = []; this.open = function(name) { this.cachename = name; caches.open(name).then(elation.bind(this, this.setCache)); } this.setCache = function(cache) { this.cache = cache; // If we queued any cache lookups before the cache opened, resolve them return Promises.all(this.queued); } this.get = function(key) { if (this.cache) { return new Promise(elation.bind(function(resolve, reject) { var req = (key instanceof Request ? key : new Request(key)); this.cache.get(req).then(resolve); })); } else { // TODO - queue it! console.log('AssetCache warning: cache not open yet, cant get', key, this.cachename); } } this.set = function(key, value) { if (this.cache) { return new Promise(elation.bind(function(resolve, reject) { var req = (key instanceof Request ? key : new Request(key)); this.cache.get(req).then(resolve); })); } else { // TODO - queue it! console.log('AssetCache warning: cache not open yet, cant set', key, value, this.cachename); } } }); elation.define('engine.assets.corsproxyloader', { _construct: function(corsproxy, manager, dummy) { this.corsproxy = corsproxy || ''; this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; this.uuidmap = {}; this.dummy = dummy; }, load: function ( url, onLoad, onProgress, onError ) { var fullurl = url; if (this.corsproxy != '' && url.indexOf(this.corsproxy) != 0 && url.indexOf('blob:') != 0 && url.indexOf('data:') != 0 && url.indexOf(self.location.origin) != 0) { fullurl = this.corsproxy + url; } if (!this.dummy) { return THREE.TextureLoader.prototype.load.call(this, fullurl, onLoad, onProgress, onError); } return this.getDummyTexture(fullurl, onLoad); }, getDummyTexture: function(url, onLoad) { var texture = new THREE.Texture(); var uuid = this.uuidmap[url]; if (!uuid) { uuid = this.uuidmap[url] = THREE.Math.generateUUID(); } var img = { uuid: uuid, src: url, toDataURL: function() { return url; } }; texture.image = img; if (onLoad) { setTimeout(onLoad.bind(img, texture), 0); } return texture; } }, THREE.TextureLoader); elation.define('engine.assets.base', { assettype: 'base', name: '', description: '', license: 'unknown', author: 'unknown', sourceurl: false, size: false, loaded: false, preview: false, baseurl: '', src: false, proxy: true, preload: false, instances: [], _construct: function(args) { elation.class.call(this, args); this.init(); }, init: function() { this.instances = []; if (this.preload && this.preload !== 'false') { this.load(); } }, load: function() { console.log('engine.assets.base load() should not be called directly', this); }, isURLRelative: function(src) { if (src && src.match(/^(https?:)?\/\//) || src[0] == '/') { return false; } return true; }, isURLAbsolute: function(src) { return (src[0] == '/' && src[1] != '/'); }, isURLLocal: function(src) { if (this.isURLBlob(src) || this.isURLData(src)) { return true; } if (src.match(/^(https?:)?\/\//i)) { return (src.indexOf(self.location.origin) == 0); } return ( (src[0] == '/' && src[1] != '/') || (src[0] != '/') ); }, isURLData: function(url) { if (!url) return false; return url.indexOf('data:') == 0; }, isURLBlob: function(url) { if (!url) return false; return url.indexOf('blob:') == 0; }, isURLProxied: function(url) { if (!url || !elation.engine.assets.corsproxy) return false; return url.indexOf(elation.engine.assets.corsproxy) == 0; }, getFullURL: function(url, baseurl) { if (!url) url = this.src; if (!baseurl) baseurl = this.baseurl; var fullurl = url; if (!this.isURLBlob(fullurl) && !this.isURLData(fullurl)) { if (this.isURLRelative(fullurl)) { fullurl = baseurl + fullurl; } else if (this.isURLProxied(fullurl)) { fullurl = fullurl.replace(elation.engine.assets.corsproxy, ''); } else if (this.isURLAbsolute(fullurl)) { fullurl = self.location.origin + fullurl; } } return fullurl; }, getProxiedURL: function(url, baseurl) { var proxiedurl = this.getFullURL(url, baseurl); if (this.proxy && this.proxy != 'false' && proxiedurl && elation.engine.assets.corsproxy && !this.isURLLocal(proxiedurl) && proxiedurl.indexOf(elation.engine.assets.corsproxy) == -1) { var re = /:\/\/([^\/\@]+@)/; var m = proxiedurl.match(re); // Check it asset has authentication info, and pass it through if it does if (m) { proxiedurl = elation.engine.assets.corsproxy.replace(':\/\/', ':\/\/' + m[1]) + proxiedurl.replace(m[1], ''); } else { proxiedurl = elation.engine.assets.corsproxy + proxiedurl; } } return proxiedurl; }, getBaseURL: function(url) { var url = url || this.getFullURL(); var parts = url.split('/'); parts.pop(); return parts.join('/') + '/'; }, getInstance: function(args) { return undefined; }, executeWhenLoaded: function(callback) { if (this.loaded) { // We've already loaded the asset, so execute the callback asynchronously setTimeout(callback, 0); } else { // Asset isn't loaded yet, set up a local callback that can self-remove, so our callback only executes once let cb = (ev) => { elation.events.remove(this, 'asset_load', cb); callback(); }; elation.events.add(this, 'asset_load', cb); } } }, elation.class); elation.define('engine.assets.unknown', { assettype: 'unknown', load: function() { }, _construct: function(args) { console.log('Unknown asset type: ', args.assettype, args); elation.engine.assets.base.call(this, args); } }, elation.engine.assets.base); elation.define('engine.assets.image', { assettype: 'image', src: false, canvas: false, sbs3d: false, ou3d: false, reverse3d: false, texture: false, frames: false, flipy: true, invert: false, imagetype: '', tex_linear: true, hasalpha: null, rawimage: null, preload: true, maxsize: null, load: function() { if (this.texture) { this._texture = this.texture; } else if (this.src) { var fullurl = this.getFullURL(this.src); var texture; if (this.sbs3d) { texture = this._texture = new THREE.SBSTexture(); texture.reverse = this.reverse3d; } else { texture = this._texture = new THREE.Texture(); } texture.image = this.canvas = this.getCanvas(); texture.image.originalSrc = this.src; texture.sourceFile = this.src; texture.needsUpdate = true; texture.flipY = (this.flipy === true || this.flipy === 'true'); if (this.isURLData(fullurl)) { this.loadImageByURL(); } else { elation.engine.assetdownloader.fetchURLs([fullurl], elation.bind(this, this.handleProgress)).then( elation.bind(this, function(events) { var xhr = events[0].target; var type = this.contenttype = xhr.getResponseHeader('content-type') if (typeof createImageBitmap == 'function' && type != 'image/gif') { var blob = new Blob([xhr.response], {type: type}); createImageBitmap(blob).then(elation.bind(this, this.handleLoad), elation.bind(this, this.handleBitmapError)); } else { this.loadImageByURL(); } this.state = 'processing'; elation.events.fire({element: this, type: 'asset_load_processing'}); }), elation.bind(this, function(error) { this.state = 'error'; elation.events.fire({element: this, type: 'asset_error'}); }) ); elation.events.fire({element: this, type: 'asset_load_queued'}); } } else if (this.canvas) { var texture = this._texture = new THREE.Texture(); texture.image = this.canvas; texture.image.originalSrc = ''; texture.sourceFile = ''; texture.needsUpdate = true; texture.flipY = this.flipy; elation.events.add(this.canvas, 'update', () => texture.needsUpdate = true); this.sendLoadEvents(); } }, loadImageByURL: function() { var proxiedurl = this.getProxiedURL(this.src); var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' ); elation.events.add(image, 'load', elation.bind(this, this.handleLoad, image)); elation.events.add(image, 'error', elation.bind(this, this.handleError)); image.crossOrigin = 'anonymous'; image.src = proxiedurl; return image; }, getCanvas: function() { if (!this.canvas) { var canvas = document.createElement('canvas'); var size = 32, gridcount = 4, gridsize = size / gridcount; canvas.width = size; canvas.height = size; var ctx = canvas.getContext('2d'); ctx.fillStyle = '#cccccc'; ctx.fillRect(0,0,size,size); ctx.fillStyle = '#666666'; for (var i = 0; i < gridcount*gridcount; i += 1) { var x = i % gridcount; var y = Math.floor(i / gridcount); if ((x + y) % 2 == 0) { ctx.fillRect(x * gridsize, y * gridsize, gridsize, gridsize); } } this.canvas = canvas; } return this.canvas; }, handleLoad: function(image) { //console.log('loaded image', this, image); this.rawimage = image; var texture = this._texture; texture.image = this.processImage(image); texture.needsUpdate = true; texture.wrapS = texture.wrapT = THREE.RepeatWrapping; texture.anisotropy = elation.config.get('engine.assets.image.anisotropy', 4); this.loaded = true; this.uploaded = false; this.sendLoadEvents(); }, sendLoadEvents: function() { elation.events.fire({type: 'asset_load', element: this._texture}); elation.events.fire({type: 'asset_load', element: this}); elation.events.fire({element: this, type: 'asset_load_complete'}); }, handleProgress: function(ev) { var progress = { src: ev.target.responseURL, loaded: ev.loaded, total: ev.total }; this.size = ev.total; //console.log('image progress', progress); elation.events.fire({element: this, type: 'asset_load_progress', data: progress}); }, handleBitmapError: function(src, ev) { console.log('Error loading image via createImageBitmap, fall back on normal image'); this.loadImageByURL(); }, handleError: function(ev) { console.log('image error!', this, this._texture.image, ev); var canvas = this.getCanvas(); var size = 16; canvas.width = canvas.height = size; var ctx = canvas.getContext('2d'); ctx.fillStyle = '#f0f'; ctx.fillRect(0,0,size,size); this._texture.image = canvas; this._texture.needsUpdate = true; this._texture.generateMipmaps = false; elation.events.fire({type: 'asset_error', element: this._texture}); }, getInstance: function(args) { if (!this._texture) { this.load(); } return this._texture; }, processImage: function(image) { this.imagetype = this.detectImageType(); if (this.imagetype == 'gif') { this.hasalpha = true; // FIXME - if we're cracking the gif open already, we should be able to tell if it has alpha or not return this.convertGif(image); } else { //if (!elation.engine.materials.isPowerOfTwo(image.width) || !elation.engine.materials.isPowerOfTwo(image.height)) { // Scale up the texture to the next highest power of two dimensions. var canvas = this.canvas; canvas.src = this.src; canvas.originalSrc = this.src; var imagemax = elation.utils.any(this.maxsize, elation.config.get('engine.assets.image.maxsize', Infinity)); canvas.width = Math.min(imagemax, this.nextHighestPowerOfTwo(image.width)); canvas.height = Math.min(imagemax, this.nextHighestPowerOfTwo(image.height)); var ctx = canvas.getContext("2d"); ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height); if (this.hasalpha === null) { if (!this.src.match(/\.jpg$/i)) { this.hasalpha = this.canvasHasAlpha(canvas); } else { this.hasalpha = false; } } this._texture.generateMipmaps = elation.config.get('engine.assets.image.mipmaps', true); if (this.invert) { this.invertImage(canvas); } return canvas; //} else { // return image; } }, convertGif: function(image) { var gif = new SuperGif({gif: image, draw_while_loading: true, loop_mode: false, auto_play: false}); // Decode gif frames into a series of canvases, then swap between canvases to animate the texture // This could be made more efficient by uploading each frame to the GPU as a separate texture, and // swapping the texture handle each frame instead of re-uploading the frame. This is hard to do // with the way Three.js handles Texture objects, but it might be possible to fiddle with // renderer.properties[texture].__webglTexture directly // It could also be made more efficient by moving the gif decoding into a worker, and just passing // back messages with decoded frame data. var getCanvas = () => { var newcanvas = document.createElement('canvas'); newcanvas.width = this.nextHighestPowerOfTwo(image.width); newcanvas.height = this.nextHighestPowerOfTwo(image.height); return newcanvas; } var newcanvas = getCanvas(); var mainctx = newcanvas.getContext('2d'); var texture = this._texture; texture.minFilter = THREE.NearestFilter; texture.magFilter = THREE.NearestFilter; //texture.generateMipmaps = false; var frames = []; var frametextures = this.frames = []; var framedelays = []; var framenum = -1; var lastframe = texture; gif.load(function() { var canvas = gif.get_canvas(); var doGIFFrame = function(isstatic) { framenum = (framenum + 1) % gif.get_length(); var frame = frames[framenum]; if (!frame) { gif.move_to(framenum); var gifframe = gif.get_frame(framenum); if (gifframe) { frame = frames[framenum] = { framenum: framenum, delay: gifframe.delay, image: getCanvas() }; ctx = frame.image.getContext('2d'); newcanvas.width = canvas.width; newcanvas.height = canvas.height; //mainctx.putImageData(gifframe.data, 0, 0, 0, 0, canvas.width, canvas.height); ctx.drawImage(canvas, 0, 0, canvas.width, canvas.height, 0, 0, frame.image.width, frame.image.height); texture.minFilter = texture.magFilter = THREE.NearestFilter; // FIXME - should this be hardcoded for all gifs? frametextures[framenum] = new THREE.Texture(frame.image); frametextures[framenum].minFilter = frametextures[framenum].magFilter = THREE.NearestFilter; // FIXME - should this be hardcoded for all gifs? frametextures[framenum].wrapS = frametextures[framenum].wrapT = THREE.RepeatWrapping; frametextures[framenum].needsUpdate = true; } } if (frame && frame.image) { /* texture.image = frame.image; texture.needsUpdate = true; elation.events.fire({type: 'update', element: texture}); */ var frametex = frametextures[framenum] || lastframe; if (frametex !== lastframe) { lastframe = frametex; } elation.events.fire({element: texture, type: 'asset_update', data: frametex}); } if (!isstatic) { var delay = (frame && frame.delay > 0 ? frame.delay : 10); setTimeout(doGIFFrame, delay * 10); } } doGIFFrame(gif.get_length() == 1); }); return newcanvas; }, detectImageType: function() { // FIXME - really we should be cracking open the file and looking at magic number to determine this // We might also be able to get hints from the XHR loader about the image's MIME type var type = 'jpg'; if (this.contenttype) { var map = { 'image/jpeg': 'jpg', 'image/png': 'png', 'image/gif': 'gif', }; type = map[this.contenttype]; } else if (this.src.match(/\.(.*?)$/)) { var parts = this.src.split('.'); type = parts.pop(); } return type; }, canvasHasAlpha: function(canvas) { if (!(this.imagetype == 'gif' || this.imagetype == 'png')) { return false; } // This could be made more efficient by doing the work on the gpu. We could make a scene with the // texture and an orthographic camera, and a shader which returns alpha=0 for any alpha value < 1 // We could then perform a series of downsamples until the texture is (1,1) in size, and read back // that pixel value with readPixels(). If there was any alpha in the original image, this final // pixel should also be transparent. var width = Math.min(64, canvas.width), height = Math.min(64, canvas.height); if (!this._scratchcanvas) { this._scratchcanvas = document.createElement('canvas'); this._scratchcanvasctx = this._scratchcanvas.getContext('2d'); } var checkcanvas = this._scratchcanvas, ctx = this._scratchcanvasctx; checkcanvas.width = width; checkcanvas.height = height; ctx.drawImage(canvas, 0, 0, canvas.width, canvas.height, 0, 0, width, height); var pixeldata = ctx.getImageData(0, 0, width, height); var hasalpha = false; for (var i = 0; i < pixeldata.data.length; i+=4) { if (pixeldata.data[i+3] != 255) { return true; } } return false; }, invertImage: function(canvas) { var ctx = canvas.getContext('2d'); var pixeldata = ctx.getImageData(0, 0, canvas.width, canvas.height); for (var i = 0; i < pixeldata.data.length; i+=4) { pixeldata.data[i] = 255 - pixeldata.data[i]; pixeldata.data[i+1] = 255 - pixeldata.data[i+1]; pixeldata.data[i+2] = 255 - pixeldata.data[i+2]; } ctx.putImageData(pixeldata, 0, 0); }, nextHighestPowerOfTwo: function(num) { num--; for (var i = 1; i < 32; i <<= 1) { num = num | num >> i; } return num + 1; } }, elation.engine.assets.base); elation.define('engine.assets.video', { assettype: 'video', src: false, sbs3d: false, ou3d: false, reverse3d: false, auto_play: false, texture: false, load: function() { var url = this.getProxiedURL(this.src); var video = document.createElement('video'); video.muted = false; video.src = url; video.crossOrigin = 'anonymous'; this._video = video; if (this.sbs3d) { this._texture = new THREE.SBSVideoTexture(video); this._texture.reverse = this.reverse3d; } else { this._texture = new THREE.VideoTexture(video); } this._texture.minFilter = THREE.LinearFilter; elation.events.add(video, 'loadeddata', elation.bind(this, this.handleLoad)); elation.events.add(video, 'error', elation.bind(this, this.handleError)); if (this.auto_play) { // FIXME - binding for easy event removal later. This should happen at a lower level this.handleAutoplayStart = elation.bind(this, this.handleAutoplayStart); // Bind on next tick to avoid time-ou firing prematurely due to load-time lag setTimeout(elation.bind(this, function() { elation.events.add(video, 'playing', this.handleAutoplayStart); this._autoplaytimeout = setTimeout(elation.bind(this, this.handleAutoplayTimeout), 1000); }), 0); var promise = video.play(); if (promise) { promise.then(elation.bind(this, function() { this.handleAutoplayStart(); })).catch(elation.bind(this, function(err) { // If autoplay failed, retry with muted video var strerr = err.toString(); if (strerr.indexOf('NotAllowedError') == 0) { video.muted = true; video.play().catch(elation.bind(this, this.handleAutoplayError)); } else if (strerr.indexOf('NotSupportedError') == 0) { this.initHLS(); } })); } } }, handleLoad: function() { this.loaded = true; elation.events.fire({element: this, type: 'asset_load'}); elation.events.fire({element: this, type: 'asset_load_complete'}); }, handleProgress: function(ev) { //console.log('image progress!', ev); var progress = { src: ev.target.responseURL, loaded: ev.loaded, total: ev.total }; this.size = ev.total; elation.events.fire({element: this, type: 'asset_load_progress', data: progress}); }, handleError: function(ev) { //console.log('video uh oh!', ev); //this._texture = false; //console.log('Video failed to load, try HLS'); }, handleAutoplayStart: function(ev) { if (this._autoplaytimeout) { clearTimeout(this._autoplaytimeout); } elation.events.remove(this._video, 'playing', this.handleAutoplayStart); elation.events.fire({element: this._texture, type: 'autoplaystart'}); }, handleAutoplayTimeout: function(ev) { elation.events.fire({element: this._texture, type: 'autoplaytimeout'}); }, handleAutoplayFail: function(ev) { elation.events.fire({element: this._texture, type: 'autoplayfail'}); }, getInstance: function(args) { if (!this._texture) { this.load(); } return this._texture; }, initHLS: function() { if (typeof Hls != 'function') { elation.file.get('js', 'https://cdn.jsdelivr.net/npm/hls.js@latest', elation.bind(this, this.initHLS)); return; } var hls = new Hls(); hls.loadSource(this.getProxiedURL()); hls.attachMedia(this._video); if (this.auto_play) { var video = this._video; hls.on(Hls.Events.MANIFEST_PARSED, function() { video.play(); }); } } }, elation.engine.assets.base); elation.define('engine.assets.material', { assettype: 'material', color: null, map: null, normalMap: null, specularMap: null, load: function() { var matargs = {}; if (this.color) matargs.color = new THREE.Color(this.color); if (this.map) matargs.map = elation.engine.assets.find('image', this.map); if (this.normalMap) matargs.normalMap = elation.engine.assets.find('image', this.normalMap); if (this.specularMap) matargs.specularMap = elation.engine.assets.find('image', this.normalMap); this._material = new THREE.MeshPhongMaterial(matargs); console.log('new material!', this._material); }, getInstance: function(args) { if (!this._material) { this.load(); } return this._material; }, handleLoad: function(data) { console.log('loaded image', data); this._texture = data; }, handleProgress: function(ev) { }, handleError: function(ev) { console.log('image uh oh!', ev); this._texture = false; } }, elation.engine.assets.base); elation.define('engine.assets.sound', { assettype: 'sound', src: false, load: function() { if (this.src) { //this._sound = new THREE.Audio(this.src); } }, handleLoad: function(data) { console.log('loaded sound', data); this._sound = data; this.loaded = true; }, handleProgress: function(ev) { console.log('sound progress!', ev); this.size = ev.total; }, handleError: function(ev) { console.log('sound uh oh!', ev); this._sound = false; }, getInstance: function(args) { return this; /* if (!this._sound) { this.load(); } return this._sound; */ } }, elation.engine.assets.base); elation.define('engine.assets.model', { assettype: 'model', src: false, mtl: false, tex: false, tex0: false, tex1: false, tex2: false, tex3: false, tex_linear: true, color: false, modeltype: '', compression: 'none', object: false, loadworkers: [ ], getInstance: function(args) { var group = new THREE.Group(); if (!this._model) { if (!this.loading) { this.load(); } var mesh; if (elation.engine.assets.placeholders.model) { mesh = elation.engine.assets.placeholders.model.clone(); } else { mesh = this.createPlaceholder(); } group.add(mesh); } else { //group.add(this._model.clone()); this.fillGroup(group, this._model); //group = this._model.clone(); this.assignTextures(group, args); setTimeout(function() { elation.events.fire({type: 'asset_load', element: group}); elation.events.fire({type: 'asset_load', element: this}); }, 0); } this.instances.push(group); return group; }, fillGroup: function(group, source) { if (!source) source = this._model; if (source) { /* group.position.copy(source.position); group.quaternion.copy(source.quaternion); //group.scale.copy(source.scale); if (source.children) { source.children.forEach(function(n) { group.add(n.clone()); }); } */ var newguy = source.clone(); group.add(newguy); newguy.updateMatrix(true); newguy.updateMatrixWorld(true); newguy.traverse(function(n) { if (n instanceof THREE.SkinnedMesh) { //n.rebindByName(newguy); } }); } return group; }, copyMaterial: function(oldmat) { var m = new THREE.MeshPhongMaterial(); m.anisotropy = elation.config.get('engine.assets.image.anisotropy', 4); m.name = oldmat.name; m.map = oldmat.map; m.normalMap = oldmat.normalMap; m.lightMap = oldmat.lightMap; m.color.copy(oldmat.color); m.transparent = oldmat.transparent; m.alphaTest = oldmat.alphaTest; return m; }, assignTextures: function(group, args) { var minFilter = (this.tex_linear && this.tex_linear != 'false' ? THREE.LinearMipMapLinearFilter : THREE.NearestFilter); var magFilter = (this.tex_linear && this.tex_linear != 'false' ? THREE.LinearFilter : THREE.NearestFilter); if (this.tex) this.tex0 = this.tex; if (this.tex0) { var tex0 = elation.engine.assets.find('image', this.tex0); if (!tex0) { var asset = elation.engine.assets.get({ assettype: 'image', name: this.tex0, src: this.tex0, baseurl: this.baseurl }); tex0 = asset.getInstance(); } } group.traverse(function(n) { if (n.material) { var materials = (elation.utils.isArray(n.material) ? n.material : [n.material]); materials.forEach(function(m) { if (tex0) { //m.transparent = true; m.alphaTest = 0.1; m.map = tex0; } if (m.map) { m.map.minFilter = minFilter; m.map.magFilter = magFilter; } m.needsUpdate = true; //if (m.color) m.color.setHex(0xffffff); }); } }); }, createPlaceholder: function() { /* var geo = new THREE.TextGeometry('loading...', { size: 1, height: .1, font: 'helvetiker' }); var font = elation.engine.assets.find('font', 'helvetiker'); var geo = new THREE.TextGeometry( 'loading...', { size: 1, height: 0.1, font: font, }); */ /* var geo = new THREE.SphereGeometry(0.25); //geo.applyMatrix(new THREE.Matrix4().makeScale(1,1,.1)); var mat = new THREE.MeshPhongMaterial({color: 0x999900, emissive: 0x333333, opacity: 0.5, transparent: true}); this.placeholder = new THREE.Mesh(geo, mat); */ this.placeholder = new THREE.Object3D(); return this.placeholder; }, load: function() { if (this.object) { this.loading = false; this.loaded = true; this.state = 'complete'; this._model = new THREE.Group(); setTimeout(() => this.complete(this.object), 0); } else if (this.src) { this.loading = true; this.loaded = false; this.state = 'loading'; var loadargs = {src: this.getFullURL()}; if (this.mtl) loadargs.mtl = this.getFullURL(this.mtl, this.getBaseURL(loadargs.src)); this.queueForDownload(loadargs); } else { this.removePlaceholders(); } }, detectType: function(url) { var parts = url.split('.'); var extension = parts.pop(); if (extension == 'gz') { extension = parts.pop(); this.extension = extension; this.compression = 'gzip'; } return extension.toLowerCase(); }, queueForDownload: function(jobdata) { var urls = [jobdata.src]; if (jobdata.mtl) urls.push(jobdata.mtl); this.state = 'queued'; var progressfunc = elation.bind(this, function(progress) { if (this.state == 'queued') { this.state = 'downloading'; elation.events.fire({element: this, type: 'asset_load_start'}); } this.handleLoadProgress(progress); }); elation.engine.assetdownloader.fetchURLs(urls, progressfunc).then( elation.bind(this, function(events) { var files = []; events.forEach(function(ev) { var url = ev.target.responseURL, data = ev.target.response; if (url == jobdata.src) { jobdata.srcdata = data; } else if (url == jobdata.mtl) { jobdata.mtldata = data; } }); this.state = 'processing'; this.loadWithWorker(jobdata); elation.events.fire({element: this, type: 'asset_load_processing'}); }), elation.bind(this, function(error) { this.state = 'error'; elation.events.fire({element: this, type: 'asset_error'}); }) ); elation.events.fire({element: this, type: 'asset_load_queued'}); }, loadWithWorker: function(jobdata) { this._model = new THREE.Group(); this._model.userData.loaded = false; if (!elation.engine.assets.loaderpool) { var numworkers = elation.config.get('engine.assets.workers', 'auto'); // default to 'auto' unless otherwise specified if (numworkers == 'auto') { // 'auto' means use all cores, minus one for the main thread let numcores = navigator.hardwareConcurrency || 2; // Safari returns NaN for navigator.hardwareConcurrency unless you enable a dev flag. Fall back 2 cores, which is what iOS would cap this value at anyway numworkers = Math.max(1, numcores - 1); // We need at least one worker, even on single-core systems } elation.engine.assets.loaderpool = new elation.utils.workerpool({component: 'engine.assetworker', scriptsuffix: 'assetworker', num: numworkers}); } elation.engine.assets.loaderpool.addJob(jobdata) .then( elation.bind(this, this.handleLoadJSON), elation.bind(this, this.handleLoadError) //elation.bind(this, this.handleLoadProgress) ); }, complete: function(object) { this.removePlaceholders(); this._model.userData.loaded = true; //this._model.add(scene); this.fillGroup(this._model, object); this.extractTextures(object); //this.assignTextures(scene); this.instances.forEach(elation.bind(this, function(n) { if (!n.userData.loaded) { n.userData.loaded = true; //n.add(scene.clone()); this.fillGroup(n, object); //this.assignTextures(n); elation.events.fire({type: 'asset_load', element: n}); //elation.events.fire({type: 'asset_load_complete', element: this}); } })); this.state = 'complete'; elation.events.fire({element: this, type: 'asset_load_processed'}); elation.events.fire({type: 'asset_load', element: this}); }, handleLoadJSON: function(json) { if (json) { this.loaded = true; var parser = new THREE.ObjectLoader(); parser.setCrossOrigin('anonymous'); var scene = parser.parse(json); this.complete(scene); } else { // no model data, error! elation.events.fire({type: 'asset_error', element: this}); } }, handleLoadError: function(e) { console.log('Error loading model', this, e); this.state = 'error'; var errorgeo = new THREE.SphereGeometry(0.25); var error = new THREE.Mesh(errorgeo, new THREE.MeshBasicMaterial({color: 0xff0000, transparent: true, opacity: .5, transparent: true, opacity: .51})); this.fillGroup(this._model, error); this.instances.forEach(elation.bind(this, function(n) { if (!n.userData.loaded) { n.userData.loaded = true; //n.add(scene.clone()); this.fillGroup(n, error); elation.events.fire({type: 'asset_load', element: n}); } })); elation.events.fire({type: 'asset_error', element: this}); }, handleLoadProgress: function(progress) { //console.log('Model loading progress', this, progress.loaded, progress.total, progress); var progressdata = { src: progress.target.responseURL, loaded: progress.loaded, total: progress.total, }; this.size = (progress.total >= progress.loaded ? progress.total : progress.loaded); elation.events.fire({element: this, type: 'asset_load_progress', data: progressdata}); }, extractTextures: function(scene) { var types = ['map', 'bumpMap', 'lightMap', 'normalMap', 'specularMap', 'aoMap']; var textures = {}; var texturepromises = []; var minFilter = (this.tex_linear && this.tex_linear != 'false' ? THREE.LinearMipMapLinearFilter : THREE.NearestFilter); var magFilter = (this.tex_linear && this.tex_linear != 'false' ? THREE.LinearFilter : THREE.NearestFilter); scene.traverse(elation.bind(this, function(n) { if (n instanceof THREE.Mesh) { var materials = elation.utils.isArray(n.material) ? n.material : [n.material]; materials.forEach(elation.bind(this, function(material) { types.forEach(elation.bind(this, function(texname) { var tex = material[texname]; if (tex) { // && tex.image instanceof HTMLImageElement) { var img = tex.image; var src = img.originalSrc || img.src; if (!textures[src]) { //elation.engine.assets.loadJSON([{"assettype": "image", name: src, "src": src}], this.baseurl); //tex = elation.engine.assets.find('image', src); var asset = elation.engine.assets.find('image', src, true); if (!asset) { asset = elation.engine.assets.get({ assettype: 'image', name: src, src: src, hasalpha: (texname == 'map' ? null : false), // We only care about alpha channel for our diffuse map. (null means autodetect) baseurl: this.baseurl, flipy: tex.flipY, invert: (texname == 'specularMap') }); } if (!asset.loaded) { texturepromises.push(new Promise(elation.bind(this, function(resolve, reject) { elation.events.add(asset, 'asset_load_complete', resolve); elation.events.add(asset, 'asset_error', reject); }))); elation.events.fire({element: this, type: 'asset_load_dependency', data: asset}); } tex = asset.getInstance(); material[texname] = textures[src] = tex; } else { tex = material[texname] = textures[src]; } } })); })); } for (var k in textures) { var tex = textures[k]; if (tex) { //tex.minFilter = minFilter; //tex.magFilter = magFilter; } } })); if (texturepromises.length > 0) { var total = texturepromises.length, finished = 0; // Send the completed event when all textures this model references are loaded var completed = function() { if (++finished >= total) { elation.events.fire({element: this, type: 'asset_load_complete'}); } }; for (var i = 0; i < texturepromises.length; i++) { texturepromises[i].then(elation.bind(this, completed), elation.bind(this, completed)); } } else { setTimeout(elation.bind(this, function() { elation.events.fire({element: this, type: 'asset_load_complete'}); }), 0); } }, extractAnimations: function(scene) { var animations = []; if (!scene) scene = this._model; scene.traverse(function(n) { if (n.animations) { console.log('ANIMATIONS:', n); //animations[n.name] = n; animations.push.apply(animations, n.animations); } }); return animations; }, extractSkeleton: function(scene) { var skeleton = false; scene.traverse(function(n) { if (n.skeleton && !skeleton) { console.log('SKELETON:', n.skeleton); skeleton = n.skeleton; } }); return skeleton; }, handleProgress: function(ev) { //console.log('model progress!', ev); }, handleError: function(ev) { console.log('model uh oh!', ev); if (this.placeholder) { var placeholder = this.placeholder; var mat = new THREE.MeshPhongMaterial({color: 0x990000, emissive: 0x333333}); var errorholder = new THREE.Mesh(new THREE.SphereGeometry(1), mat); this.instances.forEach(function(n) { n.remove(placeholder); n.add(errorholder); }); } }, removePlaceholders: function() { if (this.placeholder) { var placeholder = this.placeholder; this.instances.forEach(function(n) { n.remove(placeholder); }); if (this._model) { this._model.remove(placeholder); } } }, stats: function(stats) { var obj = this._model; if (!stats) { stats = { objects: 0, faces: 0, materials: 0 }; } obj.traverse((n) => { if (n instanceof THREE.Mesh) { stats.objects++; var geo = n.geometry; if (geo instanceof THREE.BufferGeometry) { stats.faces += geo.attributes.position.count / 3; } else { stats.faces += geofaces.length; } if (n.material instanceof THREE.Material) { stats.materials++; } else if (elation.utils.isArray(n.material)) { stats.materials += n.material.length; } } }); return stats; } }, elation.engine.assets.base); elation.define('engine.assets.pack', { assettype: 'pack', src: false, json: false, assets: null, assetmap: null, init: function() { this.assets = []; this.assetmap = {}; this.load(); }, load: function() { elation.events.fire({element: this, type: 'asset_load_queued'}); if (this.json) { this.loadJSON(this.json); } else if (this.src) { var url = this.getFullURL(); this.loadURL(url); } }, loadURL: function(url) { console.log('load:', url); elation.net.get(url, null, { callback: elation.bind(this, function(data) { //console.log('got it', this, data); console.log('loaded:', url); this.loadJSON(JSON.parse(data)); }), }); }, loadJSON: function(json) { //this.json = json; elation.events.fire({element: this, type: 'asset_load_processing'}); var baseurl = (this.baseurl && this.baseurl.length > 0 ? this.baseurl : this.getBaseURL()); if (!this.assets) this.assets = []; for (var i = 0; i < json.length; i++) { var assetdef = json[i]; assetdef.baseurl = baseurl; var existing = elation.utils.arrayget(this.assetmap, assetdef.assettype + '.' + assetdef.name); //elation.engine.assets.find(assetdef.assettype, assetdef.name, true); if (!existing) { var asset = elation.engine.assets.get(assetdef); this.assets.push(asset); if (!this.assetmap[asset.assettype]) this.assetmap[asset.assettype] = {}; this.assetmap[asset.assettype][asset.name] = asset; } //asset.load(); } this.loaded = true; elation.events.fire({element: this, type: 'asset_load'}); }, get: function(type, name, create) { if (this.assetmap[type] && this.assetmap[type][name]) { return this.assetmap[type][name]; } if (create) { // If requested, create a new asset if it doesn't exist yet // FIXME - right now we're assuming the name is a url, which sometimes leads to 404s var assetargs = {assettype: type, name: name, src: name}; if (typeof create == 'object') { elation.utils.merge(create, assetargs); } this.loadJSON([assetargs]); return this.assetmap[type][name]; } return; }, _construct: function(args) { elation.engine.assets.base.call(this, args); if (!this.name) { this.name = this.getFullURL(); } } }, elation.engine.assets.base); elation.define('engine.assets.font', { assettype: 'font', src: false, _font: false, _construct: function(args) { elation.class.call(this, args); this.load(); }, load: function() { var loader = new THREE.FontLoader(); if (this.src) { loader.load(this.src, elation.bind(this, this.handleLoad), elation.bind(this, this.handleProgress), elation.bind(this, this.handleError)); } }, handleLoad: function(data) { this._font = data; }, getInstance: function(args) { if (!this._font) { this.load(); } return this._font; } }, elation.engine.assets.base); elation.define('engine.assets.labelgen', { assettype: 'label', text: '', canvas: false, font: 'sans-serif', fontSize: 64, color: '#ffffff', outline: 'rgba(0,0,0,0.5)', outlineSize: 1, aspect: 1, _texture: false, _construct: function(args) { elation.class.call(this, args); this.cache = {}; this.canvas = document.createElement('canvas'); this.ctx = this.canvas.getContext('2d'); this.load(); }, getNextPOT: function(x) { return Math.pow(2, Math.ceil(Math.log(x) / Math.log(2))); }, load: function() { }, getLabel: function(text) { if (!this.cache[text]) { var canvas = this.canvas, ctx = this.ctx; var fontSize = this.fontSize, color = this.color, outlineSize = this.outlineSize, outline = this.outline, font = this.font; ctx.font = fontSize + 'px ' + font; ctx.lineWidth = outlineSize + 'px '; ctx.strokeStyle = outline; var size = ctx.measureText(text); var w = size.width, h = fontSize; canvas.width = w; canvas.height = h; ctx.textBaseline = 'top'; ctx.font = fontSize + 'px ' + font; ctx.lineWidth = outlineSize + 'px '; ctx.strokeStyle = outline; ctx.fillStyle = 'rgba(0,0,0,0)'; ctx.fillRect(0, 0, w, h); ctx.fillStyle = color; this.aspect = size.width / fontSize; ctx.fillText(text, 0, 0); ctx.strokeText(text, 0, 0); var scaledcanvas = document.createElement('canvas'); var scaledctx = scaledcanvas.getContext('2d'); scaledcanvas.width = this.getNextPOT(w); scaledcanvas.height = this.getNextPOT(h); scaledctx.drawImage(canvas, 0, 0, scaledcanvas.width, scaledcanvas.height); this.cache[text] = new THREE.Texture(scaledcanvas); this.cache[text].needsUpdate = true; } return this.cache[text]; }, getAspectRatio: function(text) { var ctx = this.ctx, font = this.font, fontSize = this.fontSize; ctx.font = fontSize + 'px ' + font; var size = ctx.measureText(text); return size.width / fontSize; }, getInstance: function(args) { if (!this._texture) { this.load(); } return this._texture; } }, elation.engine.assets.base); /* assetpack = [ { name: 'grass-diffuse', 'assettype: 'image', src: '/textures/grass/diffuse.jpg' }, { name: 'grass-normal', 'assettype: 'image', src: '/textures/grass/normal.png' }, { name: 'grass', 'assettype: 'material', materialtype: 'phong', map: 'grass-diffuse', normalMap: 'grass-normal'}, { name: 'house', assettype: 'model', modeltype: 'collada', src: '/models/house.dae' }, { name: 'tree', assettype: 'model', modeltype: 'collada', src: '/models/tree.dae' } ] */ elation.define('engine.assets.script', { assettype: 'script', src: false, code: false, _construct: function(args) { elation.class.call(this, args); //this.load(); }, load: function() { this._script = document.createElement('script'); if (this.code) { setTimeout(elation.bind(this, function() { this.parse(this.code); }), 0); } else if (this.src) { var url = this.getProxiedURL(this.src); elation.engine.assetdownloader.fetchURL(url).then(ev => { let decoder = new TextDecoder('utf-8'); this.parse(decoder.decode(ev.target.response)); }); } }, parse: function(data) { //var blob = new Blob(['(function(window) {\n' + data + '\n})(self)'], {type: 'application/javascript'}); var blob = new Blob(['\n' + data + '\n'], {type: 'application/javascript'}); var bloburl = URL.createObjectURL(blob); this._script.src = bloburl; elation.events.fire({type: 'asset_load', element: this._script}); elation.events.fire({type: 'asset_load', element: this}); }, handleProgress: function(ev) { }, handleError: function(ev) { this._script = false; }, getInstance: function(args) { if (!this._script) { this.load(); } return this._script; } }, elation.engine.assets.base); elation.define('engine.assets.file', { assettype: 'file', src: false, content: false, load: function() { if (this.src) { var fullurl = this.getFullURL(this.src); if (!elation.engine.assetdownloader.isUrlInQueue(fullurl)) { elation.engine.assetdownloader.fetchURLs([fullurl], elation.bind(this, this.handleProgress)).then( elation.bind(this, function(events) { var xhr = events[0].target; var type = this.contenttype = xhr.getResponseHeader('content-type') this.state = 'processing'; elation.events.fire({element: this, type: 'asset_load_processing'}); this.content = xhr.response; elation.events.fire({element: this, type: 'asset_load'}); }), elation.bind(this, function(error) { this.state = 'error'; elation.events.fire({element: this, type: 'asset_error'}); }) ); elation.events.fire({element: this, type: 'asset_load_queued'}); } } }, getInstance: function(args) { if (!this.content) { this.load(); } return this.arrayToString(this.content); }, arrayToString: function(arr) { var str = ''; var bytes = new Uint8Array(arr); for (var i = 0; i < bytes.length; i++) { str += String.fromCharCode(bytes[i]); } return str; } }, elation.engine.assets.base); elation.define('engine.assets.shader', { assettype: 'shader', fragment_src: false, vertex_src: false, uniforms: {}, _construct: function(args) { elation.class.call(this, args); //this.load(); }, load: function() { this._material = new THREE.ShaderMaterial(); if (this.fragment_src || this.vertex_src) { if (this.fragment_src) { elation.engine.assetdownloader.fetchURL(this.getProxiedURL(this.fragment_src)).then(ev => { let decoder = new TextDecoder('utf-8'); this._material.fragmentShader = decoder.decode(ev.target.response); this._material.needsUpdate = true; }); } if (this.vertex_src) { elation.engine.assetdownloader.fetchURL(this.getProxiedURL(this.vertex_src)).then(ev => { let decoder = new TextDecoder('utf-8'); this._material.vertexShader = decoder.decode(ev.target.response); this._material.needsUpdate = true; }); } } if (this.uniforms) { this._material.uniforms = this.parseUniforms(this.uniforms); } this.complete(); }, complete: function(data) { elation.events.fire({type: 'asset_load', element: this._material}); elation.events.fire({type: 'asset_load', element: this}); elation.events.fire({element: this, type: 'asset_load_complete'}); }, parseUniforms(uniforms) { let matuniforms = {}; uniforms.forEach(u => { matuniforms[u.name] = { value: u.value }; }); return matuniforms; }, handleProgress: function(ev) { }, handleError: function(ev) { this._material = false; }, getInstance: function(args) { if (!this._material) { this.load(); } return this._material; } }, elation.engine.assets.base); });
Fix for duplicated baseurl and empty urls
scripts/assets.js
Fix for duplicated baseurl and empty urls
<ide><path>cripts/assets.js <ide> }, <ide> getFullURL: function(url, baseurl) { <ide> if (!url) url = this.src; <add> if (!url) url = ''; <ide> if (!baseurl) baseurl = this.baseurl; <ide> var fullurl = url; <ide> if (!this.isURLBlob(fullurl) && !this.isURLData(fullurl)) { <del> if (this.isURLRelative(fullurl)) { <add> if (this.isURLRelative(fullurl) && fullurl.substr(0, baseurl.length) != baseurl) { <ide> fullurl = baseurl + fullurl; <ide> } else if (this.isURLProxied(fullurl)) { <ide> fullurl = fullurl.replace(elation.engine.assets.corsproxy, '');
Java
apache-2.0
a11cd119c6c2a3c041a4222d7a81c70a496c537c
0
apache/felix-dev,apache/felix-dev,apache/felix-dev,apache/felix-dev
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.felix.bundleplugin; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.apache.maven.archiver.ManifestSection; import org.apache.maven.archiver.MavenArchiveConfiguration; import org.apache.maven.archiver.MavenArchiver; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager; import org.apache.maven.model.License; import org.apache.maven.model.Model; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectHelper; import org.apache.maven.shared.osgi.DefaultMaven2OsgiConverter; import org.apache.maven.shared.osgi.Maven2OsgiConverter; import org.codehaus.plexus.archiver.UnArchiver; import org.codehaus.plexus.archiver.manager.ArchiverManager; import org.codehaus.plexus.util.DirectoryScanner; import org.codehaus.plexus.util.StringInputStream; import org.codehaus.plexus.util.StringUtils; import aQute.lib.osgi.Analyzer; import aQute.lib.osgi.Builder; import aQute.lib.osgi.EmbeddedResource; import aQute.lib.osgi.FileResource; import aQute.lib.osgi.Jar; /** * Create an OSGi bundle from Maven project * * @goal bundle * @phase package * @requiresDependencyResolution test * @description build an OSGi bundle jar */ public class BundlePlugin extends AbstractMojo { /** * Directory where the manifest will be written * * @parameter expression="${manifestLocation}" default-value="${project.build.outputDirectory}/META-INF" */ protected File manifestLocation; /** * When true, unpack the bundle contents to the outputDirectory * * @parameter expression="${unpackBundle}" */ protected boolean unpackBundle; /** * Comma separated list of artifactIds to exclude from the dependency classpath passed to BND (use "true" to exclude everything) * * @parameter expression="${excludeDependencies}" */ protected String excludeDependencies; /** * Classifier type of the bundle to be installed. For example, "jdk14". * Defaults to none which means this is the project's main bundle. * * @parameter expression="${classifier}" */ protected String classifier; /** * @component */ private MavenProjectHelper m_projectHelper; /** * @component */ private ArchiverManager m_archiverManager; /** * @component */ private ArtifactHandlerManager m_artifactHandlerManager; /** * Project types which this plugin supports. * * @parameter */ private List supportedProjectTypes = Arrays.asList( new String[] { "jar", "bundle" } ); /** * The directory for the generated bundles. * * @parameter expression="${project.build.outputDirectory}" * @required */ private File outputDirectory; /** * The directory for the pom * * @parameter expression="${basedir}" * @required */ private File baseDir; /** * The directory for the generated JAR. * * @parameter expression="${project.build.directory}" * @required */ private String buildDirectory; /** * The Maven project. * * @parameter expression="${project}" * @required * @readonly */ private MavenProject project; /** * The BND instructions for the bundle. * * @parameter */ private Map instructions = new HashMap(); /** * Use locally patched version for now. */ private Maven2OsgiConverter m_maven2OsgiConverter = new DefaultMaven2OsgiConverter(); /** * The archive configuration to use. * * @parameter */ private MavenArchiveConfiguration archive; // accessed indirectly in JarPluginConfiguration private static final String MAVEN_SYMBOLICNAME = "maven-symbolicname"; private static final String MAVEN_RESOURCES = "{maven-resources}"; private static final String[] EMPTY_STRING_ARRAY = {}; private static final String[] DEFAULT_INCLUDES = { "**/**" }; protected Maven2OsgiConverter getMaven2OsgiConverter() { return m_maven2OsgiConverter; } protected void setMaven2OsgiConverter( Maven2OsgiConverter maven2OsgiConverter ) { m_maven2OsgiConverter = maven2OsgiConverter; } protected MavenProject getProject() { return project; } /** * @see org.apache.maven.plugin.AbstractMojo#execute() */ public void execute() throws MojoExecutionException { Properties properties = new Properties(); String projectType = getProject().getArtifact().getType(); // ignore unsupported project types, useful when bundleplugin is configured in parent pom if ( !supportedProjectTypes.contains( projectType ) ) { getLog().warn( "Ignoring project type " + projectType + " - supportedProjectTypes = " + supportedProjectTypes ); return; } execute( getProject(), instructions, properties ); } protected void execute( MavenProject currentProject, Map originalInstructions, Properties properties ) throws MojoExecutionException { try { execute( currentProject, originalInstructions, properties, getClasspath( currentProject ) ); } catch ( IOException e ) { throw new MojoExecutionException( "Error calculating classpath for project " + currentProject, e ); } } /* transform directives from their XML form to the expected BND syntax (eg. _include becomes -include) */ protected static Map transformDirectives( Map originalInstructions ) { Map transformedInstructions = new HashMap(); for ( Iterator i = originalInstructions.entrySet().iterator(); i.hasNext(); ) { Map.Entry e = ( Map.Entry ) i.next(); String key = ( String ) e.getKey(); if ( key.startsWith( "_" ) ) { key = "-" + key.substring( 1 ); } String value = ( String ) e.getValue(); if ( null == value ) { value = ""; } else { value = value.replaceAll( "[\r\n]", "" ); } transformedInstructions.put( key, value ); } return transformedInstructions; } protected void execute( MavenProject currentProject, Map originalInstructions, Properties properties, Jar[] classpath ) throws MojoExecutionException { try { File jarFile = new File( getBuildDirectory(), getBundleName( currentProject ) ); Builder builder = buildOSGiBundle( currentProject, originalInstructions, properties, classpath ); List errors = builder.getErrors(); List warnings = builder.getWarnings(); for ( Iterator w = warnings.iterator(); w.hasNext(); ) { String msg = ( String ) w.next(); getLog().warn( "Warning building bundle " + currentProject.getArtifact() + " : " + msg ); } for ( Iterator e = errors.iterator(); e.hasNext(); ) { String msg = ( String ) e.next(); getLog().error( "Error building bundle " + currentProject.getArtifact() + " : " + msg ); } if ( errors.size() > 0 ) { String failok = builder.getProperty( "-failok" ); if ( null == failok || "false".equalsIgnoreCase( failok ) ) { jarFile.delete(); throw new MojoFailureException( "Error(s) found in bundle configuration" ); } } // attach bundle to maven project jarFile.getParentFile().mkdirs(); builder.getJar().write( jarFile ); Artifact mainArtifact = currentProject.getArtifact(); // workaround for MNG-1682: force maven to install artifact using the "jar" handler mainArtifact.setArtifactHandler( m_artifactHandlerManager.getArtifactHandler( "jar" ) ); if ( null == classifier || classifier.trim().length() == 0 ) { mainArtifact.setFile( jarFile ); } else { m_projectHelper.attachArtifact( currentProject, jarFile, classifier ); } if ( unpackBundle ) { unpackBundle( jarFile ); } if ( manifestLocation != null ) { File outputFile = new File( manifestLocation, "MANIFEST.MF" ); try { Manifest manifest = builder.getJar().getManifest(); ManifestPlugin.writeManifest( manifest, outputFile ); } catch ( IOException e ) { getLog().error( "Error trying to write Manifest to file " + outputFile, e ); } } // cleanup... builder.close(); } catch ( MojoFailureException e ) { getLog().error( e.getLocalizedMessage() ); throw new MojoExecutionException( "Error(s) found in bundle configuration", e ); } catch ( Exception e ) { getLog().error( "An internal error occurred", e ); throw new MojoExecutionException( "Internal error in maven-bundle-plugin", e ); } } protected Builder buildOSGiBundle( MavenProject currentProject, Map originalInstructions, Properties properties, Jar[] classpath ) throws Exception { properties.putAll( getDefaultProperties( currentProject ) ); properties.putAll( transformDirectives( originalInstructions ) ); Builder builder = new Builder(); builder.setBase( currentProject.getBasedir() ); builder.setProperties( properties ); builder.setClasspath( classpath ); // update BND instructions to add included Maven resources includeMavenResources( currentProject, builder, getLog() ); // calculate default export/private settings based on sources if ( builder.getProperty( Analyzer.PRIVATE_PACKAGE ) == null || builder.getProperty( Analyzer.EXPORT_PACKAGE ) == null ) { addLocalPackages( currentProject.getBuild().getSourceDirectory(), builder ); } // update BND instructions to embed selected Maven dependencies Collection embeddableArtifacts = getEmbeddableArtifacts( currentProject, builder ); new DependencyEmbedder( embeddableArtifacts ).processHeaders( builder ); dumpInstructions( "BND Instructions:", builder.getProperties(), getLog() ); dumpClasspath( "BND Classpath:", builder.getClasspath(), getLog() ); builder.build(); Jar jar = builder.getJar(); dumpManifest( "BND Manifest:", jar.getManifest(), getLog() ); String[] removeHeaders = builder.getProperty( Analyzer.REMOVE_HEADERS, "" ).split( "," ); mergeMavenManifest( currentProject, jar, removeHeaders, getLog() ); builder.setJar( jar ); dumpManifest( "Final Manifest:", jar.getManifest(), getLog() ); return builder; } protected static void dumpInstructions( String title, Properties properties, Log log ) { if ( log.isDebugEnabled() ) { log.debug( title ); log.debug( "------------------------------------------------------------------------" ); for ( Enumeration e = properties.propertyNames(); e.hasMoreElements(); ) { String key = ( String ) e.nextElement(); log.debug( key + ": " + properties.getProperty( key ) ); } log.debug( "------------------------------------------------------------------------" ); } } protected static void dumpClasspath( String title, List classpath, Log log ) { if ( log.isDebugEnabled() ) { log.debug( title ); log.debug( "------------------------------------------------------------------------" ); for ( Iterator i = classpath.iterator(); i.hasNext(); ) { File path = ( ( Jar ) i.next() ).getSource(); log.debug( null == path ? "null" : path.toString() ); } log.debug( "------------------------------------------------------------------------" ); } } protected static void dumpManifest( String title, Manifest manifest, Log log ) { if ( log.isDebugEnabled() ) { log.debug( title ); log.debug( "------------------------------------------------------------------------" ); for ( Iterator i = manifest.getMainAttributes().entrySet().iterator(); i.hasNext(); ) { Map.Entry entry = ( Map.Entry ) i.next(); log.debug( entry.getKey() + ": " + entry.getValue() ); } log.debug( "------------------------------------------------------------------------" ); } } protected static void includeMavenResources( MavenProject currentProject, Analyzer analyzer, Log log ) { // pass maven resource paths onto BND analyzer final String mavenResourcePaths = getMavenResourcePaths( currentProject ); final String includeResource = ( String ) analyzer.getProperty( Analyzer.INCLUDE_RESOURCE ); if ( includeResource != null ) { if ( includeResource.indexOf( MAVEN_RESOURCES ) >= 0 ) { // if there is no maven resource path, we do a special treatment and replace // every occurance of MAVEN_RESOURCES and a following comma with an empty string if ( mavenResourcePaths.length() == 0 ) { String cleanedResource = removeTagFromInstruction( includeResource, MAVEN_RESOURCES ); if ( cleanedResource.length() > 0 ) { analyzer.setProperty( Analyzer.INCLUDE_RESOURCE, cleanedResource ); } else { analyzer.unsetProperty( Analyzer.INCLUDE_RESOURCE ); } } else { String combinedResource = StringUtils .replace( includeResource, MAVEN_RESOURCES, mavenResourcePaths ); analyzer.setProperty( Analyzer.INCLUDE_RESOURCE, combinedResource ); } } else if ( mavenResourcePaths.length() > 0 ) { log.warn( Analyzer.INCLUDE_RESOURCE + ": overriding " + mavenResourcePaths + " with " + includeResource + " (add " + MAVEN_RESOURCES + " if you want to include the maven resources)" ); } } else if ( mavenResourcePaths.length() > 0 ) { analyzer.setProperty( Analyzer.INCLUDE_RESOURCE, mavenResourcePaths ); } } protected void mergeMavenManifest( MavenProject currentProject, Jar jar, String[] removeHeaders, Log log ) throws IOException { boolean addMavenDescriptor = true; try { /* * Grab customized manifest entries from the maven-jar-plugin configuration */ MavenArchiveConfiguration archiveConfig = JarPluginConfiguration.getArchiveConfiguration( currentProject ); String mavenManifestText = new MavenArchiver().getManifest( currentProject, archiveConfig ).toString(); addMavenDescriptor = archiveConfig.isAddMavenDescriptor(); Manifest mavenManifest = new Manifest(); // First grab the external manifest file (if specified) File externalManifestFile = archiveConfig.getManifestFile(); if ( null != externalManifestFile && externalManifestFile.exists() ) { InputStream mis = new FileInputStream( externalManifestFile ); mavenManifest.read( mis ); mis.close(); } // Then apply the customized entries from the jar plugin mavenManifest.read( new StringInputStream( mavenManifestText ) ); if ( !archiveConfig.isManifestSectionsEmpty() ) { /* * Add customized manifest sections (for some reason MavenArchiver doesn't do this for us) */ List sections = archiveConfig.getManifestSections(); for ( Iterator i = sections.iterator(); i.hasNext(); ) { ManifestSection section = ( ManifestSection ) i.next(); Attributes attributes = new Attributes(); if ( !section.isManifestEntriesEmpty() ) { Map entries = section.getManifestEntries(); for ( Iterator j = entries.entrySet().iterator(); j.hasNext(); ) { Map.Entry entry = ( Map.Entry ) j.next(); attributes.putValue( ( String ) entry.getKey(), ( String ) entry.getValue() ); } } mavenManifest.getEntries().put( section.getName(), attributes ); } } Attributes mainMavenAttributes = mavenManifest.getMainAttributes(); mainMavenAttributes.putValue( "Created-By", "Apache Maven Bundle Plugin" ); // apply -removeheaders to the custom manifest for ( int i = 0; i < removeHeaders.length; i++ ) { for ( Iterator j = mainMavenAttributes.keySet().iterator(); j.hasNext(); ) { if ( j.next().toString().matches( removeHeaders[i].trim() ) ) { j.remove(); } } } /* * Overlay generated bundle manifest with customized entries */ Manifest bundleManifest = jar.getManifest(); bundleManifest.getMainAttributes().putAll( mainMavenAttributes ); bundleManifest.getEntries().putAll( mavenManifest.getEntries() ); jar.setManifest( bundleManifest ); } catch ( Exception e ) { log.warn( "Unable to merge Maven manifest: " + e.getLocalizedMessage() ); } if ( addMavenDescriptor ) { doMavenMetadata( currentProject, jar ); } } private void unpackBundle( File jarFile ) { File outputDir = getOutputDirectory(); if ( null == outputDir ) { outputDir = new File( getBuildDirectory(), "classes" ); } try { /* * this directory must exist before unpacking, otherwise the plexus * unarchiver decides to use the current working directory instead! */ if ( !outputDir.exists() ) { outputDir.mkdirs(); } UnArchiver unArchiver = m_archiverManager.getUnArchiver( "jar" ); unArchiver.setDestDirectory( outputDir ); unArchiver.setSourceFile( jarFile ); unArchiver.extract(); } catch ( Exception e ) { getLog().error( "Problem unpacking " + jarFile + " to " + outputDir, e ); } } protected static String removeTagFromInstruction( String instruction, String tag ) { StringBuffer buf = new StringBuffer(); String[] clauses = instruction.split( "," ); for ( int i = 0; i < clauses.length; i++ ) { String clause = clauses[i].trim(); if ( !tag.equals( clause ) ) { if ( buf.length() > 0 ) { buf.append( ',' ); } buf.append( clause ); } } return buf.toString(); } private static Map getProperties( Model projectModel, String prefix ) { Map properties = new HashMap(); Method methods[] = Model.class.getDeclaredMethods(); for ( int i = 0; i < methods.length; i++ ) { String name = methods[i].getName(); if ( name.startsWith( "get" ) ) { try { Object v = methods[i].invoke( projectModel, null ); if ( v != null ) { name = prefix + Character.toLowerCase( name.charAt( 3 ) ) + name.substring( 4 ); if ( v.getClass().isArray() ) properties.put( name, Arrays.asList( ( Object[] ) v ).toString() ); else properties.put( name, v ); } } catch ( Exception e ) { // too bad } } } return properties; } private static StringBuffer printLicenses( List licenses ) { if ( licenses == null || licenses.size() == 0 ) return null; StringBuffer sb = new StringBuffer(); String del = ""; for ( Iterator i = licenses.iterator(); i.hasNext(); ) { License l = ( License ) i.next(); String url = l.getUrl(); if ( url == null ) continue; sb.append( del ); sb.append( url ); del = ", "; } if ( sb.length() == 0 ) return null; return sb; } /** * @param jar * @throws IOException */ private void doMavenMetadata( MavenProject currentProject, Jar jar ) throws IOException { String path = "META-INF/maven/" + currentProject.getGroupId() + "/" + currentProject.getArtifactId(); File pomFile = new File( baseDir, "pom.xml" ); jar.putResource( path + "/pom.xml", new FileResource( pomFile ) ); Properties p = new Properties(); p.put( "version", currentProject.getVersion() ); p.put( "groupId", currentProject.getGroupId() ); p.put( "artifactId", currentProject.getArtifactId() ); ByteArrayOutputStream out = new ByteArrayOutputStream(); p.store( out, "Generated by org.apache.felix.bundleplugin" ); jar .putResource( path + "/pom.properties", new EmbeddedResource( out.toByteArray(), System.currentTimeMillis() ) ); } protected Jar[] getClasspath( MavenProject currentProject ) throws IOException, MojoExecutionException { List list = new ArrayList(); if ( getOutputDirectory() != null && getOutputDirectory().exists() ) { list.add( new Jar( ".", getOutputDirectory() ) ); } final Collection artifacts = getSelectedDependencies( currentProject.getArtifacts() ); for ( Iterator it = artifacts.iterator(); it.hasNext(); ) { Artifact artifact = ( Artifact ) it.next(); if ( artifact.getArtifactHandler().isAddedToClasspath() ) { if ( !Artifact.SCOPE_TEST.equals( artifact.getScope() ) ) { File file = getFile( artifact ); if ( file == null ) { getLog().warn( "File is not available for artifact " + artifact + " in project " + currentProject.getArtifact() ); continue; } Jar jar = new Jar( artifact.getArtifactId(), file ); list.add( jar ); } } } Jar[] cp = new Jar[list.size()]; list.toArray( cp ); return cp; } private Collection getSelectedDependencies( Collection artifacts ) throws MojoExecutionException { if ( null == excludeDependencies || excludeDependencies.length() == 0 ) { return artifacts; } else if ( "true".equalsIgnoreCase( excludeDependencies ) ) { return Collections.EMPTY_LIST; } Collection selectedDependencies = new HashSet( artifacts ); DependencyExcluder excluder = new DependencyExcluder( artifacts ); excluder.processHeaders( excludeDependencies ); selectedDependencies.removeAll( excluder.getExcludedArtifacts() ); return selectedDependencies; } /** * Get the file for an Artifact * * @param artifact */ protected File getFile( Artifact artifact ) { return artifact.getFile(); } private static void header( Properties properties, String key, Object value ) { if ( value == null ) return; if ( value instanceof Collection && ( ( Collection ) value ).isEmpty() ) return; properties.put( key, value.toString().replaceAll( "[\r\n]", "" ) ); } /** * Convert a Maven version into an OSGi compliant version * * @param version Maven version * @return the OSGi version */ protected String convertVersionToOsgi( String version ) { return getMaven2OsgiConverter().getVersion( version ); } /** * TODO this should return getMaven2Osgi().getBundleFileName( project.getArtifact() ) */ protected String getBundleName( MavenProject currentProject ) { String finalName = currentProject.getBuild().getFinalName(); if ( null != classifier && classifier.trim().length() > 0 ) { return finalName + '-' + classifier + ".jar"; } return finalName + ".jar"; } protected String getBuildDirectory() { return buildDirectory; } protected void setBuildDirectory( String _buildirectory ) { buildDirectory = _buildirectory; } protected Properties getDefaultProperties( MavenProject currentProject ) { Properties properties = new Properties(); String bsn; try { bsn = getMaven2OsgiConverter().getBundleSymbolicName( currentProject.getArtifact() ); } catch ( Exception e ) { bsn = currentProject.getGroupId() + "." + currentProject.getArtifactId(); } // Setup defaults properties.put( MAVEN_SYMBOLICNAME, bsn ); properties.put( Analyzer.BUNDLE_SYMBOLICNAME, bsn ); properties.put( Analyzer.IMPORT_PACKAGE, "*" ); properties.put( Analyzer.BUNDLE_VERSION, currentProject.getVersion() ); // remove the verbose Include-Resource entry from generated manifest properties.put( Analyzer.REMOVE_HEADERS, Analyzer.INCLUDE_RESOURCE ); header( properties, Analyzer.BUNDLE_DESCRIPTION, currentProject.getDescription() ); StringBuffer licenseText = printLicenses( currentProject.getLicenses() ); if ( licenseText != null ) { header( properties, Analyzer.BUNDLE_LICENSE, licenseText ); } header( properties, Analyzer.BUNDLE_NAME, currentProject.getName() ); if ( currentProject.getOrganization() != null ) { header( properties, Analyzer.BUNDLE_VENDOR, currentProject.getOrganization().getName() ); if ( currentProject.getOrganization().getUrl() != null ) { header( properties, Analyzer.BUNDLE_DOCURL, currentProject.getOrganization().getUrl() ); } } properties.putAll( currentProject.getProperties() ); properties.putAll( currentProject.getModel().getProperties() ); properties.putAll( getProperties( currentProject.getModel(), "project.build." ) ); properties.putAll( getProperties( currentProject.getModel(), "pom." ) ); properties.putAll( getProperties( currentProject.getModel(), "project." ) ); properties.put( "project.baseDir", baseDir ); properties.put( "project.build.directory", getBuildDirectory() ); properties.put( "project.build.outputdirectory", getOutputDirectory() ); properties.put( "classifier", classifier == null ? "" : classifier ); return properties; } protected void setBasedir( File _basedir ) { baseDir = _basedir; } protected File getOutputDirectory() { return outputDirectory; } protected void setOutputDirectory( File _outputDirectory ) { outputDirectory = _outputDirectory; } private static void addLocalPackages( String sourceDirectory, Analyzer analyzer ) { Collection packages = new HashSet(); if ( sourceDirectory != null && new File( sourceDirectory ).isDirectory() ) { // scan local Java sources for potential packages DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir( sourceDirectory ); scanner.setIncludes( new String[] { "**/*.java" } ); scanner.addDefaultExcludes(); scanner.scan(); String[] paths = scanner.getIncludedFiles(); for ( int i = 0; i < paths.length; i++ ) { packages.add( getPackageName( paths[i] ) ); } } StringBuffer exportedPkgs = new StringBuffer(); StringBuffer privatePkgs = new StringBuffer(); for ( Iterator i = packages.iterator(); i.hasNext(); ) { String pkg = ( String ) i.next(); // mark all source packages as private by default (can be overridden by export list) privatePkgs.append( pkg ).append( ',' ); // we can't export the default package (".") and we shouldn't export internal packages if ( !( ".".equals( pkg ) || pkg.contains( ".internal" ) || pkg.contains( ".impl" ) ) ) { exportedPkgs.append( pkg ).append( ',' ); } } if ( analyzer.getProperty( Analyzer.EXPORT_PACKAGE ) == null ) { if ( analyzer.getProperty( Analyzer.EXPORT_CONTENTS ) == null ) { // no -exportcontents overriding the exports, so use our computed list analyzer.setProperty( Analyzer.EXPORT_PACKAGE, exportedPkgs.toString() ); } else { // leave Export-Package empty (but non-null) as we have -exportcontents analyzer.setProperty( Analyzer.EXPORT_PACKAGE, "" ); } } if ( analyzer.getProperty( Analyzer.PRIVATE_PACKAGE ) == null ) { // if there are really no private packages then use "!*" as this will keep the Bnd Tool happy analyzer.setProperty( Analyzer.PRIVATE_PACKAGE, privatePkgs.length() == 0 ? "!*" : privatePkgs.toString() ); } } private static String getPackageName( String filename ) { int n = filename.lastIndexOf( File.separatorChar ); return n < 0 ? "." : filename.substring( 0, n ).replace( File.separatorChar, '.' ); } private static String getMavenResourcePaths( MavenProject project ) { final String basePath = project.getBasedir().getAbsolutePath(); StringBuffer resourcePaths = new StringBuffer(); for ( Iterator i = project.getResources().iterator(); i.hasNext(); ) { org.apache.maven.model.Resource resource = ( org.apache.maven.model.Resource ) i.next(); final String sourcePath = resource.getDirectory(); final String targetPath = resource.getTargetPath(); // ignore empty or non-local resources if ( new File( sourcePath ).exists() && ( ( targetPath == null ) || ( targetPath.indexOf( ".." ) < 0 ) ) ) { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir( resource.getDirectory() ); if ( resource.getIncludes() != null && !resource.getIncludes().isEmpty() ) { scanner.setIncludes( ( String[] ) resource.getIncludes().toArray( EMPTY_STRING_ARRAY ) ); } else { scanner.setIncludes( DEFAULT_INCLUDES ); } if ( resource.getExcludes() != null && !resource.getExcludes().isEmpty() ) { scanner.setExcludes( ( String[] ) resource.getExcludes().toArray( EMPTY_STRING_ARRAY ) ); } scanner.addDefaultExcludes(); scanner.scan(); List includedFiles = Arrays.asList( scanner.getIncludedFiles() ); for ( Iterator j = includedFiles.iterator(); j.hasNext(); ) { String name = ( String ) j.next(); String path = sourcePath + '/' + name; // make relative to project if ( path.startsWith( basePath ) ) { if ( path.length() == basePath.length() ) { path = "."; } else { path = path.substring( basePath.length() + 1 ); } } // replace windows backslash with a slash // this is a workaround for a problem with bnd 0.0.189 if ( File.separatorChar != '/' ) { name = name.replace( File.separatorChar, '/' ); path = path.replace( File.separatorChar, '/' ); } // copy to correct place path = name + '=' + path; if ( targetPath != null ) { path = targetPath + '/' + path; } if ( resourcePaths.length() > 0 ) { resourcePaths.append( ',' ); } if ( resource.isFiltering() ) { resourcePaths.append( '{' ); resourcePaths.append( path ); resourcePaths.append( '}' ); } else { resourcePaths.append( path ); } } } } return resourcePaths.toString(); } protected Collection getEmbeddableArtifacts( MavenProject project, Analyzer analyzer ) throws MojoExecutionException { final Collection artifacts; String embedTransitive = analyzer.getProperty( DependencyEmbedder.EMBED_TRANSITIVE ); if ( Boolean.valueOf( embedTransitive ).booleanValue() ) { // includes transitive dependencies artifacts = project.getArtifacts(); } else { // only includes direct dependencies artifacts = project.getDependencyArtifacts(); } return getSelectedDependencies( artifacts ); } }
bundleplugin/src/main/java/org/apache/felix/bundleplugin/BundlePlugin.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.felix.bundleplugin; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.apache.maven.archiver.ManifestSection; import org.apache.maven.archiver.MavenArchiveConfiguration; import org.apache.maven.archiver.MavenArchiver; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager; import org.apache.maven.model.License; import org.apache.maven.model.Model; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectHelper; import org.apache.maven.shared.osgi.Maven2OsgiConverter; import org.codehaus.plexus.archiver.UnArchiver; import org.codehaus.plexus.archiver.manager.ArchiverManager; import org.codehaus.plexus.util.DirectoryScanner; import org.codehaus.plexus.util.StringInputStream; import org.codehaus.plexus.util.StringUtils; import aQute.lib.osgi.Analyzer; import aQute.lib.osgi.Builder; import aQute.lib.osgi.EmbeddedResource; import aQute.lib.osgi.FileResource; import aQute.lib.osgi.Jar; /** * Create an OSGi bundle from Maven project * * @goal bundle * @phase package * @requiresDependencyResolution test * @description build an OSGi bundle jar */ public class BundlePlugin extends AbstractMojo { /** * Directory where the manifest will be written * * @parameter expression="${manifestLocation}" default-value="${project.build.outputDirectory}/META-INF" */ protected File manifestLocation; /** * When true, unpack the bundle contents to the outputDirectory * * @parameter expression="${unpackBundle}" */ protected boolean unpackBundle; /** * Comma separated list of artifactIds to exclude from the dependency classpath passed to BND (use "true" to exclude everything) * * @parameter expression="${excludeDependencies}" */ protected String excludeDependencies; /** * Classifier type of the bundle to be installed. For example, "jdk14". * Defaults to none which means this is the project's main bundle. * * @parameter expression="${classifier}" */ protected String classifier; /** * @component */ private MavenProjectHelper m_projectHelper; /** * @component */ private ArchiverManager m_archiverManager; /** * @component */ private ArtifactHandlerManager m_artifactHandlerManager; /** * Project types which this plugin supports. * * @parameter */ private List supportedProjectTypes = Arrays.asList( new String[] { "jar", "bundle" } ); /** * The directory for the generated bundles. * * @parameter expression="${project.build.outputDirectory}" * @required */ private File outputDirectory; /** * The directory for the pom * * @parameter expression="${basedir}" * @required */ private File baseDir; /** * The directory for the generated JAR. * * @parameter expression="${project.build.directory}" * @required */ private String buildDirectory; /** * The Maven project. * * @parameter expression="${project}" * @required * @readonly */ private MavenProject project; /** * The BND instructions for the bundle. * * @parameter */ private Map instructions = new HashMap(); /** * @component */ private Maven2OsgiConverter m_maven2OsgiConverter; /** * The archive configuration to use. * * @parameter */ private MavenArchiveConfiguration archive; // accessed indirectly in JarPluginConfiguration private static final String MAVEN_SYMBOLICNAME = "maven-symbolicname"; private static final String MAVEN_RESOURCES = "{maven-resources}"; private static final String[] EMPTY_STRING_ARRAY = {}; private static final String[] DEFAULT_INCLUDES = { "**/**" }; protected Maven2OsgiConverter getMaven2OsgiConverter() { return m_maven2OsgiConverter; } protected void setMaven2OsgiConverter( Maven2OsgiConverter maven2OsgiConverter ) { m_maven2OsgiConverter = maven2OsgiConverter; } protected MavenProject getProject() { return project; } /** * @see org.apache.maven.plugin.AbstractMojo#execute() */ public void execute() throws MojoExecutionException { Properties properties = new Properties(); String projectType = getProject().getArtifact().getType(); // ignore unsupported project types, useful when bundleplugin is configured in parent pom if ( !supportedProjectTypes.contains( projectType ) ) { getLog().warn( "Ignoring project type " + projectType + " - supportedProjectTypes = " + supportedProjectTypes ); return; } execute( getProject(), instructions, properties ); } protected void execute( MavenProject currentProject, Map originalInstructions, Properties properties ) throws MojoExecutionException { try { execute( currentProject, originalInstructions, properties, getClasspath( currentProject ) ); } catch ( IOException e ) { throw new MojoExecutionException( "Error calculating classpath for project " + currentProject, e ); } } /* transform directives from their XML form to the expected BND syntax (eg. _include becomes -include) */ protected static Map transformDirectives( Map originalInstructions ) { Map transformedInstructions = new HashMap(); for ( Iterator i = originalInstructions.entrySet().iterator(); i.hasNext(); ) { Map.Entry e = ( Map.Entry ) i.next(); String key = ( String ) e.getKey(); if ( key.startsWith( "_" ) ) { key = "-" + key.substring( 1 ); } String value = ( String ) e.getValue(); if ( null == value ) { value = ""; } else { value = value.replaceAll( "[\r\n]", "" ); } transformedInstructions.put( key, value ); } return transformedInstructions; } protected void execute( MavenProject currentProject, Map originalInstructions, Properties properties, Jar[] classpath ) throws MojoExecutionException { try { File jarFile = new File( getBuildDirectory(), getBundleName( currentProject ) ); Builder builder = buildOSGiBundle( currentProject, originalInstructions, properties, classpath ); List errors = builder.getErrors(); List warnings = builder.getWarnings(); for ( Iterator w = warnings.iterator(); w.hasNext(); ) { String msg = ( String ) w.next(); getLog().warn( "Warning building bundle " + currentProject.getArtifact() + " : " + msg ); } for ( Iterator e = errors.iterator(); e.hasNext(); ) { String msg = ( String ) e.next(); getLog().error( "Error building bundle " + currentProject.getArtifact() + " : " + msg ); } if ( errors.size() > 0 ) { String failok = builder.getProperty( "-failok" ); if ( null == failok || "false".equalsIgnoreCase( failok ) ) { jarFile.delete(); throw new MojoFailureException( "Error(s) found in bundle configuration" ); } } // attach bundle to maven project jarFile.getParentFile().mkdirs(); builder.getJar().write( jarFile ); Artifact mainArtifact = currentProject.getArtifact(); // workaround for MNG-1682: force maven to install artifact using the "jar" handler mainArtifact.setArtifactHandler( m_artifactHandlerManager.getArtifactHandler( "jar" ) ); if ( null == classifier || classifier.trim().length() == 0 ) { mainArtifact.setFile( jarFile ); } else { m_projectHelper.attachArtifact( currentProject, jarFile, classifier ); } if ( unpackBundle ) { unpackBundle( jarFile ); } if ( manifestLocation != null ) { File outputFile = new File( manifestLocation, "MANIFEST.MF" ); try { Manifest manifest = builder.getJar().getManifest(); ManifestPlugin.writeManifest( manifest, outputFile ); } catch ( IOException e ) { getLog().error( "Error trying to write Manifest to file " + outputFile, e ); } } // cleanup... builder.close(); } catch ( MojoFailureException e ) { getLog().error( e.getLocalizedMessage() ); throw new MojoExecutionException( "Error(s) found in bundle configuration", e ); } catch ( Exception e ) { getLog().error( "An internal error occurred", e ); throw new MojoExecutionException( "Internal error in maven-bundle-plugin", e ); } } protected Builder buildOSGiBundle( MavenProject currentProject, Map originalInstructions, Properties properties, Jar[] classpath ) throws Exception { properties.putAll( getDefaultProperties( currentProject ) ); properties.putAll( transformDirectives( originalInstructions ) ); Builder builder = new Builder(); builder.setBase( currentProject.getBasedir() ); builder.setProperties( properties ); builder.setClasspath( classpath ); // update BND instructions to add included Maven resources includeMavenResources( currentProject, builder, getLog() ); // calculate default export/private settings based on sources if ( builder.getProperty( Analyzer.PRIVATE_PACKAGE ) == null || builder.getProperty( Analyzer.EXPORT_PACKAGE ) == null ) { addLocalPackages( currentProject.getBuild().getSourceDirectory(), builder ); } // update BND instructions to embed selected Maven dependencies Collection embeddableArtifacts = getEmbeddableArtifacts( currentProject, builder ); new DependencyEmbedder( embeddableArtifacts ).processHeaders( builder ); dumpInstructions( "BND Instructions:", builder.getProperties(), getLog() ); dumpClasspath( "BND Classpath:", builder.getClasspath(), getLog() ); builder.build(); Jar jar = builder.getJar(); dumpManifest( "BND Manifest:", jar.getManifest(), getLog() ); String[] removeHeaders = builder.getProperty( Analyzer.REMOVE_HEADERS, "" ).split( "," ); mergeMavenManifest( currentProject, jar, removeHeaders, getLog() ); builder.setJar( jar ); dumpManifest( "Final Manifest:", jar.getManifest(), getLog() ); return builder; } protected static void dumpInstructions( String title, Properties properties, Log log ) { if ( log.isDebugEnabled() ) { log.debug( title ); log.debug( "------------------------------------------------------------------------" ); for ( Enumeration e = properties.propertyNames(); e.hasMoreElements(); ) { String key = ( String ) e.nextElement(); log.debug( key + ": " + properties.getProperty( key ) ); } log.debug( "------------------------------------------------------------------------" ); } } protected static void dumpClasspath( String title, List classpath, Log log ) { if ( log.isDebugEnabled() ) { log.debug( title ); log.debug( "------------------------------------------------------------------------" ); for ( Iterator i = classpath.iterator(); i.hasNext(); ) { File path = ( ( Jar ) i.next() ).getSource(); log.debug( null == path ? "null" : path.toString() ); } log.debug( "------------------------------------------------------------------------" ); } } protected static void dumpManifest( String title, Manifest manifest, Log log ) { if ( log.isDebugEnabled() ) { log.debug( title ); log.debug( "------------------------------------------------------------------------" ); for ( Iterator i = manifest.getMainAttributes().entrySet().iterator(); i.hasNext(); ) { Map.Entry entry = ( Map.Entry ) i.next(); log.debug( entry.getKey() + ": " + entry.getValue() ); } log.debug( "------------------------------------------------------------------------" ); } } protected static void includeMavenResources( MavenProject currentProject, Analyzer analyzer, Log log ) { // pass maven resource paths onto BND analyzer final String mavenResourcePaths = getMavenResourcePaths( currentProject ); final String includeResource = ( String ) analyzer.getProperty( Analyzer.INCLUDE_RESOURCE ); if ( includeResource != null ) { if ( includeResource.indexOf( MAVEN_RESOURCES ) >= 0 ) { // if there is no maven resource path, we do a special treatment and replace // every occurance of MAVEN_RESOURCES and a following comma with an empty string if ( mavenResourcePaths.length() == 0 ) { String cleanedResource = removeTagFromInstruction( includeResource, MAVEN_RESOURCES ); if ( cleanedResource.length() > 0 ) { analyzer.setProperty( Analyzer.INCLUDE_RESOURCE, cleanedResource ); } else { analyzer.unsetProperty( Analyzer.INCLUDE_RESOURCE ); } } else { String combinedResource = StringUtils .replace( includeResource, MAVEN_RESOURCES, mavenResourcePaths ); analyzer.setProperty( Analyzer.INCLUDE_RESOURCE, combinedResource ); } } else if ( mavenResourcePaths.length() > 0 ) { log.warn( Analyzer.INCLUDE_RESOURCE + ": overriding " + mavenResourcePaths + " with " + includeResource + " (add " + MAVEN_RESOURCES + " if you want to include the maven resources)" ); } } else if ( mavenResourcePaths.length() > 0 ) { analyzer.setProperty( Analyzer.INCLUDE_RESOURCE, mavenResourcePaths ); } } protected void mergeMavenManifest( MavenProject currentProject, Jar jar, String[] removeHeaders, Log log ) throws IOException { boolean addMavenDescriptor = true; try { /* * Grab customized manifest entries from the maven-jar-plugin configuration */ MavenArchiveConfiguration archiveConfig = JarPluginConfiguration.getArchiveConfiguration( currentProject ); String mavenManifestText = new MavenArchiver().getManifest( currentProject, archiveConfig ).toString(); addMavenDescriptor = archiveConfig.isAddMavenDescriptor(); Manifest mavenManifest = new Manifest(); // First grab the external manifest file (if specified) File externalManifestFile = archiveConfig.getManifestFile(); if ( null != externalManifestFile && externalManifestFile.exists() ) { InputStream mis = new FileInputStream( externalManifestFile ); mavenManifest.read( mis ); mis.close(); } // Then apply the customized entries from the jar plugin mavenManifest.read( new StringInputStream( mavenManifestText ) ); if ( !archiveConfig.isManifestSectionsEmpty() ) { /* * Add customized manifest sections (for some reason MavenArchiver doesn't do this for us) */ List sections = archiveConfig.getManifestSections(); for ( Iterator i = sections.iterator(); i.hasNext(); ) { ManifestSection section = ( ManifestSection ) i.next(); Attributes attributes = new Attributes(); if ( !section.isManifestEntriesEmpty() ) { Map entries = section.getManifestEntries(); for ( Iterator j = entries.entrySet().iterator(); j.hasNext(); ) { Map.Entry entry = ( Map.Entry ) j.next(); attributes.putValue( ( String ) entry.getKey(), ( String ) entry.getValue() ); } } mavenManifest.getEntries().put( section.getName(), attributes ); } } Attributes mainMavenAttributes = mavenManifest.getMainAttributes(); mainMavenAttributes.putValue( "Created-By", "Apache Maven Bundle Plugin" ); // apply -removeheaders to the custom manifest for ( int i = 0; i < removeHeaders.length; i++ ) { for ( Iterator j = mainMavenAttributes.keySet().iterator(); j.hasNext(); ) { if ( j.next().toString().matches( removeHeaders[i].trim() ) ) { j.remove(); } } } /* * Overlay generated bundle manifest with customized entries */ Manifest bundleManifest = jar.getManifest(); bundleManifest.getMainAttributes().putAll( mainMavenAttributes ); bundleManifest.getEntries().putAll( mavenManifest.getEntries() ); jar.setManifest( bundleManifest ); } catch ( Exception e ) { log.warn( "Unable to merge Maven manifest: " + e.getLocalizedMessage() ); } if ( addMavenDescriptor ) { doMavenMetadata( currentProject, jar ); } } private void unpackBundle( File jarFile ) { File outputDir = getOutputDirectory(); if ( null == outputDir ) { outputDir = new File( getBuildDirectory(), "classes" ); } try { /* * this directory must exist before unpacking, otherwise the plexus * unarchiver decides to use the current working directory instead! */ if ( !outputDir.exists() ) { outputDir.mkdirs(); } UnArchiver unArchiver = m_archiverManager.getUnArchiver( "jar" ); unArchiver.setDestDirectory( outputDir ); unArchiver.setSourceFile( jarFile ); unArchiver.extract(); } catch ( Exception e ) { getLog().error( "Problem unpacking " + jarFile + " to " + outputDir, e ); } } protected static String removeTagFromInstruction( String instruction, String tag ) { StringBuffer buf = new StringBuffer(); String[] clauses = instruction.split( "," ); for ( int i = 0; i < clauses.length; i++ ) { String clause = clauses[i].trim(); if ( !tag.equals( clause ) ) { if ( buf.length() > 0 ) { buf.append( ',' ); } buf.append( clause ); } } return buf.toString(); } private static Map getProperties( Model projectModel, String prefix ) { Map properties = new HashMap(); Method methods[] = Model.class.getDeclaredMethods(); for ( int i = 0; i < methods.length; i++ ) { String name = methods[i].getName(); if ( name.startsWith( "get" ) ) { try { Object v = methods[i].invoke( projectModel, null ); if ( v != null ) { name = prefix + Character.toLowerCase( name.charAt( 3 ) ) + name.substring( 4 ); if ( v.getClass().isArray() ) properties.put( name, Arrays.asList( ( Object[] ) v ).toString() ); else properties.put( name, v ); } } catch ( Exception e ) { // too bad } } } return properties; } private static StringBuffer printLicenses( List licenses ) { if ( licenses == null || licenses.size() == 0 ) return null; StringBuffer sb = new StringBuffer(); String del = ""; for ( Iterator i = licenses.iterator(); i.hasNext(); ) { License l = ( License ) i.next(); String url = l.getUrl(); if ( url == null ) continue; sb.append( del ); sb.append( url ); del = ", "; } if ( sb.length() == 0 ) return null; return sb; } /** * @param jar * @throws IOException */ private void doMavenMetadata( MavenProject currentProject, Jar jar ) throws IOException { String path = "META-INF/maven/" + currentProject.getGroupId() + "/" + currentProject.getArtifactId(); File pomFile = new File( baseDir, "pom.xml" ); jar.putResource( path + "/pom.xml", new FileResource( pomFile ) ); Properties p = new Properties(); p.put( "version", currentProject.getVersion() ); p.put( "groupId", currentProject.getGroupId() ); p.put( "artifactId", currentProject.getArtifactId() ); ByteArrayOutputStream out = new ByteArrayOutputStream(); p.store( out, "Generated by org.apache.felix.bundleplugin" ); jar .putResource( path + "/pom.properties", new EmbeddedResource( out.toByteArray(), System.currentTimeMillis() ) ); } protected Jar[] getClasspath( MavenProject currentProject ) throws IOException, MojoExecutionException { List list = new ArrayList(); if ( getOutputDirectory() != null && getOutputDirectory().exists() ) { list.add( new Jar( ".", getOutputDirectory() ) ); } final Collection artifacts = getSelectedDependencies( currentProject.getArtifacts() ); for ( Iterator it = artifacts.iterator(); it.hasNext(); ) { Artifact artifact = ( Artifact ) it.next(); if ( artifact.getArtifactHandler().isAddedToClasspath() ) { if ( !Artifact.SCOPE_TEST.equals( artifact.getScope() ) ) { File file = getFile( artifact ); if ( file == null ) { getLog().warn( "File is not available for artifact " + artifact + " in project " + currentProject.getArtifact() ); continue; } Jar jar = new Jar( artifact.getArtifactId(), file ); list.add( jar ); } } } Jar[] cp = new Jar[list.size()]; list.toArray( cp ); return cp; } private Collection getSelectedDependencies( Collection artifacts ) throws MojoExecutionException { if ( null == excludeDependencies || excludeDependencies.length() == 0 ) { return artifacts; } else if ( "true".equalsIgnoreCase( excludeDependencies ) ) { return Collections.EMPTY_LIST; } Collection selectedDependencies = new HashSet( artifacts ); DependencyExcluder excluder = new DependencyExcluder( artifacts ); excluder.processHeaders( excludeDependencies ); selectedDependencies.removeAll( excluder.getExcludedArtifacts() ); return selectedDependencies; } /** * Get the file for an Artifact * * @param artifact */ protected File getFile( Artifact artifact ) { return artifact.getFile(); } private static void header( Properties properties, String key, Object value ) { if ( value == null ) return; if ( value instanceof Collection && ( ( Collection ) value ).isEmpty() ) return; properties.put( key, value.toString().replaceAll( "[\r\n]", "" ) ); } /** * Convert a Maven version into an OSGi compliant version * * @param version Maven version * @return the OSGi version */ protected String convertVersionToOsgi( String version ) { return getMaven2OsgiConverter().getVersion( version ); } /** * TODO this should return getMaven2Osgi().getBundleFileName( project.getArtifact() ) */ protected String getBundleName( MavenProject currentProject ) { String finalName = currentProject.getBuild().getFinalName(); if ( null != classifier && classifier.trim().length() > 0 ) { return finalName + '-' + classifier + ".jar"; } return finalName + ".jar"; } protected String getBuildDirectory() { return buildDirectory; } protected void setBuildDirectory( String _buildirectory ) { buildDirectory = _buildirectory; } protected Properties getDefaultProperties( MavenProject currentProject ) { Properties properties = new Properties(); String bsn; try { bsn = getMaven2OsgiConverter().getBundleSymbolicName( currentProject.getArtifact() ); } catch ( Exception e ) { bsn = currentProject.getGroupId() + "." + currentProject.getArtifactId(); } // Setup defaults properties.put( MAVEN_SYMBOLICNAME, bsn ); properties.put( Analyzer.BUNDLE_SYMBOLICNAME, bsn ); properties.put( Analyzer.IMPORT_PACKAGE, "*" ); properties.put( Analyzer.BUNDLE_VERSION, currentProject.getVersion() ); // remove the verbose Include-Resource entry from generated manifest properties.put( Analyzer.REMOVE_HEADERS, Analyzer.INCLUDE_RESOURCE ); header( properties, Analyzer.BUNDLE_DESCRIPTION, currentProject.getDescription() ); StringBuffer licenseText = printLicenses( currentProject.getLicenses() ); if ( licenseText != null ) { header( properties, Analyzer.BUNDLE_LICENSE, licenseText ); } header( properties, Analyzer.BUNDLE_NAME, currentProject.getName() ); if ( currentProject.getOrganization() != null ) { header( properties, Analyzer.BUNDLE_VENDOR, currentProject.getOrganization().getName() ); if ( currentProject.getOrganization().getUrl() != null ) { header( properties, Analyzer.BUNDLE_DOCURL, currentProject.getOrganization().getUrl() ); } } properties.putAll( currentProject.getProperties() ); properties.putAll( currentProject.getModel().getProperties() ); properties.putAll( getProperties( currentProject.getModel(), "project.build." ) ); properties.putAll( getProperties( currentProject.getModel(), "pom." ) ); properties.putAll( getProperties( currentProject.getModel(), "project." ) ); properties.put( "project.baseDir", baseDir ); properties.put( "project.build.directory", getBuildDirectory() ); properties.put( "project.build.outputdirectory", getOutputDirectory() ); properties.put( "classifier", classifier == null ? "" : classifier ); return properties; } protected void setBasedir( File _basedir ) { baseDir = _basedir; } protected File getOutputDirectory() { return outputDirectory; } protected void setOutputDirectory( File _outputDirectory ) { outputDirectory = _outputDirectory; } private static void addLocalPackages( String sourceDirectory, Analyzer analyzer ) { Collection packages = new HashSet(); if ( sourceDirectory != null && new File( sourceDirectory ).isDirectory() ) { // scan local Java sources for potential packages DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir( sourceDirectory ); scanner.setIncludes( new String[] { "**/*.java" } ); scanner.addDefaultExcludes(); scanner.scan(); String[] paths = scanner.getIncludedFiles(); for ( int i = 0; i < paths.length; i++ ) { packages.add( getPackageName( paths[i] ) ); } } StringBuffer exportedPkgs = new StringBuffer(); StringBuffer privatePkgs = new StringBuffer(); for ( Iterator i = packages.iterator(); i.hasNext(); ) { String pkg = ( String ) i.next(); // mark all source packages as private by default (can be overridden by export list) privatePkgs.append( pkg ).append( ',' ); // we can't export the default package (".") and we shouldn't export internal packages if ( !( ".".equals( pkg ) || pkg.contains( ".internal" ) || pkg.contains( ".impl" ) ) ) { exportedPkgs.append( pkg ).append( ',' ); } } if ( analyzer.getProperty( Analyzer.EXPORT_PACKAGE ) == null ) { if ( analyzer.getProperty( Analyzer.EXPORT_CONTENTS ) == null ) { // no -exportcontents overriding the exports, so use our computed list analyzer.setProperty( Analyzer.EXPORT_PACKAGE, exportedPkgs.toString() ); } else { // leave Export-Package empty (but non-null) as we have -exportcontents analyzer.setProperty( Analyzer.EXPORT_PACKAGE, "" ); } } if ( analyzer.getProperty( Analyzer.PRIVATE_PACKAGE ) == null ) { // if there are really no private packages then use "!*" as this will keep the Bnd Tool happy analyzer.setProperty( Analyzer.PRIVATE_PACKAGE, privatePkgs.length() == 0 ? "!*" : privatePkgs.toString() ); } } private static String getPackageName( String filename ) { int n = filename.lastIndexOf( File.separatorChar ); return n < 0 ? "." : filename.substring( 0, n ).replace( File.separatorChar, '.' ); } private static String getMavenResourcePaths( MavenProject project ) { final String basePath = project.getBasedir().getAbsolutePath(); StringBuffer resourcePaths = new StringBuffer(); for ( Iterator i = project.getResources().iterator(); i.hasNext(); ) { org.apache.maven.model.Resource resource = ( org.apache.maven.model.Resource ) i.next(); final String sourcePath = resource.getDirectory(); final String targetPath = resource.getTargetPath(); // ignore empty or non-local resources if ( new File( sourcePath ).exists() && ( ( targetPath == null ) || ( targetPath.indexOf( ".." ) < 0 ) ) ) { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir( resource.getDirectory() ); if ( resource.getIncludes() != null && !resource.getIncludes().isEmpty() ) { scanner.setIncludes( ( String[] ) resource.getIncludes().toArray( EMPTY_STRING_ARRAY ) ); } else { scanner.setIncludes( DEFAULT_INCLUDES ); } if ( resource.getExcludes() != null && !resource.getExcludes().isEmpty() ) { scanner.setExcludes( ( String[] ) resource.getExcludes().toArray( EMPTY_STRING_ARRAY ) ); } scanner.addDefaultExcludes(); scanner.scan(); List includedFiles = Arrays.asList( scanner.getIncludedFiles() ); for ( Iterator j = includedFiles.iterator(); j.hasNext(); ) { String name = ( String ) j.next(); String path = sourcePath + '/' + name; // make relative to project if ( path.startsWith( basePath ) ) { if ( path.length() == basePath.length() ) { path = "."; } else { path = path.substring( basePath.length() + 1 ); } } // replace windows backslash with a slash // this is a workaround for a problem with bnd 0.0.189 if ( File.separatorChar != '/' ) { name = name.replace( File.separatorChar, '/' ); path = path.replace( File.separatorChar, '/' ); } // copy to correct place path = name + '=' + path; if ( targetPath != null ) { path = targetPath + '/' + path; } if ( resourcePaths.length() > 0 ) { resourcePaths.append( ',' ); } if ( resource.isFiltering() ) { resourcePaths.append( '{' ); resourcePaths.append( path ); resourcePaths.append( '}' ); } else { resourcePaths.append( path ); } } } } return resourcePaths.toString(); } protected Collection getEmbeddableArtifacts( MavenProject project, Analyzer analyzer ) throws MojoExecutionException { final Collection artifacts; String embedTransitive = analyzer.getProperty( DependencyEmbedder.EMBED_TRANSITIVE ); if ( Boolean.valueOf( embedTransitive ).booleanValue() ) { // includes transitive dependencies artifacts = project.getArtifacts(); } else { // only includes direct dependencies artifacts = project.getDependencyArtifacts(); } return getSelectedDependencies( artifacts ); } }
Fix missing component (use local version) git-svn-id: e057f57e93a604d3b43d277ae69bde5ebf332112@745061 13f79535-47bb-0310-9956-ffa450edef68
bundleplugin/src/main/java/org/apache/felix/bundleplugin/BundlePlugin.java
Fix missing component (use local version)
<ide><path>undleplugin/src/main/java/org/apache/felix/bundleplugin/BundlePlugin.java <ide> import org.apache.maven.plugin.logging.Log; <ide> import org.apache.maven.project.MavenProject; <ide> import org.apache.maven.project.MavenProjectHelper; <add>import org.apache.maven.shared.osgi.DefaultMaven2OsgiConverter; <ide> import org.apache.maven.shared.osgi.Maven2OsgiConverter; <ide> import org.codehaus.plexus.archiver.UnArchiver; <ide> import org.codehaus.plexus.archiver.manager.ArchiverManager; <ide> private Map instructions = new HashMap(); <ide> <ide> /** <del> * @component <del> */ <del> private Maven2OsgiConverter m_maven2OsgiConverter; <add> * Use locally patched version for now. <add> */ <add> private Maven2OsgiConverter m_maven2OsgiConverter = new DefaultMaven2OsgiConverter(); <ide> <ide> /** <ide> * The archive configuration to use.
JavaScript
mit
202d1ae773d682cb0a5c2350e06f6414552f9780
0
tinovyatkin/stylelint-config-amp
module.exports = { "rules": { "declaration-no-important": true, "keyframe-declaration-no-important": true, "selector-no-universal": true, "selector-pseudo-class-blacklist": "not", "selector-no-type": [ true, { ignoreTypes: /^((?!^i-amp-).)*$/gm } ], "selector-class-pattern": "^((?!^-amp-).)*$", "property-blacklist": [ "behavior", "-moz-binding", "filter" ], "declaration-property-value-whitelist": { "transition": [ "/opacity/", "/transform/" ], }, }, }
index.js
module.exports = { "rules": { "declaration-no-important": true, "selector-no-universal": true, "selector-pseudo-class-blacklist": "not", "selector-no-type": [ true, { ignoreTypes: /^((?!^i-amp-).)*$/gm } ], // "selector-class-pattern": /^((?!^-amp-).)*$/gm, "property-blacklist": [ "behavior", "-moz-binding", "filter" ], "declaration-property-value-whitelist": { "transition": [ "/opacity/", "/transform/" ], }, }, }
Workaround regex error at stylelint
index.js
Workaround regex error at stylelint
<ide><path>ndex.js <ide> module.exports = { <ide> "rules": { <ide> "declaration-no-important": true, <add> "keyframe-declaration-no-important": true, <ide> "selector-no-universal": true, <ide> "selector-pseudo-class-blacklist": "not", <ide> "selector-no-type": [ true, { ignoreTypes: /^((?!^i-amp-).)*$/gm } ], <del> // "selector-class-pattern": /^((?!^-amp-).)*$/gm, <add> "selector-class-pattern": "^((?!^-amp-).)*$", <ide> "property-blacklist": [ "behavior", "-moz-binding", "filter" ], <ide> "declaration-property-value-whitelist": { <ide> "transition": [ "/opacity/", "/transform/" ],
Java
apache-2.0
ac79c031a525b9c23ad68b723977e07cf5678170
0
YzPaul3/h2o-3,spennihana/h2o-3,YzPaul3/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,YzPaul3/h2o-3,pchmieli/h2o-3,madmax983/h2o-3,madmax983/h2o-3,mathemage/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,YzPaul3/h2o-3,h2oai/h2o-dev,madmax983/h2o-3,jangorecki/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,YzPaul3/h2o-3,jangorecki/h2o-3,jangorecki/h2o-3,spennihana/h2o-3,pchmieli/h2o-3,madmax983/h2o-3,pchmieli/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,h2oai/h2o-dev,mathemage/h2o-3,pchmieli/h2o-3,mathemage/h2o-3,michalkurka/h2o-3,spennihana/h2o-3,madmax983/h2o-3,mathemage/h2o-3,mathemage/h2o-3,pchmieli/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,spennihana/h2o-3,jangorecki/h2o-3,pchmieli/h2o-3,spennihana/h2o-3,jangorecki/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,mathemage/h2o-3,YzPaul3/h2o-3,michalkurka/h2o-3,madmax983/h2o-3,jangorecki/h2o-3,jangorecki/h2o-3,michalkurka/h2o-3,YzPaul3/h2o-3,h2oai/h2o-3,h2oai/h2o-3,pchmieli/h2o-3,madmax983/h2o-3,spennihana/h2o-3,spennihana/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,mathemage/h2o-3
package water.api; import com.google.code.regexp.Matcher; import com.google.code.regexp.Pattern; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.ServerSocket; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.LinkedHashMap; import java.util.Properties; import java.util.concurrent.atomic.AtomicLong; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import water.DKV; import water.H2O; import water.H2OError; import water.H2OModelBuilderError; import water.H2ONode; import water.HeartBeatThread; import water.NanoHTTPD; import water.exceptions.H2OAbstractRuntimeException; import water.exceptions.H2OFailException; import water.exceptions.H2OIllegalArgumentException; import water.exceptions.H2OModelBuilderIllegalArgumentException; import water.exceptions.H2ONotFoundArgumentException; import water.fvec.Frame; import water.init.NodePersistentStorage; import water.nbhm.NonBlockingHashMap; import water.rapids.Assembly; import water.util.GAUtils; import water.util.GetLogsFromNode; import water.util.HttpResponseStatus; import water.util.JCodeGen; import water.util.Log; import water.util.PojoUtils; /** * This is a simple web server which accepts HTTP requests and routes them * to methods in Handler classes for processing. Schema classes are used to * provide a more stable external JSON interface while allowing the implementation * to evolve rapidly. As part of request handling the framework translates * back and forth between the stable external representation of objects (Schema) * and the less stable internal classes. * <p> * Request <i>routing</i> is done by searching a list of registered * handlers, in order of registration, for a handler whose path regex matches * the request URI and whose HTTP method (GET, POST, DELETE...) matches the * request's method. If none is found an HTTP 404 is returned. * <p> * A Handler class is parameterized by the kind of Schema that it accepts * for request handling, as well as the internal implementation class (Iced * class) that the Schema translates from and to. Handler methods are allowed to * return other Schema types than in the type parameter if that makes * sense for a given request. For example, a prediction (scoring) call on * a Model might return a Frame schema. * <p> * When an HTTP request is accepted the framework does the following steps: * <ol> * <li>searches the registered handler methods for a matching URL and HTTP method</li> * <li>collects any parameters which are captured from the URI and adds them to the map of HTTP query parameters</li> * <li>creates an instance of the correct Handler class and calls handle() on it, passing the version, route and params</li> * <li>Handler.handle() creates the correct Schema object given the version and calls fillFromParms(params) on it</li> * <li>calls schema.createImpl() to create a schema-independent "back end" object</li> * <li>dispatches to the handler method, passing in the schema-independent impl object and returning the result Schema object</li> * </ol> * * @see water.api.Handler a class which contains HTTP request handler methods and other helpers * @see water.api.Schema a class which provides a stable external representation for entities and request parameters * @see #register(String, String, Class, String, String, String) registers a specific handler method for the supplied URI pattern and HTTP method (GET, POST, DELETE, PUT) */ public class RequestServer extends NanoHTTPD { // Returned in REST API responses as X-h2o-rest-api-version public static final int H2O_REST_API_VERSION = 3; static public RequestServer SERVER; private RequestServer() {} private RequestServer( ServerSocket socket ) throws IOException { super(socket,null); } // Handlers ------------------------------------------------------------ // An array of regexs-over-URLs and handling Methods. // The list is searched in-order, first match gets dispatched. private static final LinkedHashMap<java.util.regex.Pattern,Route> _routes = new LinkedHashMap<>(); // explicit routes registered below private static final LinkedHashMap<java.util.regex.Pattern,Route> _fallbacks= new LinkedHashMap<>(); // routes that are version fallbacks (e.g., we asked for v5 but v2 is the latest) public static final int numRoutes() { return _routes.size(); } public static final Collection<Route> routes() { return _routes.values(); } private static Pattern version_pattern = null; private static Pattern getVersionPattern() { if (null == version_pattern) version_pattern = Pattern.compile("^/(\\d+|EXPERIMENTAL)/(.*)"); return version_pattern; } // NOTE! // URL patterns are searched in order. If you have two patterns that can match on the same URL // (e.g., /foo/baz and /foo) you MUST register them in decreasing order of specificity. static { // Data // TODO: ImportFiles should be a POST! register("/3/CreateFrame","POST",CreateFrameHandler.class,"run" , null,"Create a synthetic H2O Frame."); register("/3/SplitFrame" ,"POST",SplitFrameHandler.class,"run" , null,"Split a H2O Frame."); register("/3/Interaction","POST",InteractionHandler.class,"run" , null,"Create interactions between categorical columns."); register("/3/MissingInserter" ,"POST",MissingInserterHandler.class,"run", null,"Insert missing values."); register("/99/DCTTransformer" ,"POST",DCTTransformerHandler.class,"run" , null,"Row-by-Row discrete cosine transforms in 1D, 2D and 3D."); register("/99/Tabulate" ,"POST",TabulateHandler.class,"run", null,"Tabulate one column vs another."); register("/3/ImportFiles","GET",ImportFilesHandler.class,"importFiles" , null,"Import raw data files into a single-column H2O Frame."); register("/3/ImportFiles","POST",ImportFilesHandler.class,"importFiles" , null,"Import raw data files into a single-column H2O Frame."); register("/3/ParseSetup" ,"POST",ParseSetupHandler.class,"guessSetup" , null,"Guess the parameters for parsing raw byte-oriented data into an H2O Frame."); register("/3/Parse" ,"POST",ParseHandler .class,"parse" , null,"Parse a raw byte-oriented Frame into a useful columnar data Frame."); // NOTE: prefer POST due to higher content limits // Admin register("/3/Cloud", "GET", CloudHandler.class, "status", null, "Determine the status of the nodes in the H2O cloud."); register("/3/Cloud", "HEAD",CloudHandler.class, "head", null, "Determine the status of the nodes in the H2O cloud."); register("/3/Jobs" ,"GET", JobsHandler.class, "list", null, "Get a list of all the H2O Jobs (long-running actions)."); register("/3/Timeline" ,"GET",TimelineHandler .class,"fetch" , null,"Show a time line."); register("/3/Profiler" ,"GET",ProfilerHandler .class,"fetch" , null,"Report real-time profiling information for all nodes (sorted, aggregated stack traces)."); register("/3/JStack" ,"GET",JStackHandler .class,"fetch" , null,"Report stack traces for all threads on all nodes."); register("/3/NetworkTest","GET",NetworkTestHandler.class,"fetch" , null,"Run a network test to measure the performance of the cluster interconnect."); register("/3/UnlockKeys", "POST", UnlockKeysHandler.class, "unlock", null, "Unlock all keys in the H2O distributed K/V store, to attempt to recover from a crash."); register("/3/Shutdown" ,"POST",ShutdownHandler .class,"shutdown" , null,"Shut down the cluster"); // REST only, no html: register("/3/About" ,"GET" ,AboutHandler.class, "get", null, "Return information about this H2O cluster."); register("/3/Metadata/endpoints/(?<num>[0-9]+)" ,"GET" ,MetadataHandler.class, "fetchRoute", null, "Return the REST API endpoint metadata, including documentation, for the endpoint specified by number."); register("/3/Metadata/endpoints/(?<path>.*)" ,"GET" ,MetadataHandler.class, "fetchRoute", null, "Return the REST API endpoint metadata, including documentation, for the endpoint specified by path."); register("/3/Metadata/endpoints" ,"GET" ,MetadataHandler.class, "listRoutes", null, "Return a list of all the REST API endpoints."); register("/3/Metadata/schemaclasses/(?<classname>.*)" ,"GET" ,MetadataHandler.class, "fetchSchemaMetadataByClass", null, "Return the REST API schema metadata for specified schema class."); register("/3/Metadata/schemas/(?<schemaname>.*)" ,"GET" ,MetadataHandler.class, "fetchSchemaMetadata", null, "Return the REST API schema metadata for specified schema."); register("/3/Metadata/schemas" ,"GET" ,MetadataHandler.class, "listSchemas", null, "Return list of all REST API schemas."); register("/3/Typeahead/files" ,"GET",TypeaheadHandler.class, "files", null, "Typehead hander for filename completion."); register("/3/Jobs/(?<job_id>.*)" ,"GET",JobsHandler .class, "fetch", null, "Get the status of the given H2O Job (long-running action)."); register("/3/Jobs/(?<job_id>.*)/cancel" ,"POST",JobsHandler .class, "cancel", null, "Cancel a running job."); register("/3/Find" ,"GET" ,FindHandler.class, "find", null, "Find a value within a Frame."); // TODO: add a DEPRECATED flag, and make this next one DEPRECATED register("/3/Frames/(?<frame_id>.*)/export/(?<path>.*)/overwrite/(?<force>.*)" ,"GET", FramesHandler.class, "export", null, "Export a Frame to the given path with optional overwrite."); register("/3/Frames/(?<frame_id>.*)/export" ,"POST", FramesHandler.class, "export", null, "Export a Frame to the given path with optional overwrite."); register("/3/Frames/(?<frame_id>.*)/columns/(?<column>.*)/summary","GET" ,FramesHandler.class, "columnSummary", "columnSummaryDocs", "Return the summary metrics for a column, e.g. mins, maxes, mean, sigma, percentiles, etc."); register("/3/Frames/(?<frame_id>.*)/columns/(?<column>.*)/domain" ,"GET" ,FramesHandler.class, "columnDomain", null, "Return the domains for the specified column. \"null\" if the column is not a categorical."); register("/3/Frames/(?<frame_id>.*)/columns/(?<column>.*)" ,"GET" ,FramesHandler.class, "column", null, "Return the specified column from a Frame."); register("/3/Frames/(?<frame_id>.*)/columns" ,"GET" ,FramesHandler.class, "columns", null, "Return all the columns from a Frame."); register("/3/Frames/(?<frame_id>.*)/summary" ,"GET" ,FramesHandler.class, "summary", null, "Return a Frame, including the histograms, after forcing computation of rollups."); register("/3/Frames/(?<frame_id>.*)" ,"GET" ,FramesHandler.class, "fetch", null, "Return the specified Frame."); register("/3/Frames" ,"GET" ,FramesHandler.class, "list", null, "Return all Frames in the H2O distributed K/V store."); register("/3/Frames/(?<frame_id>.*)" ,"DELETE",FramesHandler.class, "delete", null, "Delete the specified Frame from the H2O distributed K/V store."); register("/3/Frames" ,"DELETE",FramesHandler.class, "deleteAll", null, "Delete all Frames from the H2O distributed K/V store."); // Handle models register("/3/Models/(?<model_id>.*)" ,"GET" ,ModelsHandler.class, "fetch", null, "Return the specified Model from the H2O distributed K/V store, optionally with the list of compatible Frames."); register("/3/Models" ,"GET" ,ModelsHandler.class, "list", null, "Return all Models from the H2O distributed K/V store."); register("/3/Models/(?<model_id>.*)" ,"DELETE",ModelsHandler.class, "delete", null, "Delete the specified Model from the H2O distributed K/V store."); register("/3/Models" ,"DELETE",ModelsHandler.class, "deleteAll", null, "Delete all Models from the H2O distributed K/V store."); // Get java code for models as register("/3/Models.java/(?<model_id>.*)/preview" ,"GET" ,ModelsHandler.class, "fetchPreview", null, "Return potentially abridged model suitable for viewing in a browser (currently only used for java model code)."); // Register resource also with .java suffix since we do not want to break API // FIXME: remove in new REST API version register("/3/Models.java/(?<model_id>.*)" ,"GET" ,ModelsHandler.class, "fetchJavaCode", null, "Return the stream containing model implementation in Java code."); // Model serialization - import/export calls register("/99/Models.bin/(?<model_id>.*)" ,"POST" ,ModelsHandler.class, "importModel", null, "Import given binary model into H2O."); register("/99/Models.bin/(?<model_id>.*)" ,"GET" ,ModelsHandler.class, "exportModel", null, "Export given model."); // register("/3/Frames/(?<frame_id>.*)/export/(?<path>.*)/overwrite/(?<force>.*)" ,"GET", FramesHandler.class, "export", null, // "Export a Frame to the given path with optional overwrite."); register("/99/Grids/(?<grid_id>.*)" ,"GET" ,GridsHandler.class, "fetch", null, "Return the specified grid search result."); register("/99/Grids" ,"GET" ,GridsHandler.class, "list", null, "Return all grids from H2O distributed K/V store."); register("/3/Configuration/ModelBuilders/visibility" ,"POST" ,ModelBuildersHandler.class, "setVisibility", null, "Set Model Builders visibility level."); register("/3/Configuration/ModelBuilders/visibility" ,"GET" ,ModelBuildersHandler.class, "getVisibility", null, "Get Model Builders visibility level."); register("/3/ModelBuilders/(?<algo>.*)/model_id" ,"POST" ,ModelBuildersHandler.class, "calcModelId", null, "Return a new unique model_id for the specified algorithm."); register("/3/ModelBuilders/(?<algo>.*)" ,"GET" ,ModelBuildersHandler.class, "fetch", null, "Return the Model Builder metadata for the specified algorithm."); register("/3/ModelBuilders" ,"GET" ,ModelBuildersHandler.class, "list", null, "Return the Model Builder metadata for all available algorithms."); // TODO: filtering isn't working for these first four; we get all results: register("/3/ModelMetrics/models/(?<model>.*)/frames/(?<frame>.*)" ,"GET" ,ModelMetricsHandler.class, "fetch", null, "Return the saved scoring metrics for the specified Model and Frame."); register("/3/ModelMetrics/models/(?<model>.*)/frames/(?<frame>.*)" ,"DELETE",ModelMetricsHandler.class, "delete", null, "Return the saved scoring metrics for the specified Model and Frame."); register("/3/ModelMetrics/models/(?<model>.*)" ,"GET" ,ModelMetricsHandler.class, "fetch", null, "Return the saved scoring metrics for the specified Model."); register("/3/ModelMetrics/frames/(?<frame>.*)/models/(?<model>.*)" ,"GET" ,ModelMetricsHandler.class, "fetch", null, "Return the saved scoring metrics for the specified Model and Frame."); register("/3/ModelMetrics/frames/(?<frame>.*)/models/(?<model>.*)" ,"DELETE",ModelMetricsHandler.class, "delete", null, "Return the saved scoring metrics for the specified Model and Frame."); register("/3/ModelMetrics/frames/(?<frame>.*)" ,"GET" ,ModelMetricsHandler.class, "fetch", null, "Return the saved scoring metrics for the specified Frame."); register("/3/ModelMetrics" ,"GET" ,ModelMetricsHandler.class, "fetch", null, "Return all the saved scoring metrics."); register("/3/ModelMetrics/models/(?<model>.*)/frames/(?<frame>.*)" ,"POST" ,ModelMetricsHandler.class, "score", null, "Return the scoring metrics for the specified Frame with the specified Model. If the Frame has already been scored with the Model then cached results will be returned; otherwise predictions for all rows in the Frame will be generated and the metrics will be returned."); register("/3/Predictions/models/(?<model>.*)/frames/(?<frame>.*)" ,"POST" ,ModelMetricsHandler.class, "predict", null, "Score (generate predictions) for the specified Frame with the specified Model. Both the Frame of predictions and the metrics will be returned."); register("/3/WaterMeterCpuTicks/(?<nodeidx>.*)" ,"GET" ,WaterMeterCpuTicksHandler.class, "fetch", null, "Return a CPU usage snapshot of all cores of all nodes in the H2O cluster."); register("/3/WaterMeterIo/(?<nodeidx>.*)" ,"GET" ,WaterMeterIoHandler.class, "fetch", null, "Return IO usage snapshot of all nodes in the H2O cluster."); register("/3/WaterMeterIo" ,"GET" ,WaterMeterIoHandler.class, "fetch_all", null, "Return IO usage snapshot of all nodes in the H2O cluster."); // Node persistent storage register("/3/NodePersistentStorage/categories/(?<category>.*)/names/(?<name>.*)/exists", "GET", NodePersistentStorageHandler.class, "exists", null, "Return true or false."); register("/3/NodePersistentStorage/categories/(?<category>.*)/exists", "GET" ,NodePersistentStorageHandler.class, "exists", null, "Return true or false."); register("/3/NodePersistentStorage/configured", "GET" ,NodePersistentStorageHandler.class, "configured", null, "Return true or false."); register("/3/NodePersistentStorage/(?<category>.*)/(?<name>.*)" ,"POST" ,NodePersistentStorageHandler.class, "put_with_name", null, "Store a named value."); register("/3/NodePersistentStorage/(?<category>.*)/(?<name>.*)" ,"GET" ,NodePersistentStorageHandler.class, "get_as_string", null, "Return value for a given name."); register("/3/NodePersistentStorage/(?<category>.*)/(?<name>.*)" ,"DELETE",NodePersistentStorageHandler.class, "delete", null, "Delete a key."); register("/3/NodePersistentStorage/(?<category>.*)" ,"POST" ,NodePersistentStorageHandler.class, "put", null, "Store a value."); register("/3/NodePersistentStorage/(?<category>.*)" ,"GET" ,NodePersistentStorageHandler.class, "list", null, "Return all keys stored for a given category."); // TODO: register("/3/ModelMetrics/models/(?<model>.*)/frames/(?<frame>.*)" ,"DELETE",ModelMetricsHandler.class, "delete"); // TODO: register("/3/ModelMetrics/frames/(?<frame>.*)/models/(?<model>.*)" ,"DELETE",ModelMetricsHandler.class, "delete"); // TODO: register("/3/ModelMetrics/frames/(?<frame>.*)" ,"DELETE",ModelMetricsHandler.class, "delete"); // TODO: register("/3/ModelMetrics/models/(?<model>.*)" ,"DELETE",ModelMetricsHandler.class, "delete"); // TODO: register("/3/ModelMetrics" ,"DELETE",ModelMetricsHandler.class, "delete"); // TODO: register("/3/Predictions/models/(?<model>.*)/frames/(?<frame>.*)" ,"POST" ,ModelMetricsHandler.class, "predict"); // Log file management. // Note: Hacky pre-route cutout of "/3/Logs/download" is done above in a non-json way. register("/3/Logs/nodes/(?<nodeidx>.*)/files/(?<name>.*)", "GET", LogsHandler.class, "fetch", null, "Get named log file for a node."); // ModelBuilder Handler registration must be done for each algo in the application class // (e.g., H2OApp), because the Handler class is parameterized by the associated Schema, // and this is different for each ModelBuilder in order to handle its parameters in a // typesafe way: // // register("/2/ModelBuilders/(?<algo>.*)" ,"POST" ,ModelBuildersHandler.class, "train", new String[] {"algo"}); register("/3/KillMinus3" ,"GET" ,KillMinus3Handler.class, "killm3", null, "Kill minus 3 on *this* node"); register("/99/Rapids" ,"POST" ,RapidsHandler.class, "exec", null, "Execute an Rapids AST."); register("/99/Assembly.java/(?<assembly_id>.*)/(?<pojo_name>.*)" ,"GET" ,AssemblyHandler.class, "toJava", null, "Generate a Java POJO from the Assembly"); register("/99/Assembly" ,"POST" ,AssemblyHandler.class, "fit", null, "Fit an assembly to an input frame"); register("/3/DownloadDataset" ,"GET" ,DownloadDataHandler.class, "fetch", null, "Download something something."); register("/3/DownloadDataset.bin" ,"GET" ,DownloadDataHandler.class, "fetchStreaming", null, "Download something something via streaming response"); register("/3/DKV/(?<key>.*)" ,"DELETE",RemoveHandler.class, "remove", null, "Remove an arbitrary key from the H2O distributed K/V store."); register("/3/DKV" ,"DELETE",RemoveAllHandler.class, "remove", null, "Remove all keys from the H2O distributed K/V store."); register("/3/LogAndEcho" ,"POST" ,LogAndEchoHandler.class, "echo", null, "Save a message to the H2O logfile."); register("/3/InitID" ,"GET" ,InitIDHandler.class, "issue", null, "Issue a new session ID."); register("/3/GarbageCollect" ,"POST" ,GarbageCollectHandler.class, "gc", null, "Explicitly call System.gc()."); register("/99/Sample" ,"GET",CloudHandler .class,"status" , null,"Example of an experimental endpoint. Call via /EXPERIMENTAL/Sample. Experimental endpoints can change at any moment."); } /** * Register an HTTP request handler method for a given URL pattern, with parameters extracted from the URI. * <p> * URIs which match this pattern will have their parameters collected from the path and from the query params * * @param uri_pattern_raw regular expression which matches the URL path for this request handler; parameters that are embedded in the path must be captured with &lt;code&gt;(?&lt;parm&gt;.*)&lt;/code&gt; syntax * @param http_method HTTP verb (GET, POST, DELETE) this handler will accept * @param handler_class class which contains the handler method * @param handler_method name of the handler method * @param doc_method name of a method which returns GitHub Flavored Markdown documentation for the request * @param summary short help string which summarizes the functionality of this endpoint * @see Route * @see water.api.RequestServer * @return the Route for this request */ public static Route register(String uri_pattern_raw, String http_method, Class<? extends Handler> handler_class, String handler_method, String doc_method, String summary) { return register(uri_pattern_raw, http_method, handler_class, handler_method, doc_method, summary, HandlerFactory.DEFAULT); } /** * Register an HTTP request handler method for a given URL pattern, with parameters extracted from the URI. * <p> * URIs which match this pattern will have their parameters collected from the path and from the query params * * @param uri_pattern_raw regular expression which matches the URL path for this request handler; parameters that are embedded in the path must be captured with &lt;code&gt;(?&lt;parm&gt;.*)&lt;/code&gt; syntax * @param http_method HTTP verb (GET, POST, DELETE) this handler will accept * @param handler_class class which contains the handler method * @param handler_method name of the handler method * @param doc_method name of a method which returns GitHub Flavored Markdown documentation for the request * @param summary short help string which summarizes the functionality of this endpoint * @param handler_factory factory to create instance of handler * @see Route * @see water.api.RequestServer * @return the Route for this request */ public static Route register(String uri_pattern_raw, String http_method, Class<? extends Handler> handler_class, String handler_method, String doc_method, String summary, HandlerFactory handler_factory) { assert uri_pattern_raw.startsWith("/"); // Search handler_class and all its superclasses for the method. Method meth = null; Method doc_meth = null; // TODO: move to ReflectionUtils: try { for (Method m : handler_class.getMethods()) { if (! m.getName().equals(handler_method)) continue; Class[] params = m.getParameterTypes(); if (null == params || params.length != 2) continue; if (params[0] != Integer.TYPE) continue; if (! Schema.class.isAssignableFrom(params[1])) continue; meth = m; break; } if (null != doc_method) doc_meth = handler_class.getMethod(doc_method, new Class[]{int.class, StringBuffer.class}); } catch (NoSuchMethodException e) { // ignore: H2O.fail below } if (null == meth) throw H2O.fail("Failed to find handler method: " + handler_method + " for handler class: " + handler_class); if (null != doc_method && null == doc_meth) throw H2O.fail("Failed to find doc method: " + doc_method + " for handler class: " + handler_class); if (! "/".equals(uri_pattern_raw)) { Matcher m = getVersionPattern().matcher(uri_pattern_raw); if (!m.matches()) throw H2O.fail("Route URL pattern must begin with a version: " + uri_pattern_raw); int version = Integer.valueOf(m.group(1)); if (version > Schema.getHighestSupportedVersion() && version != Schema.getExperimentalVersion()) throw H2O.fail("Route version is greater than the max supported of: " + Schema.getHighestSupportedVersion() + ": " + uri_pattern_raw); } // Get the group names in the uri pattern and remove any underscores, // since underscores are not actually allowed in java regex group names. String group_pattern_raw = "\\?<([\\p{Alnum}_]+)>"; ArrayList<String> params_list = new ArrayList<String>(); Pattern group_pattern = Pattern.compile(group_pattern_raw); Matcher group_matcher = group_pattern.matcher(uri_pattern_raw); StringBuffer new_uri_buffer = new StringBuffer(); while (group_matcher.find()) { String group = group_matcher.group(1); params_list.add(group); group_matcher.appendReplacement(new_uri_buffer, "?<" + group.replace("_", "") + ">"); } group_matcher.appendTail(new_uri_buffer); uri_pattern_raw = new_uri_buffer.toString(); assert lookup(handler_method, uri_pattern_raw)==null; // Not shadowed Pattern uri_pattern = Pattern.compile(uri_pattern_raw); Route route = new Route(http_method, uri_pattern_raw, uri_pattern, summary, handler_class, meth, doc_meth, params_list.toArray(new String[params_list.size()]), handler_factory); _routes.put(uri_pattern.pattern(), route); return route; } // Lookup the method/url in the register list, and return a matching Method protected static Route lookup( String http_method, String uri ) { if (null == http_method || null == uri) return null; // Search the explicitly registered routes: for( Route r : _routes.values() ) if (r._url_pattern.matcher(uri).matches()) if (http_method.equals(r._http_method)) return r; // Search the fallbacks cache: for( Route r : _fallbacks.values() ) if (r._url_pattern.matcher(uri).matches()) if (http_method.equals(r._http_method)) return r; // Didn't find a registered route and didn't find a cached fallback, so do a backward version search and cache if we find a match: Matcher m = getVersionPattern().matcher(uri); if (! m.matches()) return null; // Ok then. . . Try to fall back to a previous version. int version = Integer.valueOf(m.group(1)); if (version == Route.MIN_VERSION) return null; // don't go any lower String lower_uri = "/" + (version - 1) + "/" + m.group(2); Route fallback = lookup(http_method, lower_uri); if (null == fallback) return null; // Store the route fallback for later. Matcher route_m = version_pattern.matcher(fallback._url_pattern_raw); if (! route_m.matches()) throw H2O.fail("Found a fallback route that doesn't have a version: " + fallback); // register fallbacks for all the versions <= the one in URI we were originally given and > the one in the fallback route: int route_version = Integer.valueOf(route_m.group(1)); for (int i = version; i > route_version && i >= Route.MIN_VERSION; i--) { String fallback_route_uri = "/" + i + "/" + route_m.group(2); Pattern fallback_route_pattern = Pattern.compile(fallback_route_uri); Route generated = new Route(fallback._http_method, fallback_route_uri, fallback_route_pattern, fallback._summary, fallback._handler_class, fallback._handler_method, fallback._doc_method, fallback._path_params, fallback._handler_factory); _fallbacks.put(fallback_route_pattern.pattern(), generated); } // Better be there in the _fallbacks cache now! return lookup(http_method, uri); } public static void finalizeRegistration() { Schema.registerAllSchemasIfNecessary(); // Need a stub RequestServer to handle calls to serve() from Jetty. // But no threads are started here anymore. SERVER = new RequestServer(); H2O.getJetty().acceptRequests(); } public static void alwaysLogRequest(String uri, String method, Properties parms) { // This is never called anymore. throw H2O.fail(); } // Log all requests except the overly common ones boolean maybeLogRequest(String method, String uri, String pattern, Properties parms, Properties header) { if (uri.endsWith(".css") || uri.endsWith(".js") || uri.endsWith(".png") || uri.endsWith(".ico")) return false; if (uri.contains("/Cloud") || (uri.contains("/Jobs") && method.equals("GET")) || uri.contains("/Log") || uri.contains("/Progress") || uri.contains("/Typeahead") || uri.contains("/WaterMeterCpuTicks")) return false; String paddedMethod = String.format("%-6s", method); Log.info("Method: " + paddedMethod, ", URI: " + uri + ", route: " + pattern + ", parms: " + parms); return true; } private void capturePathParms(Properties parms, String path, Route route) { Matcher m = route._url_pattern.matcher(path); if (! m.matches()) { throw H2O.fail("Routing regex error: Pattern matched once but not again for pattern: " + route._url_pattern.pattern() + " and path: " + path); } // Java doesn't allow _ in group names but we want them in field names, so remove all _ from the path params before we look up the group capture value for (String key : route._path_params) { String key_no_underscore = key.replace("_",""); String val; try { val = m.group(key_no_underscore); } catch (IllegalArgumentException e) { throw H2O.fail("Missing request parameter in the URL: did not find " + key + " in the URL as expected; URL pattern: " + route._url_pattern.pattern() + " with expected parameters: " + Arrays.toString(route._path_params) + " for URL: " + path); } if (null != val) parms.put(key, val); } } private Response response404(String what, RequestType type) { H2ONotFoundArgumentException e = new H2ONotFoundArgumentException(what + " not found", what + " not found"); H2OError error = e.toH2OError(what); Log.warn(error._dev_msg); Log.warn(error._values.toJsonString()); Log.warn((Object[]) error._stacktrace); return wrap(new H2OErrorV3().fillFromImpl(error), type); } // Top-level dispatch based on the URI. Break down URI into parts; // e.g. /2/GBM.html/crunk?hex=some_hex breaks down into: // version: 2 // requestType: ".html" // path: "GBM/crunk" // parms: "{hex-->some_hex}" @Override public Response serve( String uri, String method, Properties header, Properties parms ) { // Jack priority for user-visible requests Thread.currentThread().setPriority(Thread.MAX_PRIORITY - 1); // determine version: if /LATEST then use the highest version of any schema (or the highest supported version, if we don't know yet). if (uri.startsWith("/LATEST")) { if (-1 == Schema.getLatestVersion()) { // Not yet initialized, and we might be in bootstrap uri = "/" + Schema.getHighestSupportedVersion() + uri.substring("/latest".length()); } else { uri = "/" + Schema.getLatestVersion() + uri.substring("/latest".length()); } } // determine the request type RequestType type = RequestType.requestType(uri); // Blank response used by R's uri.exists("/") if (uri.equals("/") && method.equals("HEAD")) { Response r = new Response(HTTP_OK, MIME_PLAINTEXT, ""); return r; } String versioned_path = uri; String path = uri; int version = 1; Matcher m = getVersionPattern().matcher(uri); if (m.matches()) { if ("EXPERIMENTAL".equals(m.group(1))) { version = 99; } else { version = Integer.valueOf(m.group(1)); } String uripath = "/" + m.group(2); path = type.requestName(uripath); // Strip suffix type from middle of URI versioned_path = "/" + version + path; } // Load resources, or dispatch on handled requests try { boolean logged; // Handle any URLs that bypass the route approach. This is stuff that has abnormal non-JSON response payloads. if (method.equals("GET") && uri.equals("/")) { logged = maybeLogRequest(method, uri, "", parms, header); if (logged) GAUtils.logRequest(uri, header); return redirectToFlow(); } if (method.equals("GET") && uri.endsWith("/Logs/download")) { logged = maybeLogRequest(method, uri, "", parms, header); if (logged) GAUtils.logRequest(uri, header); return downloadLogs(); } if (method.equals("GET")) { Pattern p2 = Pattern.compile(".*/NodePersistentStorage.bin/([^/]+)/([^/]+)"); Matcher m2 = p2.matcher(uri); boolean b2 = m2.matches(); if (b2) { String categoryName = m2.group(1); String keyName = m2.group(2); return downloadNps(categoryName, keyName); } } // Find handler for url Route route = lookup(method, versioned_path); // if the request is not known, treat as resource request, or 404 if not found if( route == null) { if (method.equals("GET")) { return getResource(type, uri); } else { return response404(method + " " + uri, type); } } else if(route._handler_class == water.api.DownloadDataHandler.class) { // DownloadDataHandler will throw H2ONotFoundException if the resource is not found return wrapDownloadData(HTTP_OK, handle(type, route, version, parms)); } else { capturePathParms(parms, versioned_path, route); // get any parameters like /Frames/<key> logged = maybeLogRequest(method, uri, route._url_pattern.namedPattern(), parms, header); if (logged) GAUtils.logRequest(uri, header); Schema s = handle(type, route, version, parms); PojoUtils.filterFields(s, (String)parms.get("_include_fields"), (String)parms.get("_exclude_fields")); Response r = wrap(s, type); return r; } } catch (H2OFailException e) { H2OError error = e.toH2OError(uri); Log.fatal("Caught exception (fatal to the cluster): " + error.toString()); // Note: don't use Schema.schema(version, error) because we have to work at bootstrap: H2O.fail(wrap(new H2OErrorV3().fillFromImpl(error), type).toString()); // unreachable, but the compiler doesn't know it: return null; } catch (H2OModelBuilderIllegalArgumentException e) { H2OModelBuilderError error = e.toH2OError(uri); Log.warn("Caught exception: " + error.toString()); // Note: don't use Schema.schema(version, error) because we have to work at bootstrap: return wrap(new H2OModelBuilderErrorV3().fillFromImpl(error), type); } catch (H2OAbstractRuntimeException e) { H2OError error = e.toH2OError(uri); Log.warn("Caught exception: " + error.toString()); // Note: don't use Schema.schema(version, error) because we have to work at bootstrap: return wrap(new H2OErrorV3().fillFromImpl(error), type); } // TODO: kill the server if someone called H2O.fail() catch( Exception e ) { // make sure that no Exception is ever thrown out from the request H2OError error = new H2OError(e, uri); // some special cases for which we return 400 because it's likely a problem with the client request: if (e instanceof IllegalArgumentException) error._http_status = HttpResponseStatus.BAD_REQUEST.getCode(); else if (e instanceof FileNotFoundException) error._http_status = HttpResponseStatus.BAD_REQUEST.getCode(); else if (e instanceof MalformedURLException) error._http_status = HttpResponseStatus.BAD_REQUEST.getCode(); Log.err("Caught exception: " + error.toString()); // Note: don't use Schema.schema(version, error) because we have to work at bootstrap: return wrap(new H2OErrorV3().fillFromImpl(error), type); } } // Handling ------------------------------------------------------------------ private Schema handle( RequestType type, Route route, int version, Properties parms ) throws Exception { switch( type ) { case html: // These request-types only dictate the response-type; case java: // the normal action is always done. case json: case xml: { Handler h = route._handler; return h.handle(version,route,parms); // Can throw any Exception the handler throws } case query: case help: default: throw H2O.unimpl("Unknown type: " + type.toString()); } } private Response wrap( Schema s, RequestType type ) { // Convert Schema to desired output flavor String http_response_header = H2OError.httpStatusHeader(HttpResponseStatus.OK.getCode()); // If we're given an http response code use it. if (s instanceof SpecifiesHttpResponseCode) { http_response_header = H2OError.httpStatusHeader(((SpecifiesHttpResponseCode) s).httpStatus()); } // If we've gotten an error always return the error as JSON if (s instanceof SpecifiesHttpResponseCode && HttpResponseStatus.OK.getCode() != ((SpecifiesHttpResponseCode) s).httpStatus()) { type = RequestType.json; } switch( type ) { case html: // return JSON for html requests case json: return new Response(http_response_header, MIME_JSON, s.toJsonString()); case xml: //return new Response(http_code, MIME_XML , new String(S.writeXML (new AutoBuffer()).buf())); throw H2O.unimpl("Unknown type: " + type.toString()); case java: if (s instanceof H2OErrorV3) { return new Response(http_response_header, MIME_JSON, s.toJsonString()); } if (s instanceof AssemblyV99) { Assembly ass = DKV.getGet(((AssemblyV99) s).assembly_id); Response r = new Response(http_response_header, MIME_DEFAULT_BINARY, ass.toJava(((AssemblyV99) s).pojo_name)); r.addHeader("Content-Disposition", "attachment; filename=\""+JCodeGen.toJavaId(((AssemblyV99) s).pojo_name)+".java\""); return r; } else if (s instanceof StreamingSchema) { StreamingSchema ss = (StreamingSchema) s; Response r = new StreamResponse(http_response_header, MIME_DEFAULT_BINARY, ss.getStreamWriter()); // Needed to make file name match class name r.addHeader("Content-Disposition", "attachment; filename=\"" + ss.getFilename() + "\""); return r; } else { throw new H2OIllegalArgumentException("Cannot generate java for type: " + s.getClass().getSimpleName()); } default: throw H2O.unimpl("Unknown type to wrap(): " + type); } } private Response wrapDownloadData(String http_code, Schema s) { DownloadDataV3 dd = (DownloadDataV3)s; Response res = new Response(http_code, MIME_DEFAULT_BINARY, dd.csv); res.addHeader("Content-Disposition", "filename=" + dd.filename); return res; } // Resource loading ---------------------------------------------------------- // cache of all loaded resources private static final NonBlockingHashMap<String,byte[]> _cache = new NonBlockingHashMap<>(); // Returns the response containing the given uri with the appropriate mime type. private Response getResource(RequestType request_type, String uri) { byte[] bytes = _cache.get(uri); if( bytes == null ) { // Try-with-resource try (InputStream resource = water.init.JarHash.getResource2(uri)) { if( resource != null ) { try { bytes = toByteArray(resource); } catch( IOException e ) { Log.err(e); } // PP 06-06-2014 Disable caching for now so that the browser // always gets the latest sources and assets when h2o-client is rebuilt. // TODO need to rethink caching behavior when h2o-dev is merged into h2o. // // if( bytes != null ) { // byte[] res = _cache.putIfAbsent(uri,bytes); // if( res != null ) bytes = res; // Racey update; take what is in the _cache //} // } } catch( IOException ignore ) { } } if( bytes == null || bytes.length == 0 ) // No resource found? return response404("Resource " + uri, request_type); String mime = MIME_DEFAULT_BINARY; if( uri.endsWith(".css") ) mime = "text/css"; else if( uri.endsWith(".html") ) mime = "text/html"; Response res = new Response(HTTP_OK,mime,new ByteArrayInputStream(bytes)); res.addHeader("Content-Length", Long.toString(bytes.length)); return res; } // Convenience utility private static byte[] toByteArray(InputStream is) throws IOException { try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { byte[] buffer = new byte[0x2000]; for( int len; (len = is.read(buffer)) != -1; ) os.write(buffer, 0, len); return os.toByteArray(); } } // Return URLs for things that want to appear Frame-inspection page static String[] frameChoices( int version, Frame fr ) { ArrayList<String> al = new ArrayList<>(); for( java.util.regex.Pattern p : _routes.keySet() ) { try { Method meth = _routes.get(p)._handler_method; Class clz0 = meth.getDeclaringClass(); Class<Handler> clz = (Class<Handler>)clz0; Handler h = clz.newInstance(); // TODO: we don't need to create new instances; handler is stateless } catch( InstantiationException | IllegalArgumentException | IllegalAccessException ignore ) { } } return al.toArray(new String[al.size()]); } // --------------------------------------------------------------------- // Download logs support // --------------------------------------------------------------------- private String getOutputLogStem() { String pattern = "yyyyMMdd_hhmmss"; SimpleDateFormat formatter = new SimpleDateFormat(pattern); String now = formatter.format(new Date()); return "h2ologs_" + now; } private byte[] zipLogs(byte[][] results, byte[] clientResult, String topDir) throws IOException { int l = 0; assert H2O.CLOUD._memary.length == results.length : "Unexpected change in the cloud!"; for (int i = 0; i<results.length;l+=results[i++].length); ByteArrayOutputStream baos = new ByteArrayOutputStream(l); // Add top-level directory. ZipOutputStream zos = new ZipOutputStream(baos); { ZipEntry zde = new ZipEntry (topDir + File.separator); zos.putNextEntry(zde); } try { // Add zip directory from each cloud member. for (int i =0; i<results.length; i++) { String filename = topDir + File.separator + "node" + i + "_" + H2O.CLOUD._memary[i].getIpPortString().replace(':', '_').replace('/', '_') + ".zip"; ZipEntry ze = new ZipEntry(filename); zos.putNextEntry(ze); zos.write(results[i]); zos.closeEntry(); } // Add zip directory from the client node. Name it 'driver' since that's what Sparking Water users see. if (clientResult != null) { String filename = topDir + File.separator + "driver.zip"; ZipEntry ze = new ZipEntry(filename); zos.putNextEntry(ze); zos.write(clientResult); zos.closeEntry(); } // Close the top-level directory. zos.closeEntry(); } finally { // Close the full zip file. zos.close(); } return baos.toByteArray(); } private Response downloadLogs() { Log.info("\nCollecting logs."); H2ONode[] members = H2O.CLOUD.members(); byte[][] perNodeZipByteArray = new byte[members.length][]; byte[] clientNodeByteArray = null; for (int i = 0; i < members.length; i++) { byte[] bytes; try { // Skip nodes that aren't healthy, since they are likely to cause the entire process to hang. boolean healthy = (System.currentTimeMillis() - members[i]._last_heard_from) < HeartBeatThread.TIMEOUT; if (healthy) { GetLogsFromNode g = new GetLogsFromNode(); g.nodeidx = i; g.doIt(); bytes = g.bytes; } else { bytes = "Node not healthy".getBytes(); } } catch (Exception e) { bytes = e.toString().getBytes(); } perNodeZipByteArray[i] = bytes; } if (H2O.ARGS.client) { byte[] bytes; try { GetLogsFromNode g = new GetLogsFromNode(); g.nodeidx = -1; g.doIt(); bytes = g.bytes; } catch (Exception e) { bytes = e.toString().getBytes(); } clientNodeByteArray = bytes; } String outputFileStem = getOutputLogStem(); byte[] finalZipByteArray; try { finalZipByteArray = zipLogs(perNodeZipByteArray, clientNodeByteArray, outputFileStem); } catch (Exception e) { finalZipByteArray = e.toString().getBytes(); } NanoHTTPD.Response res = new Response(NanoHTTPD.HTTP_OK,NanoHTTPD.MIME_DEFAULT_BINARY, new ByteArrayInputStream(finalZipByteArray)); res.addHeader("Content-Length", Long.toString(finalZipByteArray.length)); res.addHeader("Content-Disposition", "attachment; filename="+outputFileStem + ".zip"); return res; } // --------------------------------------------------------------------- // Download NPS support // --------------------------------------------------------------------- private Response downloadNps(String categoryName, String keyName) { NodePersistentStorage nps = H2O.getNPS(); AtomicLong length = new AtomicLong(); InputStream is = nps.get(categoryName, keyName, length); NanoHTTPD.Response res = new Response(NanoHTTPD.HTTP_OK, NanoHTTPD.MIME_DEFAULT_BINARY, is); res.addHeader("Content-Length", Long.toString(length.get())); res.addHeader("Content-Disposition", "attachment; filename="+keyName + ".flow"); return res; } private Response redirectToFlow() { StringBuilder sb = new StringBuilder(); NanoHTTPD.Response res = new Response(NanoHTTPD.HTTP_REDIRECT, NanoHTTPD.MIME_PLAINTEXT, sb.toString()); res.addHeader("Location", "/flow/index.html"); return res; } }
h2o-core/src/main/java/water/api/RequestServer.java
package water.api; import com.google.code.regexp.Matcher; import com.google.code.regexp.Pattern; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.ServerSocket; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.LinkedHashMap; import java.util.Properties; import java.util.concurrent.atomic.AtomicLong; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import water.DKV; import water.H2O; import water.H2OError; import water.H2OModelBuilderError; import water.H2ONode; import water.HeartBeatThread; import water.NanoHTTPD; import water.exceptions.H2OAbstractRuntimeException; import water.exceptions.H2OFailException; import water.exceptions.H2OIllegalArgumentException; import water.exceptions.H2OModelBuilderIllegalArgumentException; import water.exceptions.H2ONotFoundArgumentException; import water.fvec.Frame; import water.init.NodePersistentStorage; import water.nbhm.NonBlockingHashMap; import water.rapids.Assembly; import water.util.GAUtils; import water.util.GetLogsFromNode; import water.util.HttpResponseStatus; import water.util.JCodeGen; import water.util.Log; import water.util.PojoUtils; /** * This is a simple web server which accepts HTTP requests and routes them * to methods in Handler classes for processing. Schema classes are used to * provide a more stable external JSON interface while allowing the implementation * to evolve rapidly. As part of request handling the framework translates * back and forth between the stable external representation of objects (Schema) * and the less stable internal classes. * <p> * Request <i>routing</i> is done by searching a list of registered * handlers, in order of registration, for a handler whose path regex matches * the request URI and whose HTTP method (GET, POST, DELETE...) matches the * request's method. If none is found an HTTP 404 is returned. * <p> * A Handler class is parameterized by the kind of Schema that it accepts * for request handling, as well as the internal implementation class (Iced * class) that the Schema translates from and to. Handler methods are allowed to * return other Schema types than in the type parameter if that makes * sense for a given request. For example, a prediction (scoring) call on * a Model might return a Frame schema. * <p> * When an HTTP request is accepted the framework does the following steps: * <ol> * <li>searches the registered handler methods for a matching URL and HTTP method</li> * <li>collects any parameters which are captured from the URI and adds them to the map of HTTP query parameters</li> * <li>creates an instance of the correct Handler class and calls handle() on it, passing the version, route and params</li> * <li>Handler.handle() creates the correct Schema object given the version and calls fillFromParms(params) on it</li> * <li>calls schema.createImpl() to create a schema-independent "back end" object</li> * <li>dispatches to the handler method, passing in the schema-independent impl object and returning the result Schema object</li> * </ol> * * @see water.api.Handler a class which contains HTTP request handler methods and other helpers * @see water.api.Schema a class which provides a stable external representation for entities and request parameters * @see #register(String, String, Class, String, String, String) registers a specific handler method for the supplied URI pattern and HTTP method (GET, POST, DELETE, PUT) */ public class RequestServer extends NanoHTTPD { // Returned in REST API responses as X-h2o-rest-api-version public static final int H2O_REST_API_VERSION = 3; static public RequestServer SERVER; private RequestServer() {} private RequestServer( ServerSocket socket ) throws IOException { super(socket,null); } // Handlers ------------------------------------------------------------ // An array of regexs-over-URLs and handling Methods. // The list is searched in-order, first match gets dispatched. private static final LinkedHashMap<java.util.regex.Pattern,Route> _routes = new LinkedHashMap<>(); // explicit routes registered below private static final LinkedHashMap<java.util.regex.Pattern,Route> _fallbacks= new LinkedHashMap<>(); // routes that are version fallbacks (e.g., we asked for v5 but v2 is the latest) public static final int numRoutes() { return _routes.size(); } public static final Collection<Route> routes() { return _routes.values(); } private static Pattern version_pattern = null; private static Pattern getVersionPattern() { if (null == version_pattern) version_pattern = Pattern.compile("^/(\\d+|EXPERIMENTAL)/(.*)"); return version_pattern; } // NOTE! // URL patterns are searched in order. If you have two patterns that can match on the same URL // (e.g., /foo/baz and /foo) you MUST register them in decreasing order of specificity. static { // Data // TODO: ImportFiles should be a POST! register("/3/CreateFrame","POST",CreateFrameHandler.class,"run" , null,"Create a synthetic H2O Frame."); register("/3/SplitFrame" ,"POST",SplitFrameHandler.class,"run" , null,"Split a H2O Frame."); register("/3/Interaction","POST",InteractionHandler.class,"run" , null,"Create interactions between categorical columns."); register("/3/MissingInserter" ,"POST",MissingInserterHandler.class,"run", null,"Insert missing values."); register("/99/DCTTransformer" ,"POST",DCTTransformerHandler.class,"run" , null,"Row-by-Row discrete cosine transforms in 1D, 2D and 3D."); register("/99/Tabulate" ,"POST",TabulateHandler.class,"run", null,"Tabulate one column vs another."); register("/3/ImportFiles","GET",ImportFilesHandler.class,"importFiles" , null,"Import raw data files into a single-column H2O Frame."); register("/3/ImportFiles","POST",ImportFilesHandler.class,"importFiles" , null,"Import raw data files into a single-column H2O Frame."); register("/3/ParseSetup" ,"POST",ParseSetupHandler.class,"guessSetup" , null,"Guess the parameters for parsing raw byte-oriented data into an H2O Frame."); register("/3/Parse" ,"POST",ParseHandler .class,"parse" , null,"Parse a raw byte-oriented Frame into a useful columnar data Frame."); // NOTE: prefer POST due to higher content limits // Admin register("/3/Cloud", "GET", CloudHandler.class, "status", null, "Determine the status of the nodes in the H2O cloud."); register("/3/Cloud", "HEAD",CloudHandler.class, "head", null, "Determine the status of the nodes in the H2O cloud."); register("/3/Jobs" ,"GET", JobsHandler.class, "list", null, "Get a list of all the H2O Jobs (long-running actions)."); register("/3/Timeline" ,"GET",TimelineHandler .class,"fetch" , null,"Something something something."); register("/3/Profiler" ,"GET",ProfilerHandler .class,"fetch" , null,"Something something something."); register("/3/JStack" ,"GET",JStackHandler .class,"fetch" , null,"Something something something."); register("/3/NetworkTest","GET",NetworkTestHandler.class,"fetch" , null,"Something something something."); register("/3/UnlockKeys", "POST", UnlockKeysHandler.class, "unlock", null, "Unlock all keys in the H2O distributed K/V store, to attempt to recover from a crash."); register("/3/Shutdown" ,"POST",ShutdownHandler .class,"shutdown" , null,"Shut down the cluster"); // REST only, no html: register("/3/About" ,"GET" ,AboutHandler.class, "get", null, "Return information about this H2O cluster."); register("/3/Metadata/endpoints/(?<num>[0-9]+)" ,"GET" ,MetadataHandler.class, "fetchRoute", null, "Return the REST API endpoint metadata, including documentation, for the endpoint specified by number."); register("/3/Metadata/endpoints/(?<path>.*)" ,"GET" ,MetadataHandler.class, "fetchRoute", null, "Return the REST API endpoint metadata, including documentation, for the endpoint specified by path."); register("/3/Metadata/endpoints" ,"GET" ,MetadataHandler.class, "listRoutes", null, "Return a list of all the REST API endpoints."); register("/3/Metadata/schemaclasses/(?<classname>.*)" ,"GET" ,MetadataHandler.class, "fetchSchemaMetadataByClass", null, "Return the REST API schema metadata for specified schema class."); register("/3/Metadata/schemas/(?<schemaname>.*)" ,"GET" ,MetadataHandler.class, "fetchSchemaMetadata", null, "Return the REST API schema metadata for specified schema."); register("/3/Metadata/schemas" ,"GET" ,MetadataHandler.class, "listSchemas", null, "Return list of all REST API schemas."); register("/3/Typeahead/files" ,"GET",TypeaheadHandler.class, "files", null, "Typehead hander for filename completion."); register("/3/Jobs/(?<job_id>.*)" ,"GET",JobsHandler .class, "fetch", null, "Get the status of the given H2O Job (long-running action)."); register("/3/Jobs/(?<job_id>.*)/cancel" ,"POST",JobsHandler .class, "cancel", null, "Cancel a running job."); register("/3/Find" ,"GET" ,FindHandler.class, "find", null, "Find a value within a Frame."); // TODO: add a DEPRECATED flag, and make this next one DEPRECATED register("/3/Frames/(?<frame_id>.*)/export/(?<path>.*)/overwrite/(?<force>.*)" ,"GET", FramesHandler.class, "export", null, "Export a Frame to the given path with optional overwrite."); register("/3/Frames/(?<frame_id>.*)/export" ,"POST", FramesHandler.class, "export", null, "Export a Frame to the given path with optional overwrite."); register("/3/Frames/(?<frame_id>.*)/columns/(?<column>.*)/summary","GET" ,FramesHandler.class, "columnSummary", "columnSummaryDocs", "Return the summary metrics for a column, e.g. mins, maxes, mean, sigma, percentiles, etc."); register("/3/Frames/(?<frame_id>.*)/columns/(?<column>.*)/domain" ,"GET" ,FramesHandler.class, "columnDomain", null, "Return the domains for the specified column. \"null\" if the column is not a categorical."); register("/3/Frames/(?<frame_id>.*)/columns/(?<column>.*)" ,"GET" ,FramesHandler.class, "column", null, "Return the specified column from a Frame."); register("/3/Frames/(?<frame_id>.*)/columns" ,"GET" ,FramesHandler.class, "columns", null, "Return all the columns from a Frame."); register("/3/Frames/(?<frame_id>.*)/summary" ,"GET" ,FramesHandler.class, "summary", null, "Return a Frame, including the histograms, after forcing computation of rollups."); register("/3/Frames/(?<frame_id>.*)" ,"GET" ,FramesHandler.class, "fetch", null, "Return the specified Frame."); register("/3/Frames" ,"GET" ,FramesHandler.class, "list", null, "Return all Frames in the H2O distributed K/V store."); register("/3/Frames/(?<frame_id>.*)" ,"DELETE",FramesHandler.class, "delete", null, "Delete the specified Frame from the H2O distributed K/V store."); register("/3/Frames" ,"DELETE",FramesHandler.class, "deleteAll", null, "Delete all Frames from the H2O distributed K/V store."); // Handle models register("/3/Models/(?<model_id>.*)" ,"GET" ,ModelsHandler.class, "fetch", null, "Return the specified Model from the H2O distributed K/V store, optionally with the list of compatible Frames."); register("/3/Models" ,"GET" ,ModelsHandler.class, "list", null, "Return all Models from the H2O distributed K/V store."); register("/3/Models/(?<model_id>.*)" ,"DELETE",ModelsHandler.class, "delete", null, "Delete the specified Model from the H2O distributed K/V store."); register("/3/Models" ,"DELETE",ModelsHandler.class, "deleteAll", null, "Delete all Models from the H2O distributed K/V store."); // Get java code for models as register("/3/Models.java/(?<model_id>.*)/preview" ,"GET" ,ModelsHandler.class, "fetchPreview", null, "Return potentially abridged model suitable for viewing in a browser (currently only used for java model code)."); // Register resource also with .java suffix since we do not want to break API // FIXME: remove in new REST API version register("/3/Models.java/(?<model_id>.*)" ,"GET" ,ModelsHandler.class, "fetchJavaCode", null, "Return the stream containing model implementation in Java code."); // Model serialization - import/export calls register("/99/Models.bin/(?<model_id>.*)" ,"POST" ,ModelsHandler.class, "importModel", null, "Import given binary model into H2O."); register("/99/Models.bin/(?<model_id>.*)" ,"GET" ,ModelsHandler.class, "exportModel", null, "Export given model."); // register("/3/Frames/(?<frame_id>.*)/export/(?<path>.*)/overwrite/(?<force>.*)" ,"GET", FramesHandler.class, "export", null, // "Export a Frame to the given path with optional overwrite."); register("/99/Grids/(?<grid_id>.*)" ,"GET" ,GridsHandler.class, "fetch", null, "Return the specified grid search result."); register("/99/Grids" ,"GET" ,GridsHandler.class, "list", null, "Return all grids from H2O distributed K/V store."); register("/3/Configuration/ModelBuilders/visibility" ,"POST" ,ModelBuildersHandler.class, "setVisibility", null, "Set Model Builders visibility level."); register("/3/Configuration/ModelBuilders/visibility" ,"GET" ,ModelBuildersHandler.class, "getVisibility", null, "Get Model Builders visibility level."); register("/3/ModelBuilders/(?<algo>.*)/model_id" ,"POST" ,ModelBuildersHandler.class, "calcModelId", null, "Return a new unique model_id for the specified algorithm."); register("/3/ModelBuilders/(?<algo>.*)" ,"GET" ,ModelBuildersHandler.class, "fetch", null, "Return the Model Builder metadata for the specified algorithm."); register("/3/ModelBuilders" ,"GET" ,ModelBuildersHandler.class, "list", null, "Return the Model Builder metadata for all available algorithms."); // TODO: filtering isn't working for these first four; we get all results: register("/3/ModelMetrics/models/(?<model>.*)/frames/(?<frame>.*)" ,"GET" ,ModelMetricsHandler.class, "fetch", null, "Return the saved scoring metrics for the specified Model and Frame."); register("/3/ModelMetrics/models/(?<model>.*)/frames/(?<frame>.*)" ,"DELETE",ModelMetricsHandler.class, "delete", null, "Return the saved scoring metrics for the specified Model and Frame."); register("/3/ModelMetrics/models/(?<model>.*)" ,"GET" ,ModelMetricsHandler.class, "fetch", null, "Return the saved scoring metrics for the specified Model."); register("/3/ModelMetrics/frames/(?<frame>.*)/models/(?<model>.*)" ,"GET" ,ModelMetricsHandler.class, "fetch", null, "Return the saved scoring metrics for the specified Model and Frame."); register("/3/ModelMetrics/frames/(?<frame>.*)/models/(?<model>.*)" ,"DELETE",ModelMetricsHandler.class, "delete", null, "Return the saved scoring metrics for the specified Model and Frame."); register("/3/ModelMetrics/frames/(?<frame>.*)" ,"GET" ,ModelMetricsHandler.class, "fetch", null, "Return the saved scoring metrics for the specified Frame."); register("/3/ModelMetrics" ,"GET" ,ModelMetricsHandler.class, "fetch", null, "Return all the saved scoring metrics."); register("/3/ModelMetrics/models/(?<model>.*)/frames/(?<frame>.*)" ,"POST" ,ModelMetricsHandler.class, "score", null, "Return the scoring metrics for the specified Frame with the specified Model. If the Frame has already been scored with the Model then cached results will be returned; otherwise predictions for all rows in the Frame will be generated and the metrics will be returned."); register("/3/Predictions/models/(?<model>.*)/frames/(?<frame>.*)" ,"POST" ,ModelMetricsHandler.class, "predict", null, "Score (generate predictions) for the specified Frame with the specified Model. Both the Frame of predictions and the metrics will be returned."); register("/3/WaterMeterCpuTicks/(?<nodeidx>.*)" ,"GET" ,WaterMeterCpuTicksHandler.class, "fetch", null, "Return a CPU usage snapshot of all cores of all nodes in the H2O cluster."); register("/3/WaterMeterIo/(?<nodeidx>.*)" ,"GET" ,WaterMeterIoHandler.class, "fetch", null, "Return IO usage snapshot of all nodes in the H2O cluster."); register("/3/WaterMeterIo" ,"GET" ,WaterMeterIoHandler.class, "fetch_all", null, "Return IO usage snapshot of all nodes in the H2O cluster."); // Node persistent storage register("/3/NodePersistentStorage/categories/(?<category>.*)/names/(?<name>.*)/exists", "GET", NodePersistentStorageHandler.class, "exists", null, "Return true or false."); register("/3/NodePersistentStorage/categories/(?<category>.*)/exists", "GET" ,NodePersistentStorageHandler.class, "exists", null, "Return true or false."); register("/3/NodePersistentStorage/configured", "GET" ,NodePersistentStorageHandler.class, "configured", null, "Return true or false."); register("/3/NodePersistentStorage/(?<category>.*)/(?<name>.*)" ,"POST" ,NodePersistentStorageHandler.class, "put_with_name", null, "Store a named value."); register("/3/NodePersistentStorage/(?<category>.*)/(?<name>.*)" ,"GET" ,NodePersistentStorageHandler.class, "get_as_string", null, "Return value for a given name."); register("/3/NodePersistentStorage/(?<category>.*)/(?<name>.*)" ,"DELETE",NodePersistentStorageHandler.class, "delete", null, "Delete a key."); register("/3/NodePersistentStorage/(?<category>.*)" ,"POST" ,NodePersistentStorageHandler.class, "put", null, "Store a value."); register("/3/NodePersistentStorage/(?<category>.*)" ,"GET" ,NodePersistentStorageHandler.class, "list", null, "Return all keys stored for a given category."); // TODO: register("/3/ModelMetrics/models/(?<model>.*)/frames/(?<frame>.*)" ,"DELETE",ModelMetricsHandler.class, "delete"); // TODO: register("/3/ModelMetrics/frames/(?<frame>.*)/models/(?<model>.*)" ,"DELETE",ModelMetricsHandler.class, "delete"); // TODO: register("/3/ModelMetrics/frames/(?<frame>.*)" ,"DELETE",ModelMetricsHandler.class, "delete"); // TODO: register("/3/ModelMetrics/models/(?<model>.*)" ,"DELETE",ModelMetricsHandler.class, "delete"); // TODO: register("/3/ModelMetrics" ,"DELETE",ModelMetricsHandler.class, "delete"); // TODO: register("/3/Predictions/models/(?<model>.*)/frames/(?<frame>.*)" ,"POST" ,ModelMetricsHandler.class, "predict"); // Log file management. // Note: Hacky pre-route cutout of "/3/Logs/download" is done above in a non-json way. register("/3/Logs/nodes/(?<nodeidx>.*)/files/(?<name>.*)", "GET", LogsHandler.class, "fetch", null, "Get named log file for a node."); // ModelBuilder Handler registration must be done for each algo in the application class // (e.g., H2OApp), because the Handler class is parameterized by the associated Schema, // and this is different for each ModelBuilder in order to handle its parameters in a // typesafe way: // // register("/2/ModelBuilders/(?<algo>.*)" ,"POST" ,ModelBuildersHandler.class, "train", new String[] {"algo"}); register("/3/KillMinus3" ,"GET" ,KillMinus3Handler.class, "killm3", null, "Kill minus 3 on *this* node"); register("/99/Rapids" ,"POST" ,RapidsHandler.class, "exec", null, "Execute an Rapids AST."); register("/99/Assembly.java/(?<assembly_id>.*)/(?<pojo_name>.*)" ,"GET" ,AssemblyHandler.class, "toJava", null, "Generate a Java POJO from the Assembly"); register("/99/Assembly" ,"POST" ,AssemblyHandler.class, "fit", null, "Fit an assembly to an input frame"); register("/3/DownloadDataset" ,"GET" ,DownloadDataHandler.class, "fetch", null, "Download something something."); register("/3/DownloadDataset.bin" ,"GET" ,DownloadDataHandler.class, "fetchStreaming", null, "Download something something via streaming response"); register("/3/DKV/(?<key>.*)" ,"DELETE",RemoveHandler.class, "remove", null, "Remove an arbitrary key from the H2O distributed K/V store."); register("/3/DKV" ,"DELETE",RemoveAllHandler.class, "remove", null, "Remove all keys from the H2O distributed K/V store."); register("/3/LogAndEcho" ,"POST" ,LogAndEchoHandler.class, "echo", null, "Save a message to the H2O logfile."); register("/3/InitID" ,"GET" ,InitIDHandler.class, "issue", null, "Issue a new session ID."); register("/3/GarbageCollect" ,"POST" ,GarbageCollectHandler.class, "gc", null, "Explicitly call System.gc()."); register("/99/Sample" ,"GET",CloudHandler .class,"status" , null,"Example of an experimental endpoint. Call via /EXPERIMENTAL/Sample. Experimental endpoints can change at any moment."); } /** * Register an HTTP request handler method for a given URL pattern, with parameters extracted from the URI. * <p> * URIs which match this pattern will have their parameters collected from the path and from the query params * * @param uri_pattern_raw regular expression which matches the URL path for this request handler; parameters that are embedded in the path must be captured with &lt;code&gt;(?&lt;parm&gt;.*)&lt;/code&gt; syntax * @param http_method HTTP verb (GET, POST, DELETE) this handler will accept * @param handler_class class which contains the handler method * @param handler_method name of the handler method * @param doc_method name of a method which returns GitHub Flavored Markdown documentation for the request * @param summary short help string which summarizes the functionality of this endpoint * @see Route * @see water.api.RequestServer * @return the Route for this request */ public static Route register(String uri_pattern_raw, String http_method, Class<? extends Handler> handler_class, String handler_method, String doc_method, String summary) { return register(uri_pattern_raw, http_method, handler_class, handler_method, doc_method, summary, HandlerFactory.DEFAULT); } /** * Register an HTTP request handler method for a given URL pattern, with parameters extracted from the URI. * <p> * URIs which match this pattern will have their parameters collected from the path and from the query params * * @param uri_pattern_raw regular expression which matches the URL path for this request handler; parameters that are embedded in the path must be captured with &lt;code&gt;(?&lt;parm&gt;.*)&lt;/code&gt; syntax * @param http_method HTTP verb (GET, POST, DELETE) this handler will accept * @param handler_class class which contains the handler method * @param handler_method name of the handler method * @param doc_method name of a method which returns GitHub Flavored Markdown documentation for the request * @param summary short help string which summarizes the functionality of this endpoint * @param handler_factory factory to create instance of handler * @see Route * @see water.api.RequestServer * @return the Route for this request */ public static Route register(String uri_pattern_raw, String http_method, Class<? extends Handler> handler_class, String handler_method, String doc_method, String summary, HandlerFactory handler_factory) { assert uri_pattern_raw.startsWith("/"); // Search handler_class and all its superclasses for the method. Method meth = null; Method doc_meth = null; // TODO: move to ReflectionUtils: try { for (Method m : handler_class.getMethods()) { if (! m.getName().equals(handler_method)) continue; Class[] params = m.getParameterTypes(); if (null == params || params.length != 2) continue; if (params[0] != Integer.TYPE) continue; if (! Schema.class.isAssignableFrom(params[1])) continue; meth = m; break; } if (null != doc_method) doc_meth = handler_class.getMethod(doc_method, new Class[]{int.class, StringBuffer.class}); } catch (NoSuchMethodException e) { // ignore: H2O.fail below } if (null == meth) throw H2O.fail("Failed to find handler method: " + handler_method + " for handler class: " + handler_class); if (null != doc_method && null == doc_meth) throw H2O.fail("Failed to find doc method: " + doc_method + " for handler class: " + handler_class); if (! "/".equals(uri_pattern_raw)) { Matcher m = getVersionPattern().matcher(uri_pattern_raw); if (!m.matches()) throw H2O.fail("Route URL pattern must begin with a version: " + uri_pattern_raw); int version = Integer.valueOf(m.group(1)); if (version > Schema.getHighestSupportedVersion() && version != Schema.getExperimentalVersion()) throw H2O.fail("Route version is greater than the max supported of: " + Schema.getHighestSupportedVersion() + ": " + uri_pattern_raw); } // Get the group names in the uri pattern and remove any underscores, // since underscores are not actually allowed in java regex group names. String group_pattern_raw = "\\?<([\\p{Alnum}_]+)>"; ArrayList<String> params_list = new ArrayList<String>(); Pattern group_pattern = Pattern.compile(group_pattern_raw); Matcher group_matcher = group_pattern.matcher(uri_pattern_raw); StringBuffer new_uri_buffer = new StringBuffer(); while (group_matcher.find()) { String group = group_matcher.group(1); params_list.add(group); group_matcher.appendReplacement(new_uri_buffer, "?<" + group.replace("_", "") + ">"); } group_matcher.appendTail(new_uri_buffer); uri_pattern_raw = new_uri_buffer.toString(); assert lookup(handler_method, uri_pattern_raw)==null; // Not shadowed Pattern uri_pattern = Pattern.compile(uri_pattern_raw); Route route = new Route(http_method, uri_pattern_raw, uri_pattern, summary, handler_class, meth, doc_meth, params_list.toArray(new String[params_list.size()]), handler_factory); _routes.put(uri_pattern.pattern(), route); return route; } // Lookup the method/url in the register list, and return a matching Method protected static Route lookup( String http_method, String uri ) { if (null == http_method || null == uri) return null; // Search the explicitly registered routes: for( Route r : _routes.values() ) if (r._url_pattern.matcher(uri).matches()) if (http_method.equals(r._http_method)) return r; // Search the fallbacks cache: for( Route r : _fallbacks.values() ) if (r._url_pattern.matcher(uri).matches()) if (http_method.equals(r._http_method)) return r; // Didn't find a registered route and didn't find a cached fallback, so do a backward version search and cache if we find a match: Matcher m = getVersionPattern().matcher(uri); if (! m.matches()) return null; // Ok then. . . Try to fall back to a previous version. int version = Integer.valueOf(m.group(1)); if (version == Route.MIN_VERSION) return null; // don't go any lower String lower_uri = "/" + (version - 1) + "/" + m.group(2); Route fallback = lookup(http_method, lower_uri); if (null == fallback) return null; // Store the route fallback for later. Matcher route_m = version_pattern.matcher(fallback._url_pattern_raw); if (! route_m.matches()) throw H2O.fail("Found a fallback route that doesn't have a version: " + fallback); // register fallbacks for all the versions <= the one in URI we were originally given and > the one in the fallback route: int route_version = Integer.valueOf(route_m.group(1)); for (int i = version; i > route_version && i >= Route.MIN_VERSION; i--) { String fallback_route_uri = "/" + i + "/" + route_m.group(2); Pattern fallback_route_pattern = Pattern.compile(fallback_route_uri); Route generated = new Route(fallback._http_method, fallback_route_uri, fallback_route_pattern, fallback._summary, fallback._handler_class, fallback._handler_method, fallback._doc_method, fallback._path_params, fallback._handler_factory); _fallbacks.put(fallback_route_pattern.pattern(), generated); } // Better be there in the _fallbacks cache now! return lookup(http_method, uri); } public static void finalizeRegistration() { Schema.registerAllSchemasIfNecessary(); // Need a stub RequestServer to handle calls to serve() from Jetty. // But no threads are started here anymore. SERVER = new RequestServer(); H2O.getJetty().acceptRequests(); } public static void alwaysLogRequest(String uri, String method, Properties parms) { // This is never called anymore. throw H2O.fail(); } // Log all requests except the overly common ones boolean maybeLogRequest(String method, String uri, String pattern, Properties parms, Properties header) { if (uri.endsWith(".css") || uri.endsWith(".js") || uri.endsWith(".png") || uri.endsWith(".ico")) return false; if (uri.contains("/Cloud") || (uri.contains("/Jobs") && method.equals("GET")) || uri.contains("/Log") || uri.contains("/Progress") || uri.contains("/Typeahead") || uri.contains("/WaterMeterCpuTicks")) return false; String paddedMethod = String.format("%-6s", method); Log.info("Method: " + paddedMethod, ", URI: " + uri + ", route: " + pattern + ", parms: " + parms); return true; } private void capturePathParms(Properties parms, String path, Route route) { Matcher m = route._url_pattern.matcher(path); if (! m.matches()) { throw H2O.fail("Routing regex error: Pattern matched once but not again for pattern: " + route._url_pattern.pattern() + " and path: " + path); } // Java doesn't allow _ in group names but we want them in field names, so remove all _ from the path params before we look up the group capture value for (String key : route._path_params) { String key_no_underscore = key.replace("_",""); String val; try { val = m.group(key_no_underscore); } catch (IllegalArgumentException e) { throw H2O.fail("Missing request parameter in the URL: did not find " + key + " in the URL as expected; URL pattern: " + route._url_pattern.pattern() + " with expected parameters: " + Arrays.toString(route._path_params) + " for URL: " + path); } if (null != val) parms.put(key, val); } } private Response response404(String what, RequestType type) { H2ONotFoundArgumentException e = new H2ONotFoundArgumentException(what + " not found", what + " not found"); H2OError error = e.toH2OError(what); Log.warn(error._dev_msg); Log.warn(error._values.toJsonString()); Log.warn((Object[]) error._stacktrace); return wrap(new H2OErrorV3().fillFromImpl(error), type); } // Top-level dispatch based on the URI. Break down URI into parts; // e.g. /2/GBM.html/crunk?hex=some_hex breaks down into: // version: 2 // requestType: ".html" // path: "GBM/crunk" // parms: "{hex-->some_hex}" @Override public Response serve( String uri, String method, Properties header, Properties parms ) { // Jack priority for user-visible requests Thread.currentThread().setPriority(Thread.MAX_PRIORITY - 1); // determine version: if /LATEST then use the highest version of any schema (or the highest supported version, if we don't know yet). if (uri.startsWith("/LATEST")) { if (-1 == Schema.getLatestVersion()) { // Not yet initialized, and we might be in bootstrap uri = "/" + Schema.getHighestSupportedVersion() + uri.substring("/latest".length()); } else { uri = "/" + Schema.getLatestVersion() + uri.substring("/latest".length()); } } // determine the request type RequestType type = RequestType.requestType(uri); // Blank response used by R's uri.exists("/") if (uri.equals("/") && method.equals("HEAD")) { Response r = new Response(HTTP_OK, MIME_PLAINTEXT, ""); return r; } String versioned_path = uri; String path = uri; int version = 1; Matcher m = getVersionPattern().matcher(uri); if (m.matches()) { if ("EXPERIMENTAL".equals(m.group(1))) { version = 99; } else { version = Integer.valueOf(m.group(1)); } String uripath = "/" + m.group(2); path = type.requestName(uripath); // Strip suffix type from middle of URI versioned_path = "/" + version + path; } // Load resources, or dispatch on handled requests try { boolean logged; // Handle any URLs that bypass the route approach. This is stuff that has abnormal non-JSON response payloads. if (method.equals("GET") && uri.equals("/")) { logged = maybeLogRequest(method, uri, "", parms, header); if (logged) GAUtils.logRequest(uri, header); return redirectToFlow(); } if (method.equals("GET") && uri.endsWith("/Logs/download")) { logged = maybeLogRequest(method, uri, "", parms, header); if (logged) GAUtils.logRequest(uri, header); return downloadLogs(); } if (method.equals("GET")) { Pattern p2 = Pattern.compile(".*/NodePersistentStorage.bin/([^/]+)/([^/]+)"); Matcher m2 = p2.matcher(uri); boolean b2 = m2.matches(); if (b2) { String categoryName = m2.group(1); String keyName = m2.group(2); return downloadNps(categoryName, keyName); } } // Find handler for url Route route = lookup(method, versioned_path); // if the request is not known, treat as resource request, or 404 if not found if( route == null) { if (method.equals("GET")) { return getResource(type, uri); } else { return response404(method + " " + uri, type); } } else if(route._handler_class == water.api.DownloadDataHandler.class) { // DownloadDataHandler will throw H2ONotFoundException if the resource is not found return wrapDownloadData(HTTP_OK, handle(type, route, version, parms)); } else { capturePathParms(parms, versioned_path, route); // get any parameters like /Frames/<key> logged = maybeLogRequest(method, uri, route._url_pattern.namedPattern(), parms, header); if (logged) GAUtils.logRequest(uri, header); Schema s = handle(type, route, version, parms); PojoUtils.filterFields(s, (String)parms.get("_include_fields"), (String)parms.get("_exclude_fields")); Response r = wrap(s, type); return r; } } catch (H2OFailException e) { H2OError error = e.toH2OError(uri); Log.fatal("Caught exception (fatal to the cluster): " + error.toString()); // Note: don't use Schema.schema(version, error) because we have to work at bootstrap: H2O.fail(wrap(new H2OErrorV3().fillFromImpl(error), type).toString()); // unreachable, but the compiler doesn't know it: return null; } catch (H2OModelBuilderIllegalArgumentException e) { H2OModelBuilderError error = e.toH2OError(uri); Log.warn("Caught exception: " + error.toString()); // Note: don't use Schema.schema(version, error) because we have to work at bootstrap: return wrap(new H2OModelBuilderErrorV3().fillFromImpl(error), type); } catch (H2OAbstractRuntimeException e) { H2OError error = e.toH2OError(uri); Log.warn("Caught exception: " + error.toString()); // Note: don't use Schema.schema(version, error) because we have to work at bootstrap: return wrap(new H2OErrorV3().fillFromImpl(error), type); } // TODO: kill the server if someone called H2O.fail() catch( Exception e ) { // make sure that no Exception is ever thrown out from the request H2OError error = new H2OError(e, uri); // some special cases for which we return 400 because it's likely a problem with the client request: if (e instanceof IllegalArgumentException) error._http_status = HttpResponseStatus.BAD_REQUEST.getCode(); else if (e instanceof FileNotFoundException) error._http_status = HttpResponseStatus.BAD_REQUEST.getCode(); else if (e instanceof MalformedURLException) error._http_status = HttpResponseStatus.BAD_REQUEST.getCode(); Log.err("Caught exception: " + error.toString()); // Note: don't use Schema.schema(version, error) because we have to work at bootstrap: return wrap(new H2OErrorV3().fillFromImpl(error), type); } } // Handling ------------------------------------------------------------------ private Schema handle( RequestType type, Route route, int version, Properties parms ) throws Exception { switch( type ) { case html: // These request-types only dictate the response-type; case java: // the normal action is always done. case json: case xml: { Handler h = route._handler; return h.handle(version,route,parms); // Can throw any Exception the handler throws } case query: case help: default: throw H2O.unimpl("Unknown type: " + type.toString()); } } private Response wrap( Schema s, RequestType type ) { // Convert Schema to desired output flavor String http_response_header = H2OError.httpStatusHeader(HttpResponseStatus.OK.getCode()); // If we're given an http response code use it. if (s instanceof SpecifiesHttpResponseCode) { http_response_header = H2OError.httpStatusHeader(((SpecifiesHttpResponseCode) s).httpStatus()); } // If we've gotten an error always return the error as JSON if (s instanceof SpecifiesHttpResponseCode && HttpResponseStatus.OK.getCode() != ((SpecifiesHttpResponseCode) s).httpStatus()) { type = RequestType.json; } switch( type ) { case html: // return JSON for html requests case json: return new Response(http_response_header, MIME_JSON, s.toJsonString()); case xml: //return new Response(http_code, MIME_XML , new String(S.writeXML (new AutoBuffer()).buf())); throw H2O.unimpl("Unknown type: " + type.toString()); case java: if (s instanceof H2OErrorV3) { return new Response(http_response_header, MIME_JSON, s.toJsonString()); } if (s instanceof AssemblyV99) { Assembly ass = DKV.getGet(((AssemblyV99) s).assembly_id); Response r = new Response(http_response_header, MIME_DEFAULT_BINARY, ass.toJava(((AssemblyV99) s).pojo_name)); r.addHeader("Content-Disposition", "attachment; filename=\""+JCodeGen.toJavaId(((AssemblyV99) s).pojo_name)+".java\""); return r; } else if (s instanceof StreamingSchema) { StreamingSchema ss = (StreamingSchema) s; Response r = new StreamResponse(http_response_header, MIME_DEFAULT_BINARY, ss.getStreamWriter()); // Needed to make file name match class name r.addHeader("Content-Disposition", "attachment; filename=\"" + ss.getFilename() + "\""); return r; } else { throw new H2OIllegalArgumentException("Cannot generate java for type: " + s.getClass().getSimpleName()); } default: throw H2O.unimpl("Unknown type to wrap(): " + type); } } private Response wrapDownloadData(String http_code, Schema s) { DownloadDataV3 dd = (DownloadDataV3)s; Response res = new Response(http_code, MIME_DEFAULT_BINARY, dd.csv); res.addHeader("Content-Disposition", "filename=" + dd.filename); return res; } // Resource loading ---------------------------------------------------------- // cache of all loaded resources private static final NonBlockingHashMap<String,byte[]> _cache = new NonBlockingHashMap<>(); // Returns the response containing the given uri with the appropriate mime type. private Response getResource(RequestType request_type, String uri) { byte[] bytes = _cache.get(uri); if( bytes == null ) { // Try-with-resource try (InputStream resource = water.init.JarHash.getResource2(uri)) { if( resource != null ) { try { bytes = toByteArray(resource); } catch( IOException e ) { Log.err(e); } // PP 06-06-2014 Disable caching for now so that the browser // always gets the latest sources and assets when h2o-client is rebuilt. // TODO need to rethink caching behavior when h2o-dev is merged into h2o. // // if( bytes != null ) { // byte[] res = _cache.putIfAbsent(uri,bytes); // if( res != null ) bytes = res; // Racey update; take what is in the _cache //} // } } catch( IOException ignore ) { } } if( bytes == null || bytes.length == 0 ) // No resource found? return response404("Resource " + uri, request_type); String mime = MIME_DEFAULT_BINARY; if( uri.endsWith(".css") ) mime = "text/css"; else if( uri.endsWith(".html") ) mime = "text/html"; Response res = new Response(HTTP_OK,mime,new ByteArrayInputStream(bytes)); res.addHeader("Content-Length", Long.toString(bytes.length)); return res; } // Convenience utility private static byte[] toByteArray(InputStream is) throws IOException { try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { byte[] buffer = new byte[0x2000]; for( int len; (len = is.read(buffer)) != -1; ) os.write(buffer, 0, len); return os.toByteArray(); } } // Return URLs for things that want to appear Frame-inspection page static String[] frameChoices( int version, Frame fr ) { ArrayList<String> al = new ArrayList<>(); for( java.util.regex.Pattern p : _routes.keySet() ) { try { Method meth = _routes.get(p)._handler_method; Class clz0 = meth.getDeclaringClass(); Class<Handler> clz = (Class<Handler>)clz0; Handler h = clz.newInstance(); // TODO: we don't need to create new instances; handler is stateless } catch( InstantiationException | IllegalArgumentException | IllegalAccessException ignore ) { } } return al.toArray(new String[al.size()]); } // --------------------------------------------------------------------- // Download logs support // --------------------------------------------------------------------- private String getOutputLogStem() { String pattern = "yyyyMMdd_hhmmss"; SimpleDateFormat formatter = new SimpleDateFormat(pattern); String now = formatter.format(new Date()); return "h2ologs_" + now; } private byte[] zipLogs(byte[][] results, byte[] clientResult, String topDir) throws IOException { int l = 0; assert H2O.CLOUD._memary.length == results.length : "Unexpected change in the cloud!"; for (int i = 0; i<results.length;l+=results[i++].length); ByteArrayOutputStream baos = new ByteArrayOutputStream(l); // Add top-level directory. ZipOutputStream zos = new ZipOutputStream(baos); { ZipEntry zde = new ZipEntry (topDir + File.separator); zos.putNextEntry(zde); } try { // Add zip directory from each cloud member. for (int i =0; i<results.length; i++) { String filename = topDir + File.separator + "node" + i + "_" + H2O.CLOUD._memary[i].getIpPortString().replace(':', '_').replace('/', '_') + ".zip"; ZipEntry ze = new ZipEntry(filename); zos.putNextEntry(ze); zos.write(results[i]); zos.closeEntry(); } // Add zip directory from the client node. Name it 'driver' since that's what Sparking Water users see. if (clientResult != null) { String filename = topDir + File.separator + "driver.zip"; ZipEntry ze = new ZipEntry(filename); zos.putNextEntry(ze); zos.write(clientResult); zos.closeEntry(); } // Close the top-level directory. zos.closeEntry(); } finally { // Close the full zip file. zos.close(); } return baos.toByteArray(); } private Response downloadLogs() { Log.info("\nCollecting logs."); H2ONode[] members = H2O.CLOUD.members(); byte[][] perNodeZipByteArray = new byte[members.length][]; byte[] clientNodeByteArray = null; for (int i = 0; i < members.length; i++) { byte[] bytes; try { // Skip nodes that aren't healthy, since they are likely to cause the entire process to hang. boolean healthy = (System.currentTimeMillis() - members[i]._last_heard_from) < HeartBeatThread.TIMEOUT; if (healthy) { GetLogsFromNode g = new GetLogsFromNode(); g.nodeidx = i; g.doIt(); bytes = g.bytes; } else { bytes = "Node not healthy".getBytes(); } } catch (Exception e) { bytes = e.toString().getBytes(); } perNodeZipByteArray[i] = bytes; } if (H2O.ARGS.client) { byte[] bytes; try { GetLogsFromNode g = new GetLogsFromNode(); g.nodeidx = -1; g.doIt(); bytes = g.bytes; } catch (Exception e) { bytes = e.toString().getBytes(); } clientNodeByteArray = bytes; } String outputFileStem = getOutputLogStem(); byte[] finalZipByteArray; try { finalZipByteArray = zipLogs(perNodeZipByteArray, clientNodeByteArray, outputFileStem); } catch (Exception e) { finalZipByteArray = e.toString().getBytes(); } NanoHTTPD.Response res = new Response(NanoHTTPD.HTTP_OK,NanoHTTPD.MIME_DEFAULT_BINARY, new ByteArrayInputStream(finalZipByteArray)); res.addHeader("Content-Length", Long.toString(finalZipByteArray.length)); res.addHeader("Content-Disposition", "attachment; filename="+outputFileStem + ".zip"); return res; } // --------------------------------------------------------------------- // Download NPS support // --------------------------------------------------------------------- private Response downloadNps(String categoryName, String keyName) { NodePersistentStorage nps = H2O.getNPS(); AtomicLong length = new AtomicLong(); InputStream is = nps.get(categoryName, keyName, length); NanoHTTPD.Response res = new Response(NanoHTTPD.HTTP_OK, NanoHTTPD.MIME_DEFAULT_BINARY, is); res.addHeader("Content-Length", Long.toString(length.get())); res.addHeader("Content-Disposition", "attachment; filename="+keyName + ".flow"); return res; } private Response redirectToFlow() { StringBuilder sb = new StringBuilder(); NanoHTTPD.Response res = new Response(NanoHTTPD.HTTP_REDIRECT, NanoHTTPD.MIME_PLAINTEXT, sb.toString()); res.addHeader("Location", "/flow/index.html"); return res; } }
PUBDEV-2220: Update Request Server descriptions.
h2o-core/src/main/java/water/api/RequestServer.java
PUBDEV-2220: Update Request Server descriptions.
<ide><path>2o-core/src/main/java/water/api/RequestServer.java <ide> register("/3/Cloud", "GET", CloudHandler.class, "status", null, "Determine the status of the nodes in the H2O cloud."); <ide> register("/3/Cloud", "HEAD",CloudHandler.class, "head", null, "Determine the status of the nodes in the H2O cloud."); <ide> register("/3/Jobs" ,"GET", JobsHandler.class, "list", null, "Get a list of all the H2O Jobs (long-running actions)."); <del> register("/3/Timeline" ,"GET",TimelineHandler .class,"fetch" , null,"Something something something."); <del> register("/3/Profiler" ,"GET",ProfilerHandler .class,"fetch" , null,"Something something something."); <del> register("/3/JStack" ,"GET",JStackHandler .class,"fetch" , null,"Something something something."); <del> register("/3/NetworkTest","GET",NetworkTestHandler.class,"fetch" , null,"Something something something."); <add> register("/3/Timeline" ,"GET",TimelineHandler .class,"fetch" , null,"Show a time line."); <add> register("/3/Profiler" ,"GET",ProfilerHandler .class,"fetch" , null,"Report real-time profiling information for all nodes (sorted, aggregated stack traces)."); <add> register("/3/JStack" ,"GET",JStackHandler .class,"fetch" , null,"Report stack traces for all threads on all nodes."); <add> register("/3/NetworkTest","GET",NetworkTestHandler.class,"fetch" , null,"Run a network test to measure the performance of the cluster interconnect."); <ide> register("/3/UnlockKeys", "POST", UnlockKeysHandler.class, "unlock", null, "Unlock all keys in the H2O distributed K/V store, to attempt to recover from a crash."); <ide> register("/3/Shutdown" ,"POST",ShutdownHandler .class,"shutdown" , null,"Shut down the cluster"); <ide>
Java
apache-2.0
1de0e0c4239ca7ce31901e6a11f6b7185b2fef74
0
EclairJS/eclairjs,EclairJS/eclairjs-nashorn,EclairJS/eclairjs-nashorn,EclairJS/eclairjs-nashorn,conker84/eclairjs-nashorn,doronrosenberg/eclairjs,EclairJS/eclairjs,EclairJS/eclairjs-nashorn,doronrosenberg/eclairjs,conker84/eclairjs-nashorn,EclairJS/eclairjs,doronrosenberg/eclairjs,EclairJS/eclairjs,EclairJS/eclairjs,conker84/eclairjs-nashorn,doronrosenberg/eclairjs,doronrosenberg/eclairjs
package com.ibm.eclair; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.apache.spark.SparkContext; import org.junit.Test; import java.io.InputStreamReader; public class SparkBootstrapTest { @Test public void getEngine() throws Exception { ScriptEngine engine = TestUtils.getEngine(); engine.eval(new InputStreamReader(getClass().getResourceAsStream("/rddtest.js"))); Object ret = ((Invocable)engine).invokeFunction("test"); System.out.println(ret); assertNotNull(ret); } }
src/test/java/com/ibm/eclair/SparkBootstrapTest.java
package com.ibm.eclair; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.apache.spark.SparkContext; import org.junit.Test; import java.io.InputStreamReader; public class SparkBootstrapTest { @Test public void getEngine() throws Exception { ScriptEngineManager engineManager = new ScriptEngineManager(); ScriptEngine engine = engineManager.getEngineByName("nashorn"); SparkContext sc = new SparkContext("local[*]", "testapp"); engine.put("sc", sc); SparkBootstrap b = new SparkBootstrap(); b.load(engine); engine.eval(new InputStreamReader(getClass().getResourceAsStream("/rddtest.js"))); Object ret = ((Invocable)engine).invokeFunction("test"); System.out.println(ret); assertNotNull(ret); } }
test error
src/test/java/com/ibm/eclair/SparkBootstrapTest.java
test error
<ide><path>rc/test/java/com/ibm/eclair/SparkBootstrapTest.java <ide> <ide> @Test <ide> public void getEngine() throws Exception { <del> ScriptEngineManager engineManager = new ScriptEngineManager(); <del> ScriptEngine engine = engineManager.getEngineByName("nashorn"); <del> SparkContext sc = new SparkContext("local[*]", "testapp"); <del> engine.put("sc", sc); <ide> <del> SparkBootstrap b = new SparkBootstrap(); <del> b.load(engine); <del> <add> ScriptEngine engine = TestUtils.getEngine(); <ide> engine.eval(new InputStreamReader(getClass().getResourceAsStream("/rddtest.js"))); <ide> Object ret = ((Invocable)engine).invokeFunction("test"); <ide>
Java
epl-1.0
09f1260891297baa379a6c41e27113d2b6b53ce4
0
opendaylight/ovsdb,opendaylight/ovsdb,opendaylight/ovsdb
/* * Copyright (c) 2014 - 2016 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.ovsdb.openstack.netvirt.impl; import com.google.common.base.Preconditions; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.opendaylight.ovsdb.openstack.netvirt.AbstractEvent; import org.opendaylight.ovsdb.openstack.netvirt.AbstractHandler; import org.opendaylight.ovsdb.openstack.netvirt.ConfigInterface; import org.opendaylight.ovsdb.openstack.netvirt.NeutronL3AdapterEvent; import org.opendaylight.ovsdb.openstack.netvirt.api.Action; import org.opendaylight.ovsdb.openstack.netvirt.api.ArpProvider; import org.opendaylight.ovsdb.openstack.netvirt.api.ConfigurationService; import org.opendaylight.ovsdb.openstack.netvirt.api.Constants; import org.opendaylight.ovsdb.openstack.netvirt.api.EventDispatcher; import org.opendaylight.ovsdb.openstack.netvirt.api.GatewayMacResolver; import org.opendaylight.ovsdb.openstack.netvirt.api.GatewayMacResolverListener; import org.opendaylight.ovsdb.openstack.netvirt.api.IcmpEchoProvider; import org.opendaylight.ovsdb.openstack.netvirt.api.InboundNatProvider; import org.opendaylight.ovsdb.openstack.netvirt.api.L3ForwardingProvider; import org.opendaylight.ovsdb.openstack.netvirt.api.NodeCacheManager; import org.opendaylight.ovsdb.openstack.netvirt.api.OutboundNatProvider; import org.opendaylight.ovsdb.openstack.netvirt.api.RoutingProvider; import org.opendaylight.ovsdb.openstack.netvirt.api.SecurityServicesManager; import org.opendaylight.ovsdb.openstack.netvirt.api.Southbound; import org.opendaylight.ovsdb.openstack.netvirt.api.Status; import org.opendaylight.ovsdb.openstack.netvirt.api.StatusCode; import org.opendaylight.ovsdb.openstack.netvirt.api.TenantNetworkManager; import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronFloatingIP; import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronNetwork; import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronPort; import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronRouter; import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronRouter_Interface; import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronSecurityGroup; import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronSubnet; import org.opendaylight.ovsdb.openstack.netvirt.translator.Neutron_IPs; import org.opendaylight.ovsdb.openstack.netvirt.translator.crud.INeutronFloatingIPCRUD; import org.opendaylight.ovsdb.openstack.netvirt.translator.crud.INeutronNetworkCRUD; import org.opendaylight.ovsdb.openstack.netvirt.translator.crud.INeutronPortCRUD; import org.opendaylight.ovsdb.openstack.netvirt.translator.crud.INeutronSubnetCRUD; import org.opendaylight.ovsdb.openstack.netvirt.translator.iaware.impl.NeutronIAwareUtil; import org.opendaylight.ovsdb.utils.neutron.utils.NeutronModelsDataStoreHelper; import org.opendaylight.ovsdb.utils.servicehelper.ServiceHelper; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.Routers; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.Router; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentation; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node; import org.osgi.framework.ServiceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.Inet4Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * Neutron L3 Adapter implements a hub-like adapter for the various Neutron events. Based on * these events, the abstract router callbacks can be generated to the multi-tenant aware router, * as well as the multi-tenant router forwarding provider. */ public class NeutronL3Adapter extends AbstractHandler implements GatewayMacResolverListener, ConfigInterface { private static final Logger LOG = LoggerFactory.getLogger(NeutronL3Adapter.class); // The implementation for each of these services is resolved by the OSGi Service Manager private volatile ConfigurationService configurationService; private volatile TenantNetworkManager tenantNetworkManager; private volatile NodeCacheManager nodeCacheManager; private volatile INeutronNetworkCRUD neutronNetworkCache; private volatile INeutronSubnetCRUD neutronSubnetCache; private volatile INeutronPortCRUD neutronPortCache; private volatile INeutronFloatingIPCRUD neutronFloatingIpCache; private volatile L3ForwardingProvider l3ForwardingProvider; private volatile InboundNatProvider inboundNatProvider; private volatile OutboundNatProvider outboundNatProvider; private volatile ArpProvider arpProvider; private volatile RoutingProvider routingProvider; private volatile GatewayMacResolver gatewayMacResolver; private volatile SecurityServicesManager securityServicesManager; private volatile IcmpEchoProvider icmpEchoProvider; private class FloatIpData { // br-int of node where floating ip is associated with tenant port private final Long dpid; // patch port in br-int used to reach br-ex private final Long ofPort; // segmentation id of the net where fixed ip is instantiated private final String segId; // mac address assigned to neutron port of floating ip private final String macAddress; private final String floatingIpAddress; // ip address given to tenant vm private final String fixedIpAddress; private final String neutronRouterMac; FloatIpData(final Long dpid, final Long ofPort, final String segId, final String macAddress, final String floatingIpAddress, final String fixedIpAddress, final String neutronRouterMac) { this.dpid = dpid; this.ofPort = ofPort; this.segId = segId; this.macAddress = macAddress; this.floatingIpAddress = floatingIpAddress; this.fixedIpAddress = fixedIpAddress; this.neutronRouterMac = neutronRouterMac; } } private Map<String, String> networkIdToRouterMacCache; private Map<String, List<Neutron_IPs>> networkIdToRouterIpListCache; private Map<String, NeutronRouter_Interface> subnetIdToRouterInterfaceCache; private Map<String, Pair<Long, Uuid>> neutronPortToDpIdCache; private Map<String, FloatIpData> floatIpDataMapCache; private String externalRouterMac; private Boolean enabled = false; private Boolean isCachePopulationDone = false; private Map<String, NeutronPort> portCleanupCache; private Map<String, NeutronNetwork> networkCleanupCache; private Southbound southbound; private DistributedArpService distributedArpService; private NeutronModelsDataStoreHelper neutronModelsDataStoreHelper; private static final String OWNER_ROUTER_INTERFACE = "network:router_interface"; private static final String OWNER_ROUTER_INTERFACE_DISTRIBUTED = "network:router_interface_distributed"; private static final String OWNER_ROUTER_GATEWAY = "network:router_gateway"; private static final String OWNER_FLOATING_IP = "network:floatingip"; private static final String DEFAULT_EXT_RTR_MAC = "00:00:5E:00:01:01"; public NeutronL3Adapter(NeutronModelsDataStoreHelper neutronHelper) { LOG.info(">>>>>> NeutronL3Adapter constructor {}", this.getClass()); this.neutronModelsDataStoreHelper = neutronHelper; } private void initL3AdapterMembers() { Preconditions.checkNotNull(configurationService); if (configurationService.isL3ForwardingEnabled()) { this.networkIdToRouterMacCache = new HashMap<>(); this.networkIdToRouterIpListCache = new HashMap<>(); this.subnetIdToRouterInterfaceCache = new HashMap<>(); this.neutronPortToDpIdCache = new HashMap<>(); this.floatIpDataMapCache = new HashMap<>(); this.externalRouterMac = configurationService.getDefaultGatewayMacAddress(null); if (this.externalRouterMac == null) { this.externalRouterMac = DEFAULT_EXT_RTR_MAC; } this.enabled = true; LOG.info("OVSDB L3 forwarding is enabled"); } else { LOG.debug("OVSDB L3 forwarding is disabled"); } this.portCleanupCache = new HashMap<>(); this.networkCleanupCache = new HashMap<>(); } // // Callbacks from AbstractHandler // @Override public void processEvent(AbstractEvent abstractEvent) { if (!(abstractEvent instanceof NeutronL3AdapterEvent)) { LOG.error("Unable to process abstract event " + abstractEvent); return; } if (!this.enabled) { return; } NeutronL3AdapterEvent ev = (NeutronL3AdapterEvent) abstractEvent; switch (ev.getAction()) { case UPDATE: if (ev.getSubType() == NeutronL3AdapterEvent.SubType.SUBTYPE_EXTERNAL_MAC_UPDATE) { updateExternalRouterMac( ev.getMacAddress().getValue() ); } else { LOG.warn("Received update for an unexpected event " + ev); } break; case ADD: // fall through... // break; case DELETE: // fall through... // break; default: LOG.warn("Unable to process event " + ev); break; } } // // Callbacks from GatewayMacResolverListener // @Override public void gatewayMacResolved(Long externalNetworkBridgeDpid, IpAddress gatewayIpAddress, MacAddress macAddress) { LOG.info("got gatewayMacResolved callback for ip {} on dpid {} to mac {}", gatewayIpAddress, externalNetworkBridgeDpid, macAddress); if (!this.enabled) { return; } if (macAddress == null || macAddress.getValue() == null) { // TODO: handle cases when mac is null return; } // // Enqueue event so update is handled by adapter's thread // enqueueEvent( new NeutronL3AdapterEvent(externalNetworkBridgeDpid, gatewayIpAddress, macAddress) ); } private void populateL3ForwardingCaches() { if (!this.enabled) { return; } if(this.isCachePopulationDone || this.neutronFloatingIpCache == null || this.neutronPortCache == null ||this.neutronNetworkCache == null) { return; } this.isCachePopulationDone = true; LOG.debug("Populating NetVirt L3 caches from data store configuration"); Routers routers = this.neutronModelsDataStoreHelper.readAllNeutronRouters(); Ports ports = this.neutronModelsDataStoreHelper.readAllNeutronPorts(); if(routers != null && routers.getRouter() != null && ports != null) { LOG.debug("L3 Cache Population : {} Neutron router present in data store",routers.getRouter().size()); for( Router router : routers.getRouter()) { LOG.debug("L3 Cache Population : Populate caches for router {}",router); if(!ports.getPort().isEmpty()) { for( Port port : ports.getPort()) { if (port.getDeviceId().equals(router.getUuid().getValue()) && port.getDeviceOwner().equals(OWNER_ROUTER_INTERFACE)) { LOG.debug("L3 Cache Population : Router interface {} found.",port); networkIdToRouterMacCache.put(port.getNetworkId().getValue() , port.getMacAddress()); networkIdToRouterIpListCache.put(port.getNetworkId().getValue(), NeutronIAwareUtil.convertMDSalIpToNeutronIp(port.getFixedIps())); subnetIdToRouterInterfaceCache.put(port.getFixedIps().get(0).getSubnetId().getValue(), NeutronIAwareUtil.convertMDSalInterfaceToNeutronRouterInterface(port)); } } }else { LOG.warn("L3 Cache Population :Did not find any port information " + "in config Data Store for router {}",router); } } } LOG.debug("NetVirt L3 caches population is done"); } private Pair<Long, Uuid> getDpIdOfNeutronPort(String neutronTenantPortUuid) { if(neutronPortToDpIdCache.get(neutronTenantPortUuid) == null) { List<Node> bridges = this.southbound.readOvsdbTopologyBridgeNodes(); LOG.debug("getDpIdOfNeutronPort : {} bridges present in ovsdb topology",bridges.size()); for(Node bridge : bridges) { List<OvsdbTerminationPointAugmentation> interfaces = southbound.extractTerminationPointAugmentations(bridge); if(interfaces != null && !interfaces.isEmpty()) { LOG.debug("getDpIdOfNeutronPort : {} termination point present on bridge {}", interfaces.size(), bridge.getNodeId()); for (OvsdbTerminationPointAugmentation intf : interfaces) { NeutronPort neutronPort = tenantNetworkManager.getTenantPort(intf); if(neutronPort != null && neutronPort.getID().equals(neutronTenantPortUuid)) { Long dpId = getDpidForIntegrationBridge(bridge); Uuid interfaceUuid = intf.getInterfaceUuid(); LOG.debug("getDpIdOfNeutronPort : Found bridge {} and interface {} for the tenant neutron" + " port {}",dpId,interfaceUuid,neutronTenantPortUuid); handleInterfaceEventAdd(neutronPort.getPortUUID(), dpId, interfaceUuid); break; } } } } } return neutronPortToDpIdCache.get(neutronTenantPortUuid); } private Collection<FloatIpData> getAllFloatingIPsWithMetadata() { LOG.debug("getAllFloatingIPsWithMetadata : Fechting all floating Ips and it's metadata"); List<NeutronFloatingIP> neutronFloatingIps = neutronFloatingIpCache.getAllFloatingIPs(); if(neutronFloatingIps != null && !neutronFloatingIps.isEmpty()) { for (NeutronFloatingIP neutronFloatingIP : neutronFloatingIps) { if(!floatIpDataMapCache.containsKey(neutronFloatingIP.getID())){ LOG.debug("Metadata for floating ip {} is not present in the cache. " + "Fetching from data store.",neutronFloatingIP.getID()); this.getFloatingIPWithMetadata(neutronFloatingIP.getID()); } } } LOG.debug("getAllFloatingIPsWithMetadata : {} floating points found in data store",floatIpDataMapCache.size()); return floatIpDataMapCache.values(); } private FloatIpData getFloatingIPWithMetadata(String neutronFloatingId) { LOG.debug("getFloatingIPWithMetadata : Get Floating ip and it's meta data for neutron " + "floating id {} ",neutronFloatingId); if(floatIpDataMapCache.get(neutronFloatingId) == null) { NeutronFloatingIP neutronFloatingIP = neutronFloatingIpCache.getFloatingIP(neutronFloatingId); if (neutronFloatingIP == null) { LOG.error("getFloatingIPWithMetadata : Floating ip {} is missing from data store, that should not happen",neutronFloatingId); return null; } List<NeutronPort> neutronPorts = neutronPortCache.getAllPorts(); NeutronPort neutronPortForFloatIp = null; for (NeutronPort neutronPort : neutronPorts) { if (neutronPort.getDeviceOwner().equals(OWNER_FLOATING_IP) && neutronPort.getDeviceID().equals(neutronFloatingIP.getID())) { neutronPortForFloatIp = neutronPort; break; } } String neutronTenantPortUuid = neutronFloatingIP.getPortUUID(); if(neutronTenantPortUuid == null) { return null; } Pair<Long, Uuid> nodeIfPair = this.getDpIdOfNeutronPort(neutronTenantPortUuid); String floatingIpMac = neutronPortForFloatIp == null ? null : neutronPortForFloatIp.getMacAddress(); String fixedIpAddress = neutronFloatingIP.getFixedIPAddress(); String floatingIpAddress = neutronFloatingIP.getFloatingIPAddress(); NeutronPort tenantNeutronPort = neutronPortCache.getPort(neutronTenantPortUuid); NeutronNetwork tenantNeutronNetwork = tenantNeutronPort != null ? neutronNetworkCache.getNetwork(tenantNeutronPort.getNetworkUUID()) : null; String providerSegmentationId = tenantNeutronNetwork != null ? tenantNeutronNetwork.getProviderSegmentationID() : null; String neutronRouterMac = tenantNeutronNetwork != null ? networkIdToRouterMacCache.get(tenantNeutronNetwork.getID()) : null; if (nodeIfPair == null || neutronTenantPortUuid == null || providerSegmentationId == null || providerSegmentationId.isEmpty() || floatingIpMac == null || floatingIpMac.isEmpty() || neutronRouterMac == null || neutronRouterMac.isEmpty()) { LOG.debug("getFloatingIPWithMetadata :Floating IP {}<->{}, incomplete floatPort {} tenantPortUuid {} " + "seg {} mac {} rtrMac {}", fixedIpAddress, floatingIpAddress, neutronPortForFloatIp, neutronTenantPortUuid, providerSegmentationId, floatingIpMac, neutronRouterMac); return null; } // get ofport for patch port in br-int final Long dpId = nodeIfPair.getLeft(); final Long ofPort = findOFPortForExtPatch(dpId); if (ofPort == null) { LOG.warn("getFloatingIPWithMetadata : Unable to locate OF port of patch port " + "to connect floating ip to external bridge. dpid {}", dpId); return null; } final FloatIpData floatIpData = new FloatIpData(dpId, ofPort, providerSegmentationId, floatingIpMac, floatingIpAddress, fixedIpAddress, neutronRouterMac); floatIpDataMapCache.put(neutronFloatingIP.getID(), floatIpData); } return floatIpDataMapCache.get(neutronFloatingId); } /** * Invoked to configure the mac address for the external gateway in br-ex. ovsdb netvirt needs help in getting * mac for given ip in br-ex (bug 3378). For example, since ovsdb has no real arp, it needs a service in can * subscribe so that the mac address associated to the gateway ip address is available. * * @param externalRouterMacUpdate The mac address to be associated to the gateway. */ public void updateExternalRouterMac(final String externalRouterMacUpdate) { Preconditions.checkNotNull(externalRouterMacUpdate); flushExistingIpRewrite(); this.externalRouterMac = externalRouterMacUpdate; rebuildExistingIpRewrite(); } /** * Process the event. * * @param action the {@link org.opendaylight.ovsdb.openstack.netvirt.api.Action} action to be handled. * @param subnet An instance of NeutronSubnet object. */ public void handleNeutronSubnetEvent(final NeutronSubnet subnet, Action action) { LOG.debug("Neutron subnet {} event : {}", action, subnet.toString()); if (action == Action.ADD) { this.storeNetworkInCleanupCache(neutronNetworkCache.getNetwork(subnet.getNetworkUUID())); } } /** * Process the port event as a router interface event. * For a not delete action, since a port is only create when the tennat uses the subnet, it is required to * verify if all routers across all nodes have the interface for the port's subnet(s) configured. * * @param action the {@link org.opendaylight.ovsdb.openstack.netvirt.api.Action} action to be handled. * @param neutronPort An instance of NeutronPort object. */ public void handleNeutronPortEvent(final NeutronPort neutronPort, Action action) { LOG.debug("Neutron port {} event : {}", action, neutronPort.toString()); if (action == Action.UPDATE) { // FIXME: Bug 4971 Move cleanup cache to SG Impl this.updatePortInCleanupCache(neutronPort, neutronPort.getOriginalPort()); this.processSecurityGroupUpdate(neutronPort); } if (!this.enabled) { return; } final boolean isDelete = action == Action.DELETE; if (action == Action.DELETE) { // Bug 5164: Cleanup Floating IP OpenFlow Rules when port is deleted. this.cleanupFloatingIPRules(neutronPort); } else if (action == Action.UPDATE){ // Bug 5353: VM restart cause floatingIp flows to be removed this.updateFloatingIPRules(neutronPort); } if (neutronPort.getDeviceOwner().equalsIgnoreCase(OWNER_ROUTER_GATEWAY)){ if (!isDelete) { LOG.info("Port {} is network router gateway interface, " + "triggering gateway resolution for the attached external network", neutronPort); this.triggerGatewayMacResolver(neutronPort); }else{ NeutronNetwork externalNetwork = neutronNetworkCache.getNetwork(neutronPort.getNetworkUUID()); if (null == externalNetwork) { externalNetwork = this.getNetworkFromCleanupCache(neutronPort.getNetworkUUID()); } if (externalNetwork != null && externalNetwork.isRouterExternal()) { final NeutronSubnet externalSubnet = getExternalNetworkSubnet(neutronPort); // TODO support IPv6 if (externalSubnet != null && externalSubnet.getIpVersion() == 4) { gatewayMacResolver.stopPeriodicRefresh(new Ipv4Address(externalSubnet.getGatewayIP())); } } } } // Treat the port event as a router interface event if the port belongs to router. This is a // helper for handling cases when handleNeutronRouterInterfaceEvent is not available // if (neutronPort.getDeviceOwner().equalsIgnoreCase(OWNER_ROUTER_INTERFACE) || neutronPort.getDeviceOwner().equalsIgnoreCase(OWNER_ROUTER_INTERFACE_DISTRIBUTED)) { if (neutronPort.getFixedIPs() != null) { for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) { NeutronRouter_Interface neutronRouterInterface = new NeutronRouter_Interface(neutronIP.getSubnetUUID(), neutronPort.getPortUUID()); // id of router interface to be same as subnet neutronRouterInterface.setID(neutronIP.getSubnetUUID()); neutronRouterInterface.setTenantID(neutronPort.getTenantID()); this.handleNeutronRouterInterfaceEvent(null /*neutronRouter*/, neutronRouterInterface, action); } } } else { // We made it here, port is not used as a router interface. If this is not a delete action, make sure that // all nodes that are supposed to have a router interface for the port's subnet(s), have it configured. We // need to do this check here because a router interface is not added to a node until tenant becomes needed // there. // if (!isDelete && neutronPort.getFixedIPs() != null) { for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) { NeutronRouter_Interface neutronRouterInterface = subnetIdToRouterInterfaceCache.get(neutronIP.getSubnetUUID()); if (neutronRouterInterface != null) { this.handleNeutronRouterInterfaceEvent(null /*neutronRouter*/, neutronRouterInterface, action); } } } this.updateL3ForNeutronPort(neutronPort, isDelete); } } /** * Process the event. * * @param action the {@link org.opendaylight.ovsdb.openstack.netvirt.api.Action} action to be handled. * @param neutronRouter An instance of NeutronRouter object. */ public void handleNeutronRouterEvent(final NeutronRouter neutronRouter, Action action) { LOG.debug("Neutron router {} event : {}", action, neutronRouter.toString()); } /** * Process the event enforcing actions and verifying dependencies between all router's interface. For example, * delete the ports on the same subnet. * * @param action the {@link org.opendaylight.ovsdb.openstack.netvirt.api.Action} action to be handled. * @param neutronRouter An instance of NeutronRouter object. * @param neutronRouterInterface An instance of NeutronRouter_Interface object. */ public void handleNeutronRouterInterfaceEvent(final NeutronRouter neutronRouter, final NeutronRouter_Interface neutronRouterInterface, Action action) { LOG.debug("Router interface {} got event {}. Subnet {}", neutronRouterInterface.getPortUUID(), action, neutronRouterInterface.getSubnetUUID()); if (!this.enabled) { return; } final boolean isDelete = action == Action.DELETE; this.programFlowsForNeutronRouterInterface(neutronRouterInterface, isDelete); // As neutron router interface is added/removed, we need to iterate through all the neutron ports and // see if they are affected by l3 // for (NeutronPort neutronPort : neutronPortCache.getAllPorts()) { boolean currPortShouldBeDeleted = false; // Note: delete in this case only applies to 1)router interface delete and 2)ports on the same subnet if (isDelete) { if (neutronPort.getFixedIPs() != null) { for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) { if (neutronRouterInterface.getSubnetUUID().equalsIgnoreCase(neutronIP.getSubnetUUID())) { currPortShouldBeDeleted = true; break; } } } } this.updateL3ForNeutronPort(neutronPort, currPortShouldBeDeleted); } } /** * Invoked when a neutron message regarding the floating ip association is sent to odl via ml2. If the action is * a creation, it will first add ARP rules for the given floating ip and then configure the DNAT (rewrite the * packets from the floating IP address to the internal fixed ip) rules on OpenFlow Table 30 and SNAT rules (other * way around) on OpenFlow Table 100. * * @param actionIn the {@link org.opendaylight.ovsdb.openstack.netvirt.api.Action} action to be handled. * @param neutronFloatingIP An {@link org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronFloatingIP} instance of NeutronFloatingIP object. */ public void handleNeutronFloatingIPEvent(final NeutronFloatingIP neutronFloatingIP, Action actionIn) { Preconditions.checkNotNull(neutronFloatingIP); LOG.debug(" Floating IP {} {}<->{}, network uuid {}", actionIn, neutronFloatingIP.getFixedIPAddress(), neutronFloatingIP.getFloatingIPAddress(), neutronFloatingIP.getFloatingNetworkUUID()); if (!this.enabled) { return; } Action action; // Consider action to be delete if getFixedIPAddress is null // if (neutronFloatingIP.getFixedIPAddress() == null) { action = Action.DELETE; } else { action = actionIn; } // this.programFlowsForFloatingIP(neutronFloatingIP, action == Action.DELETE); if (action != Action.DELETE) { // must be first, as it updates floatIpDataMapCache programFlowsForFloatingIPArpAdd(neutronFloatingIP); programFlowsForFloatingIPInbound(neutronFloatingIP, Action.ADD); programFlowsForFloatingIPOutbound(neutronFloatingIP, Action.ADD); } else { programFlowsForFloatingIPOutbound(neutronFloatingIP, Action.DELETE); programFlowsForFloatingIPInbound(neutronFloatingIP, Action.DELETE); // must be last, as it updates floatIpDataMapCache programFlowsForFloatingIPArpDelete(neutronFloatingIP.getID()); } } /** * This method performs creation or deletion of in-bound rules into Table 30 for a existing available floating * ip, otherwise for newer one. */ private void programFlowsForFloatingIPInbound(final NeutronFloatingIP neutronFloatingIP, final Action action) { Preconditions.checkNotNull(neutronFloatingIP); final FloatIpData fid = getFloatingIPWithMetadata(neutronFloatingIP.getID()); if (fid == null) { LOG.trace("programFlowsForFloatingIPInboundAdd {} for {} uuid {} not in local cache", action, neutronFloatingIP.getFloatingIPAddress(), neutronFloatingIP.getID()); return; } programInboundIpRewriteStage1(fid.dpid, fid.ofPort, fid.segId, fid.floatingIpAddress, fid.fixedIpAddress, action); } /** * This method performs creation or deletion of out-bound rules into Table 100 for a existing available floating * ip, otherwise for newer one. */ private void programFlowsForFloatingIPOutbound(final NeutronFloatingIP neutronFloatingIP, final Action action) { Preconditions.checkNotNull(neutronFloatingIP); final FloatIpData fid = getFloatingIPWithMetadata(neutronFloatingIP.getID()); if (fid == null) { LOG.trace("programFlowsForFloatingIPOutbound {} for {} uuid {} not in local cache", action, neutronFloatingIP.getFloatingIPAddress(), neutronFloatingIP.getID()); return; } programOutboundIpRewriteStage1(fid, action); } private void flushExistingIpRewrite() { for (FloatIpData fid : getAllFloatingIPsWithMetadata()) { programOutboundIpRewriteStage1(fid, Action.DELETE); } } private void rebuildExistingIpRewrite() { for (FloatIpData fid : getAllFloatingIPsWithMetadata()) { programOutboundIpRewriteStage1(fid, Action.ADD); } } /** * This method creates ARP response rules into OpenFlow Table 30 for a given floating ip. In order to connect * to br-ex from br-int, a patch-port is used. Thus, the patch-port will be responsible to respond the ARP * requests. */ private void programFlowsForFloatingIPArpAdd(final NeutronFloatingIP neutronFloatingIP) { Preconditions.checkNotNull(neutronFloatingIP); Preconditions.checkNotNull(neutronFloatingIP.getFixedIPAddress()); Preconditions.checkNotNull(neutronFloatingIP.getFloatingIPAddress()); // find bridge Node where floating ip is configured by looking up cache for its port final NeutronPort neutronPortForFloatIp = findNeutronPortForFloatingIp(neutronFloatingIP.getID()); final String neutronTenantPortUuid = neutronFloatingIP.getPortUUID(); final Pair<Long, Uuid> nodeIfPair = this.getDpIdOfNeutronPort(neutronTenantPortUuid); final String floatingIpMac = neutronPortForFloatIp == null ? null : neutronPortForFloatIp.getMacAddress(); final String fixedIpAddress = neutronFloatingIP.getFixedIPAddress(); final String floatingIpAddress = neutronFloatingIP.getFloatingIPAddress(); final NeutronPort tenantNeutronPort = neutronPortCache.getPort(neutronTenantPortUuid); final NeutronNetwork tenantNeutronNetwork = tenantNeutronPort != null ? neutronNetworkCache.getNetwork(tenantNeutronPort.getNetworkUUID()) : null; final String providerSegmentationId = tenantNeutronNetwork != null ? tenantNeutronNetwork.getProviderSegmentationID() : null; final String neutronRouterMac = tenantNeutronNetwork != null ? networkIdToRouterMacCache.get(tenantNeutronNetwork.getID()) : null; if (nodeIfPair == null || neutronTenantPortUuid == null || providerSegmentationId == null || providerSegmentationId.isEmpty() || floatingIpMac == null || floatingIpMac.isEmpty() || neutronRouterMac == null || neutronRouterMac.isEmpty()) { LOG.trace("Floating IP {}<->{}, incomplete floatPort {} tenantPortUuid {} seg {} mac {} rtrMac {}", fixedIpAddress, floatingIpAddress, neutronPortForFloatIp, neutronTenantPortUuid, providerSegmentationId, floatingIpMac, neutronRouterMac); return; } // get ofport for patch port in br-int final Long dpId = nodeIfPair.getLeft(); final Long ofPort = findOFPortForExtPatch(dpId); if (ofPort == null) { LOG.warn("Unable to locate OF port of patch port to connect floating ip to external bridge. dpid {}", dpId); return; } // Respond to ARPs for the floating ip address by default, via the patch port that connects br-int to br-ex // if (distributedArpService.programStaticRuleStage1(dpId, encodeExcplicitOFPort(ofPort), floatingIpMac, floatingIpAddress, Action.ADD)) { final FloatIpData floatIpData = new FloatIpData(dpId, ofPort, providerSegmentationId, floatingIpMac, floatingIpAddress, fixedIpAddress, neutronRouterMac); floatIpDataMapCache.put(neutronFloatingIP.getID(), floatIpData); LOG.info("Floating IP {}<->{} programmed ARP mac {} on OFport {} seg {} dpid {}", neutronFloatingIP.getFixedIPAddress(), neutronFloatingIP.getFloatingIPAddress(), floatingIpMac, ofPort, providerSegmentationId, dpId); } } private void programFlowsForFloatingIPArpDelete(final String neutronFloatingIPUuid) { final FloatIpData floatIpData = getFloatingIPWithMetadata(neutronFloatingIPUuid); if (floatIpData == null) { LOG.trace("programFlowsForFloatingIPArpDelete for uuid {} is not needed", neutronFloatingIPUuid); return; } if (distributedArpService.programStaticRuleStage1(floatIpData.dpid, encodeExcplicitOFPort(floatIpData.ofPort), floatIpData.macAddress, floatIpData.floatingIpAddress, Action.DELETE)) { floatIpDataMapCache.remove(neutronFloatingIPUuid); LOG.info("Floating IP {} un-programmed ARP mac {} on {} dpid {}", floatIpData.floatingIpAddress, floatIpData.macAddress, floatIpData.ofPort, floatIpData.dpid); } } private NeutronPort findNeutronPortForFloatingIp(final String floatingIpUuid) { for (NeutronPort neutronPort : neutronPortCache.getAllPorts()) { if (neutronPort.getDeviceOwner().equals(OWNER_FLOATING_IP) && neutronPort.getDeviceID().equals(floatingIpUuid)) { return neutronPort; } } return null; } private Long findOFPortForExtPatch(Long dpId) { final String brInt = configurationService.getIntegrationBridgeName(); final String brExt = configurationService.getExternalBridgeName(); final String portNameInt = configurationService.getPatchPortName(new ImmutablePair<>(brInt, brExt)); Preconditions.checkNotNull(dpId); Preconditions.checkNotNull(portNameInt); final long dpidPrimitive = dpId; for (Node node : nodeCacheManager.getBridgeNodes()) { if (dpidPrimitive == southbound.getDataPathId(node)) { final OvsdbTerminationPointAugmentation terminationPointOfBridge = southbound.getTerminationPointOfBridge(node, portNameInt); return terminationPointOfBridge == null ? null : terminationPointOfBridge.getOfport(); } } return null; } /** * Process the event. * * @param action the {@link org.opendaylight.ovsdb.openstack.netvirt.api.Action} action to be handled. * @param neutronNetwork An {@link org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronNetwork} instance of NeutronFloatingIP object. */ public void handleNeutronNetworkEvent(final NeutronNetwork neutronNetwork, Action action) { LOG.debug("neutronNetwork {}: network: {}", action, neutronNetwork); if (action == Action.UPDATE) { this.updateNetworkInCleanupCache(neutronNetwork); } } // // Callbacks from OVSDB's southbound handler // /** * Process the event. * * @param bridgeNode An instance of Node object. * @param intf An {@link org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105 * .OvsdbTerminationPointAugmentation} instance of OvsdbTerminationPointAugmentation object. * @param neutronNetwork An {@link org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronNetwork} instance of NeutronNetwork * object. * @param action the {@link org.opendaylight.ovsdb.openstack.netvirt.api.Action} action to be handled. */ public void handleInterfaceEvent(final Node bridgeNode, final OvsdbTerminationPointAugmentation intf, final NeutronNetwork neutronNetwork, Action action) { LOG.debug("southbound interface {} node:{} interface:{}, neutronNetwork:{}", action, bridgeNode.getNodeId().getValue(), intf.getName(), neutronNetwork); final NeutronPort neutronPort = tenantNetworkManager.getTenantPort(intf); if (action != Action.DELETE && neutronPort != null) { // FIXME: Bug 4971 Move cleanup cache to SG Impl storePortInCleanupCache(neutronPort); } if (!this.enabled) { return; } final Long dpId = getDpidForIntegrationBridge(bridgeNode); final Uuid interfaceUuid = intf.getInterfaceUuid(); LOG.trace("southbound interface {} node:{} interface:{}, neutronNetwork:{} port:{} dpid:{} intfUuid:{}", action, bridgeNode.getNodeId().getValue(), intf.getName(), neutronNetwork, neutronPort, dpId, interfaceUuid); if (neutronPort != null) { final String neutronPortUuid = neutronPort.getPortUUID(); if (action != Action.DELETE && dpId != null && interfaceUuid != null) { handleInterfaceEventAdd(neutronPortUuid, dpId, interfaceUuid); } handleNeutronPortEvent(neutronPort, action); } if (action == Action.DELETE && interfaceUuid != null) { handleInterfaceEventDelete(intf, dpId); } } private void handleInterfaceEventAdd(final String neutronPortUuid, Long dpId, final Uuid interfaceUuid) { neutronPortToDpIdCache.put(neutronPortUuid, new ImmutablePair<>(dpId, interfaceUuid)); LOG.debug("handleInterfaceEvent add cache entry NeutronPortUuid {} : dpid {}, ifUuid {}", neutronPortUuid, dpId, interfaceUuid.getValue()); } private void handleInterfaceEventDelete(final OvsdbTerminationPointAugmentation intf, final Long dpId) { // Remove entry from neutronPortToDpIdCache based on interface uuid for (Map.Entry<String, Pair<Long, Uuid>> entry : neutronPortToDpIdCache.entrySet()) { final String currPortUuid = entry.getKey(); if (intf.getInterfaceUuid().equals(entry.getValue().getRight())) { LOG.debug("handleInterfaceEventDelete remove cache entry NeutronPortUuid {} : dpid {}, ifUuid {}", currPortUuid, dpId, intf.getInterfaceUuid().getValue()); neutronPortToDpIdCache.remove(currPortUuid); break; } } } // // Internal helpers // private void updateL3ForNeutronPort(final NeutronPort neutronPort, final boolean isDelete) { final String networkUUID = neutronPort.getNetworkUUID(); final String routerMacAddress = networkIdToRouterMacCache.get(networkUUID); if(!isDelete) { // If there is no router interface handling the networkUUID, we are done if (routerMacAddress == null || routerMacAddress.isEmpty()) { return; } // If this is the neutron port for the router interface itself, ignore it as well. Ports that represent the // router interface are handled via handleNeutronRouterInterfaceEvent. if (routerMacAddress.equalsIgnoreCase(neutronPort.getMacAddress())) { return; } } final NeutronNetwork neutronNetwork = neutronNetworkCache.getNetwork(networkUUID); final String providerSegmentationId = neutronNetwork != null ? neutronNetwork.getProviderSegmentationID() : null; final String tenantMac = neutronPort.getMacAddress(); if (providerSegmentationId == null || providerSegmentationId.isEmpty() || tenantMac == null || tenantMac.isEmpty()) { // done: go no further w/out all the info needed... return; } final Action action = isDelete ? Action.DELETE : Action.ADD; List<Node> nodes = nodeCacheManager.getBridgeNodes(); if (nodes.isEmpty()) { LOG.trace("updateL3ForNeutronPort has no nodes to work with"); } for (Node node : nodes) { final Long dpid = getDpidForIntegrationBridge(node); if (dpid == null) { continue; } if (neutronPort.getFixedIPs() == null) { continue; } for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) { final String tenantIpStr = neutronIP.getIpAddress(); if (tenantIpStr.isEmpty()) { continue; } // Configure L3 fwd. We do that regardless of tenant network present, because these rules are // still needed when routing to subnets non-local to node (bug 2076). programL3ForwardingStage1(node, dpid, providerSegmentationId, tenantMac, tenantIpStr, action); } } } private void processSecurityGroupUpdate(NeutronPort neutronPort) { LOG.trace("processSecurityGroupUpdate:" + neutronPort); /** * Get updated data and original data for the the changed. Identify the security groups that got * added and removed and call the appropriate providers for updating the flows. */ try { NeutronPort originalPort = neutronPort.getOriginalPort(); List<NeutronSecurityGroup> addedGroup = getsecurityGroupChanged(neutronPort, neutronPort.getOriginalPort()); List<NeutronSecurityGroup> deletedGroup = getsecurityGroupChanged(neutronPort.getOriginalPort(), neutronPort); if (null != addedGroup && !addedGroup.isEmpty()) { securityServicesManager.syncSecurityGroup(neutronPort,addedGroup,true); } if (null != deletedGroup && !deletedGroup.isEmpty()) { securityServicesManager.syncSecurityGroup(neutronPort,deletedGroup,false); } } catch (Exception e) { LOG.error("Exception in processSecurityGroupUpdate", e); } } private List<NeutronSecurityGroup> getsecurityGroupChanged(NeutronPort port1, NeutronPort port2) { LOG.trace("getsecurityGroupChanged:" + "Port1:" + port1 + "Port2" + port2); if (port1 == null) { return null; } List<NeutronSecurityGroup> list1 = new ArrayList<>(port1.getSecurityGroups()); if (port2 == null) { return list1; } List<NeutronSecurityGroup> list2 = new ArrayList<>(port2.getSecurityGroups()); for (Iterator<NeutronSecurityGroup> iterator = list1.iterator(); iterator.hasNext();) { NeutronSecurityGroup securityGroup1 = iterator.next(); for (NeutronSecurityGroup securityGroup2 :list2) { if (securityGroup1.getID().equals(securityGroup2.getID())) { iterator.remove(); } } } return list1; } private void programL3ForwardingStage1(Node node, Long dpid, String providerSegmentationId, String macAddress, String ipStr, Action actionForNode) { if (actionForNode == Action.DELETE) { LOG.trace("Deleting Flow : programL3ForwardingStage1 for node {} providerId {} mac {} ip {} action {}", node.getNodeId().getValue(), providerSegmentationId, macAddress, ipStr, actionForNode); } if (actionForNode == Action.ADD) { LOG.trace("Adding Flow : programL3ForwardingStage1 for node {} providerId {} mac {} ip {} action {}", node.getNodeId().getValue(), providerSegmentationId, macAddress, ipStr, actionForNode); } this.programL3ForwardingStage2(node, dpid, providerSegmentationId, macAddress, ipStr, actionForNode); } private Status programL3ForwardingStage2(Node node, Long dpid, String providerSegmentationId, String macAddress, String address, Action actionForNode) { Status status; try { InetAddress inetAddress = InetAddress.getByName(address); status = l3ForwardingProvider == null ? new Status(StatusCode.SUCCESS) : l3ForwardingProvider.programForwardingTableEntry(dpid, providerSegmentationId, inetAddress, macAddress, actionForNode); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } if (status.isSuccess()) { LOG.debug("ProgramL3Forwarding {} for mac:{} addr:{} node:{} action:{}", l3ForwardingProvider == null ? "skipped" : "programmed", macAddress, address, node.getNodeId().getValue(), actionForNode); } else { LOG.error("ProgramL3Forwarding failed for mac:{} addr:{} node:{} action:{} status:{}", macAddress, address, node.getNodeId().getValue(), actionForNode, status); } return status; } // -- private void programFlowsForNeutronRouterInterface(final NeutronRouter_Interface destNeutronRouterInterface, Boolean isDelete) { Preconditions.checkNotNull(destNeutronRouterInterface); final NeutronPort neutronPort = neutronPortCache.getPort(destNeutronRouterInterface.getPortUUID()); String macAddress = neutronPort != null ? neutronPort.getMacAddress() : null; List<Neutron_IPs> ipList = neutronPort != null ? neutronPort.getFixedIPs() : null; final NeutronSubnet subnet = neutronSubnetCache.getSubnet(destNeutronRouterInterface.getSubnetUUID()); final NeutronNetwork neutronNetwork = subnet != null ? neutronNetworkCache.getNetwork(subnet.getNetworkUUID()) : null; final String destinationSegmentationId = neutronNetwork != null ? neutronNetwork.getProviderSegmentationID() : null; final Boolean isExternal = neutronNetwork != null ? neutronNetwork.getRouterExternal() : Boolean.TRUE; final String cidr = subnet != null ? subnet.getCidr() : null; final int mask = getMaskLenFromCidr(cidr); LOG.trace("programFlowsForNeutronRouterInterface called for interface {} isDelete {}", destNeutronRouterInterface, isDelete); // in delete path, mac address as well as ip address are not provided. Being so, let's find them from // the local cache if (neutronNetwork != null) { if (macAddress == null || macAddress.isEmpty()) { macAddress = networkIdToRouterMacCache.get(neutronNetwork.getNetworkUUID()); } if (ipList == null || ipList.isEmpty()) { ipList = networkIdToRouterIpListCache.get(neutronNetwork.getNetworkUUID()); } } if (destinationSegmentationId == null || destinationSegmentationId.isEmpty() || cidr == null || cidr.isEmpty() || macAddress == null || macAddress.isEmpty() || ipList == null || ipList.isEmpty()) { LOG.debug("programFlowsForNeutronRouterInterface is bailing seg:{} cidr:{} mac:{} ip:{}", destinationSegmentationId, cidr, macAddress, ipList); // done: go no further w/out all the info needed... return; } final Action actionForNode = isDelete ? Action.DELETE : Action.ADD; // Keep cache for finding router's mac from network uuid -- add // if (! isDelete) { networkIdToRouterMacCache.put(neutronNetwork.getNetworkUUID(), macAddress); networkIdToRouterIpListCache.put(neutronNetwork.getNetworkUUID(), new ArrayList<>(ipList)); subnetIdToRouterInterfaceCache.put(subnet.getSubnetUUID(), destNeutronRouterInterface); } List<Node> nodes = nodeCacheManager.getBridgeNodes(); if (nodes.isEmpty()) { LOG.trace("programFlowsForNeutronRouterInterface has no nodes to work with"); } for (Node node : nodes) { final Long dpid = getDpidForIntegrationBridge(node); if (dpid == null) { continue; } for (Neutron_IPs neutronIP : ipList) { final String ipStr = neutronIP.getIpAddress(); if (ipStr.isEmpty()) { LOG.debug("programFlowsForNeutronRouterInterface is skipping node {} ip {}", node.getNodeId().getValue(), ipStr); continue; } // Iterate through all other interfaces and add/remove reflexive flows to this interface // for (NeutronRouter_Interface srcNeutronRouterInterface : subnetIdToRouterInterfaceCache.values()) { programFlowsForNeutronRouterInterfacePair(node, dpid, srcNeutronRouterInterface, destNeutronRouterInterface, neutronNetwork, destinationSegmentationId, macAddress, ipStr, mask, actionForNode, true /*isReflexsive*/); } if (! isExternal) { programFlowForNetworkFromExternal(node, dpid, destinationSegmentationId, macAddress, ipStr, mask, actionForNode); } // Enable ARP responder by default, because router interface needs to be responded always. distributedArpService.programStaticRuleStage1(dpid, destinationSegmentationId, macAddress, ipStr, actionForNode); programIcmpEcho(dpid, destinationSegmentationId, macAddress, ipStr, actionForNode); } // Compute action to be programmed. In the case of rewrite exclusions, we must never program rules // for the external neutron networks. // { final Action actionForRewriteExclusion = isExternal ? Action.DELETE : actionForNode; programIpRewriteExclusionStage1(node, dpid, destinationSegmentationId, cidr, actionForRewriteExclusion); } } if (isDelete) { networkIdToRouterMacCache.remove(neutronNetwork.getNetworkUUID()); networkIdToRouterIpListCache.remove(neutronNetwork.getNetworkUUID()); subnetIdToRouterInterfaceCache.remove(subnet.getSubnetUUID()); } } private void programFlowForNetworkFromExternal(final Node node, final Long dpid, final String destinationSegmentationId, final String dstMacAddress, final String destIpStr, final int destMask, final Action actionForNode) { programRouterInterfaceStage1(node, dpid, Constants.EXTERNAL_NETWORK, destinationSegmentationId, dstMacAddress, destIpStr, destMask, actionForNode); } private void programFlowsForNeutronRouterInterfacePair(final Node node, final Long dpid, final NeutronRouter_Interface srcNeutronRouterInterface, final NeutronRouter_Interface dstNeutronRouterInterface, final NeutronNetwork dstNeutronNetwork, final String destinationSegmentationId, final String dstMacAddress, final String destIpStr, final int destMask, final Action actionForNode, Boolean isReflexsive) { Preconditions.checkNotNull(srcNeutronRouterInterface); Preconditions.checkNotNull(dstNeutronRouterInterface); final String sourceSubnetId = srcNeutronRouterInterface.getSubnetUUID(); if (sourceSubnetId == null) { LOG.error("Could not get provider Subnet ID from router interface {}", srcNeutronRouterInterface.getID()); return; } final NeutronSubnet sourceSubnet = neutronSubnetCache.getSubnet(sourceSubnetId); final String sourceNetworkId = sourceSubnet == null ? null : sourceSubnet.getNetworkUUID(); if (sourceNetworkId == null) { LOG.error("Could not get provider Network ID from subnet {}", sourceSubnetId); return; } final NeutronNetwork sourceNetwork = neutronNetworkCache.getNetwork(sourceNetworkId); if (sourceNetwork == null) { LOG.error("Could not get provider Network for Network ID {}", sourceNetworkId); return; } if (! sourceNetwork.getTenantID().equals(dstNeutronNetwork.getTenantID())) { // Isolate subnets from different tenants within the same router return; } final String sourceSegmentationId = sourceNetwork.getProviderSegmentationID(); if (sourceSegmentationId == null) { LOG.error("Could not get provider Segmentation ID for Subnet {}", sourceSubnetId); return; } if (sourceSegmentationId.equals(destinationSegmentationId)) { // Skip 'self' return; } programRouterInterfaceStage1(node, dpid, sourceSegmentationId, destinationSegmentationId, dstMacAddress, destIpStr, destMask, actionForNode); // Flip roles src->dst; dst->src if (isReflexsive) { final NeutronPort sourceNeutronPort = neutronPortCache.getPort(srcNeutronRouterInterface.getPortUUID()); final String macAddress2 = sourceNeutronPort != null ? sourceNeutronPort.getMacAddress() : null; final List<Neutron_IPs> ipList2 = sourceNeutronPort != null ? sourceNeutronPort.getFixedIPs() : null; final String cidr2 = sourceSubnet.getCidr(); final int mask2 = getMaskLenFromCidr(cidr2); if (cidr2 == null || cidr2.isEmpty() || macAddress2 == null || macAddress2.isEmpty() || ipList2 == null || ipList2.isEmpty()) { LOG.trace("programFlowsForNeutronRouterInterfacePair reflexive is bailing seg:{} cidr:{} mac:{} ip:{}", sourceSegmentationId, cidr2, macAddress2, ipList2); // done: go no further w/out all the info needed... return; } for (Neutron_IPs neutronIP2 : ipList2) { final String ipStr2 = neutronIP2.getIpAddress(); if (ipStr2.isEmpty()) { continue; } programFlowsForNeutronRouterInterfacePair(node, dpid, dstNeutronRouterInterface, srcNeutronRouterInterface, sourceNetwork, sourceSegmentationId, macAddress2, ipStr2, mask2, actionForNode, false /*isReflexsive*/); } } } private void programRouterInterfaceStage1(Node node, Long dpid, String sourceSegmentationId, String destinationSegmentationId, String macAddress, String ipStr, int mask, Action actionForNode) { if (actionForNode == Action.DELETE) { LOG.trace("Deleting Flow : programRouterInterfaceStage1 for node {} sourceSegId {} destSegId {} mac {} ip {} mask {}" + " action {}", node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId, macAddress, ipStr, mask, actionForNode); } if (actionForNode == Action.ADD) { LOG.trace("Adding Flow : programRouterInterfaceStage1 for node {} sourceSegId {} destSegId {} mac {} ip {} mask {}" + " action {}", node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId, macAddress, ipStr, mask, actionForNode); } this.programRouterInterfaceStage2(node, dpid, sourceSegmentationId, destinationSegmentationId, macAddress, ipStr, mask, actionForNode); } private Status programRouterInterfaceStage2(Node node, Long dpid, String sourceSegmentationId, String destinationSegmentationId, String macAddress, String address, int mask, Action actionForNode) { Status status; try { InetAddress inetAddress = InetAddress.getByName(address); status = routingProvider == null ? new Status(StatusCode.SUCCESS) : routingProvider.programRouterInterface(dpid, sourceSegmentationId, destinationSegmentationId, macAddress, inetAddress, mask, actionForNode); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } if (status.isSuccess()) { LOG.debug("programRouterInterfaceStage2 {} for mac:{} addr:{}/{} node:{} srcTunId:{} destTunId:{} action:{}", routingProvider == null ? "skipped" : "programmed", macAddress, address, mask, node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId, actionForNode); } else { LOG.error("programRouterInterfaceStage2 failed for mac:{} addr:{}/{} node:{} srcTunId:{} destTunId:{} action:{} status:{}", macAddress, address, mask, node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId, actionForNode, status); } return status; } private boolean programIcmpEcho(Long dpid, String segOrOfPort, String macAddress, String ipStr, Action action) { if (action == Action.DELETE ) { LOG.trace("Deleting Flow : programIcmpEcho dpid {} segOrOfPort {} mac {} ip {} action {}", dpid, segOrOfPort, macAddress, ipStr, action); } if (action == Action.ADD) { LOG.trace("Adding Flow : programIcmpEcho dpid {} segOrOfPort {} mac {} ip {} action {}", dpid, segOrOfPort, macAddress, ipStr, action); } Status status = new Status(StatusCode.UNSUPPORTED); if (icmpEchoProvider != null){ try { InetAddress inetAddress = InetAddress.getByName(ipStr); status = icmpEchoProvider.programIcmpEchoEntry(dpid, segOrOfPort, macAddress, inetAddress, action); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } } if (status.isSuccess()) { LOG.debug("programIcmpEcho {} for mac:{} addr:{} dpid:{} segOrOfPort:{} action:{}", icmpEchoProvider == null ? "skipped" : "programmed", macAddress, ipStr, dpid, segOrOfPort, action); } else { LOG.error("programIcmpEcho failed for mac:{} addr:{} dpid:{} segOrOfPort:{} action:{} status:{}", macAddress, ipStr, dpid, segOrOfPort, action, status); } return status.isSuccess(); } private boolean programInboundIpRewriteStage1(Long dpid, Long inboundOFPort, String providerSegmentationId, String matchAddress, String rewriteAddress, Action action) { if (action == Action.DELETE ) { LOG.trace("Deleting Flow : programInboundIpRewriteStage1 dpid {} OFPort {} seg {} matchAddress {} rewriteAddress {}" + " action {}", dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action); } if (action == Action.ADD ) { LOG.trace("Adding Flow : programInboundIpRewriteStage1 dpid {} OFPort {} seg {} matchAddress {} rewriteAddress {}" + " action {}", dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action); } Status status = programInboundIpRewriteStage2(dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action); return status.isSuccess(); } private Status programInboundIpRewriteStage2(Long dpid, Long inboundOFPort, String providerSegmentationId, String matchAddress, String rewriteAddress, Action action) { Status status; try { InetAddress inetMatchAddress = InetAddress.getByName(matchAddress); InetAddress inetRewriteAddress = InetAddress.getByName(rewriteAddress); status = inboundNatProvider == null ? new Status(StatusCode.SUCCESS) : inboundNatProvider.programIpRewriteRule(dpid, inboundOFPort, providerSegmentationId, inetMatchAddress, inetRewriteAddress, action); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } if (status.isSuccess()) { final boolean isSkipped = inboundNatProvider == null; LOG.debug("programInboundIpRewriteStage2 {} for dpid:{} ofPort:{} seg:{} match:{} rewrite:{} action:{}", isSkipped ? "skipped" : "programmed", dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action); } else { LOG.error("programInboundIpRewriteStage2 failed for dpid:{} ofPort:{} seg:{} match:{} rewrite:{} action:{}" + " status:{}", dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action, status); } return status; } private void programIpRewriteExclusionStage1(Node node, Long dpid, String providerSegmentationId, String cidr, Action actionForRewriteExclusion) { if (actionForRewriteExclusion == Action.DELETE ) { LOG.trace("Deleting Flow : programIpRewriteExclusionStage1 node {} providerId {} cidr {} action {}", node.getNodeId().getValue(), providerSegmentationId, cidr, actionForRewriteExclusion); } if (actionForRewriteExclusion == Action.ADD) { LOG.trace("Adding Flow : programIpRewriteExclusionStage1 node {} providerId {} cidr {} action {}", node.getNodeId().getValue(), providerSegmentationId, cidr, actionForRewriteExclusion); } this.programIpRewriteExclusionStage2(node, dpid, providerSegmentationId, cidr,actionForRewriteExclusion); } private Status programIpRewriteExclusionStage2(Node node, Long dpid, String providerSegmentationId, String cidr, Action actionForNode) { final Status status = outboundNatProvider == null ? new Status(StatusCode.SUCCESS) : outboundNatProvider.programIpRewriteExclusion(dpid, providerSegmentationId, cidr, actionForNode); if (status.isSuccess()) { final boolean isSkipped = outboundNatProvider == null; LOG.debug("IpRewriteExclusion {} for cidr:{} node:{} action:{}", isSkipped ? "skipped" : "programmed", cidr, node.getNodeId().getValue(), actionForNode); } else { LOG.error("IpRewriteExclusion failed for cidr:{} node:{} action:{} status:{}", cidr, node.getNodeId().getValue(), actionForNode, status); } return status; } private void programOutboundIpRewriteStage1(FloatIpData fid, Action action) { if (action == Action.DELETE) { LOG.trace("Deleting Flow : programOutboundIpRewriteStage1 dpid {} seg {} fixedIpAddress {} floatIp {} action {} ", fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action); } if (action == Action.ADD) { LOG.trace("Adding Flow : programOutboundIpRewriteStage1 dpid {} seg {} fixedIpAddress {} floatIp {} action {} " , fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action); } this.programOutboundIpRewriteStage2(fid, action); } private Status programOutboundIpRewriteStage2(FloatIpData fid, Action action) { Status status; try { InetAddress matchSrcAddress = InetAddress.getByName(fid.fixedIpAddress); InetAddress rewriteSrcAddress = InetAddress.getByName(fid.floatingIpAddress); status = outboundNatProvider == null ? new Status(StatusCode.SUCCESS) : outboundNatProvider.programIpRewriteRule( fid.dpid, fid.segId, fid.neutronRouterMac, matchSrcAddress, fid.macAddress, this.externalRouterMac, rewriteSrcAddress, fid.ofPort, action); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } if (status.isSuccess()) { final boolean isSkipped = outboundNatProvider == null; LOG.debug("programOutboundIpRewriteStage2 {} for dpid {} seg {} fixedIpAddress {} floatIp {}" + " action {}", isSkipped ? "skipped" : "programmed", fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action); } else { LOG.error("programOutboundIpRewriteStage2 failed for dpid {} seg {} fixedIpAddress {} floatIp {}" + " action {} status:{}", fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action, status); } return status; } private int getMaskLenFromCidr(String cidr) { if (cidr == null) { return 0; } String[] splits = cidr.split("/"); if (splits.length != 2) { return 0; } int result; try { result = Integer.parseInt(splits[1].trim()); } catch (NumberFormatException nfe) { result = 0; } return result; } private Long getDpidForIntegrationBridge(Node node) { // Check if node is integration bridge; and only then return its dpid if (southbound.getBridge(node, configurationService.getIntegrationBridgeName()) != null) { return southbound.getDataPathId(node); } return null; } private Long getDpidForExternalBridge(Node node) { // Check if node is external bridge; and only then return its dpid if (southbound.getBridge(node, configurationService.getExternalBridgeName()) != null) { return southbound.getDataPathId(node); } return null; } private Node getExternalBridgeNode(){ //Pickup the first node that has external bridge (br-ex). //NOTE: We are assuming that all the br-ex are serving one external network and gateway ip of //the external network is reachable from every br-ex // TODO: Consider other deployment scenario, and thing of better solution. List<Node> allBridges = nodeCacheManager.getBridgeNodes(); for(Node node : allBridges){ if (southbound.getBridge(node, configurationService.getExternalBridgeName()) != null) { return node; } } return null; } private NeutronSubnet getExternalNetworkSubnet(NeutronPort gatewayPort){ if (gatewayPort.getFixedIPs() == null) { return null; } for (Neutron_IPs neutronIPs : gatewayPort.getFixedIPs()) { String subnetUUID = neutronIPs.getSubnetUUID(); NeutronSubnet extSubnet = neutronSubnetCache.getSubnet(subnetUUID); if (extSubnet != null && extSubnet.getGatewayIP() != null) { return extSubnet; } if (extSubnet == null) { // TODO: when subnet is created, try again. LOG.debug("subnet {} in not found", subnetUUID); } } return null; } private void cleanupFloatingIPRules(final NeutronPort neutronPort) { List<NeutronFloatingIP> neutronFloatingIps = neutronFloatingIpCache.getAllFloatingIPs(); if (neutronFloatingIps != null && !neutronFloatingIps.isEmpty()) { for (NeutronFloatingIP neutronFloatingIP : neutronFloatingIps) { if (neutronFloatingIP.getPortUUID().equals(neutronPort.getPortUUID())) { handleNeutronFloatingIPEvent(neutronFloatingIP, Action.DELETE); } } } } private void updateFloatingIPRules(final NeutronPort neutronPort) { List<NeutronFloatingIP> neutronFloatingIps = neutronFloatingIpCache.getAllFloatingIPs(); if (neutronFloatingIps != null) { for (NeutronFloatingIP neutronFloatingIP : neutronFloatingIps) { if (neutronFloatingIP.getPortUUID().equals(neutronPort.getPortUUID())) { handleNeutronFloatingIPEvent(neutronFloatingIP, Action.UPDATE); } } } } private void triggerGatewayMacResolver(final NeutronPort gatewayPort){ Preconditions.checkNotNull(gatewayPort); NeutronNetwork externalNetwork = neutronNetworkCache.getNetwork(gatewayPort.getNetworkUUID()); if(externalNetwork != null){ if(externalNetwork.isRouterExternal()){ final NeutronSubnet externalSubnet = getExternalNetworkSubnet(gatewayPort); // TODO: address IPv6 case. if (externalSubnet != null && externalSubnet.getIpVersion() == 4 && gatewayPort.getFixedIPs() != null) { LOG.info("Trigger MAC resolution for gateway ip {}", externalSubnet.getGatewayIP()); Neutron_IPs neutronIP = null; for (Neutron_IPs nIP : gatewayPort.getFixedIPs()) { InetAddress ipAddress; try { ipAddress = InetAddress.getByName(nIP.getIpAddress()); } catch (UnknownHostException e) { LOG.warn("unknown host exception {}", e); continue; } if (ipAddress instanceof Inet4Address) { neutronIP = nIP; break; } } if (neutronIP == null) { // TODO IPv6 neighbor discovery LOG.debug("Ignoring gateway ports with IPv6 only fixed ip {}", gatewayPort.getFixedIPs()); } else { gatewayMacResolver.resolveMacAddress( this, /* gatewayMacResolverListener */ null, /* externalNetworkBridgeDpid */ true, /* refreshExternalNetworkBridgeDpidIfNeeded */ new Ipv4Address(externalSubnet.getGatewayIP()), new Ipv4Address(neutronIP.getIpAddress()), new MacAddress(gatewayPort.getMacAddress()), true /* periodicRefresh */); } } else { LOG.warn("No gateway IP address found for external network {}", externalNetwork); } } }else{ LOG.warn("Neutron network not found for router interface {}", gatewayPort); } } private void storePortInCleanupCache(NeutronPort port) { this.portCleanupCache.put(port.getPortUUID(),port); } private void updatePortInCleanupCache(NeutronPort updatedPort,NeutronPort originalPort) { removePortFromCleanupCache(originalPort); storePortInCleanupCache(updatedPort); } public void removePortFromCleanupCache(NeutronPort port) { if(port != null) { this.portCleanupCache.remove(port.getPortUUID()); } } public Map<String, NeutronPort> getPortCleanupCache() { return this.portCleanupCache; } public NeutronPort getPortFromCleanupCache(String portid) { for (String neutronPortUuid : this.portCleanupCache.keySet()) { if (neutronPortUuid.equals(portid)) { LOG.info("getPortFromCleanupCache: Matching NeutronPort found {}", portid); return this.portCleanupCache.get(neutronPortUuid); } } return null; } private void storeNetworkInCleanupCache(NeutronNetwork network) { this.networkCleanupCache.put(network.getNetworkUUID(), network); } private void updateNetworkInCleanupCache(NeutronNetwork network) { for (String neutronNetworkUuid:this.networkCleanupCache.keySet()) { if (neutronNetworkUuid.equals(network.getNetworkUUID())) { this.networkCleanupCache.remove(neutronNetworkUuid); } } this.networkCleanupCache.put(network.getNetworkUUID(), network); } public void removeNetworkFromCleanupCache(String networkid) { NeutronNetwork network = null; for (String neutronNetworkUuid:this.networkCleanupCache.keySet()) { if (neutronNetworkUuid.equals(networkid)) { network = networkCleanupCache.get(neutronNetworkUuid); break; } } if (network != null) { for (String neutronPortUuid:this.portCleanupCache.keySet()) { if (this.portCleanupCache.get(neutronPortUuid).getNetworkUUID().equals(network.getNetworkUUID())) { LOG.info("This network is used by another port", network); return; } } this.networkCleanupCache.remove(network.getNetworkUUID()); } } public Map<String, NeutronNetwork> getNetworkCleanupCache() { return this.networkCleanupCache; } public NeutronNetwork getNetworkFromCleanupCache(String networkid) { for (String neutronNetworkUuid:this.networkCleanupCache.keySet()) { if (neutronNetworkUuid.equals(networkid)) { LOG.info("getPortFromCleanupCache: Matching NeutronPort found {}", networkid); return networkCleanupCache.get(neutronNetworkUuid); } } return null; } /** * Return String that represents OF port with marker explicitly provided (reverse of MatchUtils:parseExplicitOFPort) * * @param ofPort the OF port number * @return the string with encoded OF port (example format "OFPort|999") */ public static String encodeExcplicitOFPort(Long ofPort) { return "OFPort|" + ofPort.toString(); } private void initNetworkCleanUpCache() { if (this.neutronNetworkCache != null) { for (NeutronNetwork neutronNetwork : neutronNetworkCache.getAllNetworks()) { networkCleanupCache.put(neutronNetwork.getNetworkUUID(), neutronNetwork); } } } private void initPortCleanUpCache() { if (this.neutronPortCache != null) { for (NeutronPort neutronPort : neutronPortCache.getAllPorts()) { portCleanupCache.put(neutronPort.getPortUUID(), neutronPort); } } } @Override public void setDependencies(ServiceReference serviceReference) { eventDispatcher = (EventDispatcher) ServiceHelper.getGlobalInstance(EventDispatcher.class, this); eventDispatcher.eventHandlerAdded(serviceReference, this); tenantNetworkManager = (TenantNetworkManager) ServiceHelper.getGlobalInstance(TenantNetworkManager.class, this); configurationService = (ConfigurationService) ServiceHelper.getGlobalInstance(ConfigurationService.class, this); arpProvider = (ArpProvider) ServiceHelper.getGlobalInstance(ArpProvider.class, this); inboundNatProvider = (InboundNatProvider) ServiceHelper.getGlobalInstance(InboundNatProvider.class, this); outboundNatProvider = (OutboundNatProvider) ServiceHelper.getGlobalInstance(OutboundNatProvider.class, this); routingProvider = (RoutingProvider) ServiceHelper.getGlobalInstance(RoutingProvider.class, this); l3ForwardingProvider = (L3ForwardingProvider) ServiceHelper.getGlobalInstance(L3ForwardingProvider.class, this); distributedArpService = (DistributedArpService) ServiceHelper.getGlobalInstance(DistributedArpService.class, this); nodeCacheManager = (NodeCacheManager) ServiceHelper.getGlobalInstance(NodeCacheManager.class, this); southbound = (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this); gatewayMacResolver = (GatewayMacResolver) ServiceHelper.getGlobalInstance(GatewayMacResolver.class, this); securityServicesManager = (SecurityServicesManager) ServiceHelper.getGlobalInstance(SecurityServicesManager.class, this); initL3AdapterMembers(); } @Override public void setDependencies(Object impl) { if (impl instanceof INeutronNetworkCRUD) { neutronNetworkCache = (INeutronNetworkCRUD)impl; initNetworkCleanUpCache(); } else if (impl instanceof INeutronPortCRUD) { neutronPortCache = (INeutronPortCRUD)impl; initPortCleanUpCache(); } else if (impl instanceof INeutronSubnetCRUD) { neutronSubnetCache = (INeutronSubnetCRUD)impl; } else if (impl instanceof INeutronFloatingIPCRUD) { neutronFloatingIpCache = (INeutronFloatingIPCRUD)impl; } else if (impl instanceof ArpProvider) { arpProvider = (ArpProvider)impl; } else if (impl instanceof InboundNatProvider) { inboundNatProvider = (InboundNatProvider)impl; } else if (impl instanceof OutboundNatProvider) { outboundNatProvider = (OutboundNatProvider)impl; } else if (impl instanceof RoutingProvider) { routingProvider = (RoutingProvider)impl; } else if (impl instanceof L3ForwardingProvider) { l3ForwardingProvider = (L3ForwardingProvider)impl; }else if (impl instanceof GatewayMacResolver) { gatewayMacResolver = (GatewayMacResolver)impl; }else if (impl instanceof IcmpEchoProvider) { icmpEchoProvider = (IcmpEchoProvider)impl; } populateL3ForwardingCaches(); } }
openstack/net-virt/src/main/java/org/opendaylight/ovsdb/openstack/netvirt/impl/NeutronL3Adapter.java
/* * Copyright (c) 2014 - 2016 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.ovsdb.openstack.netvirt.impl; import com.google.common.base.Preconditions; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.opendaylight.ovsdb.openstack.netvirt.AbstractEvent; import org.opendaylight.ovsdb.openstack.netvirt.AbstractHandler; import org.opendaylight.ovsdb.openstack.netvirt.ConfigInterface; import org.opendaylight.ovsdb.openstack.netvirt.NeutronL3AdapterEvent; import org.opendaylight.ovsdb.openstack.netvirt.api.Action; import org.opendaylight.ovsdb.openstack.netvirt.api.ArpProvider; import org.opendaylight.ovsdb.openstack.netvirt.api.ConfigurationService; import org.opendaylight.ovsdb.openstack.netvirt.api.Constants; import org.opendaylight.ovsdb.openstack.netvirt.api.EventDispatcher; import org.opendaylight.ovsdb.openstack.netvirt.api.GatewayMacResolver; import org.opendaylight.ovsdb.openstack.netvirt.api.GatewayMacResolverListener; import org.opendaylight.ovsdb.openstack.netvirt.api.IcmpEchoProvider; import org.opendaylight.ovsdb.openstack.netvirt.api.InboundNatProvider; import org.opendaylight.ovsdb.openstack.netvirt.api.L3ForwardingProvider; import org.opendaylight.ovsdb.openstack.netvirt.api.NodeCacheManager; import org.opendaylight.ovsdb.openstack.netvirt.api.OutboundNatProvider; import org.opendaylight.ovsdb.openstack.netvirt.api.RoutingProvider; import org.opendaylight.ovsdb.openstack.netvirt.api.SecurityServicesManager; import org.opendaylight.ovsdb.openstack.netvirt.api.Southbound; import org.opendaylight.ovsdb.openstack.netvirt.api.Status; import org.opendaylight.ovsdb.openstack.netvirt.api.StatusCode; import org.opendaylight.ovsdb.openstack.netvirt.api.TenantNetworkManager; import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronFloatingIP; import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronNetwork; import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronPort; import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronRouter; import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronRouter_Interface; import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronSecurityGroup; import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronSubnet; import org.opendaylight.ovsdb.openstack.netvirt.translator.Neutron_IPs; import org.opendaylight.ovsdb.openstack.netvirt.translator.crud.INeutronFloatingIPCRUD; import org.opendaylight.ovsdb.openstack.netvirt.translator.crud.INeutronNetworkCRUD; import org.opendaylight.ovsdb.openstack.netvirt.translator.crud.INeutronPortCRUD; import org.opendaylight.ovsdb.openstack.netvirt.translator.crud.INeutronSubnetCRUD; import org.opendaylight.ovsdb.openstack.netvirt.translator.iaware.impl.NeutronIAwareUtil; import org.opendaylight.ovsdb.utils.neutron.utils.NeutronModelsDataStoreHelper; import org.opendaylight.ovsdb.utils.servicehelper.ServiceHelper; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.Routers; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.Router; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentation; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node; import org.osgi.framework.ServiceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.Inet4Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * Neutron L3 Adapter implements a hub-like adapter for the various Neutron events. Based on * these events, the abstract router callbacks can be generated to the multi-tenant aware router, * as well as the multi-tenant router forwarding provider. */ public class NeutronL3Adapter extends AbstractHandler implements GatewayMacResolverListener, ConfigInterface { private static final Logger LOG = LoggerFactory.getLogger(NeutronL3Adapter.class); // The implementation for each of these services is resolved by the OSGi Service Manager private volatile ConfigurationService configurationService; private volatile TenantNetworkManager tenantNetworkManager; private volatile NodeCacheManager nodeCacheManager; private volatile INeutronNetworkCRUD neutronNetworkCache; private volatile INeutronSubnetCRUD neutronSubnetCache; private volatile INeutronPortCRUD neutronPortCache; private volatile INeutronFloatingIPCRUD neutronFloatingIpCache; private volatile L3ForwardingProvider l3ForwardingProvider; private volatile InboundNatProvider inboundNatProvider; private volatile OutboundNatProvider outboundNatProvider; private volatile ArpProvider arpProvider; private volatile RoutingProvider routingProvider; private volatile GatewayMacResolver gatewayMacResolver; private volatile SecurityServicesManager securityServicesManager; private volatile IcmpEchoProvider icmpEchoProvider; private class FloatIpData { // br-int of node where floating ip is associated with tenant port private final Long dpid; // patch port in br-int used to reach br-ex private final Long ofPort; // segmentation id of the net where fixed ip is instantiated private final String segId; // mac address assigned to neutron port of floating ip private final String macAddress; private final String floatingIpAddress; // ip address given to tenant vm private final String fixedIpAddress; private final String neutronRouterMac; FloatIpData(final Long dpid, final Long ofPort, final String segId, final String macAddress, final String floatingIpAddress, final String fixedIpAddress, final String neutronRouterMac) { this.dpid = dpid; this.ofPort = ofPort; this.segId = segId; this.macAddress = macAddress; this.floatingIpAddress = floatingIpAddress; this.fixedIpAddress = fixedIpAddress; this.neutronRouterMac = neutronRouterMac; } } private Map<String, String> networkIdToRouterMacCache; private Map<String, List<Neutron_IPs>> networkIdToRouterIpListCache; private Map<String, NeutronRouter_Interface> subnetIdToRouterInterfaceCache; private Map<String, Pair<Long, Uuid>> neutronPortToDpIdCache; private Map<String, FloatIpData> floatIpDataMapCache; private String externalRouterMac; private Boolean enabled = false; private Boolean isCachePopulationDone = false; private Map<String, NeutronPort> portCleanupCache; private Map<String, NeutronNetwork> networkCleanupCache; private Southbound southbound; private DistributedArpService distributedArpService; private NeutronModelsDataStoreHelper neutronModelsDataStoreHelper; private static final String OWNER_ROUTER_INTERFACE = "network:router_interface"; private static final String OWNER_ROUTER_INTERFACE_DISTRIBUTED = "network:router_interface_distributed"; private static final String OWNER_ROUTER_GATEWAY = "network:router_gateway"; private static final String OWNER_FLOATING_IP = "network:floatingip"; private static final String DEFAULT_EXT_RTR_MAC = "00:00:5E:00:01:01"; public NeutronL3Adapter(NeutronModelsDataStoreHelper neutronHelper) { LOG.info(">>>>>> NeutronL3Adapter constructor {}", this.getClass()); this.neutronModelsDataStoreHelper = neutronHelper; } private void initL3AdapterMembers() { Preconditions.checkNotNull(configurationService); if (configurationService.isL3ForwardingEnabled()) { this.networkIdToRouterMacCache = new HashMap<>(); this.networkIdToRouterIpListCache = new HashMap<>(); this.subnetIdToRouterInterfaceCache = new HashMap<>(); this.neutronPortToDpIdCache = new HashMap<>(); this.floatIpDataMapCache = new HashMap<>(); this.externalRouterMac = configurationService.getDefaultGatewayMacAddress(null); if (this.externalRouterMac == null) { this.externalRouterMac = DEFAULT_EXT_RTR_MAC; } this.enabled = true; LOG.info("OVSDB L3 forwarding is enabled"); } else { LOG.debug("OVSDB L3 forwarding is disabled"); } this.portCleanupCache = new HashMap<>(); this.networkCleanupCache = new HashMap<>(); } // // Callbacks from AbstractHandler // @Override public void processEvent(AbstractEvent abstractEvent) { if (!(abstractEvent instanceof NeutronL3AdapterEvent)) { LOG.error("Unable to process abstract event " + abstractEvent); return; } if (!this.enabled) { return; } NeutronL3AdapterEvent ev = (NeutronL3AdapterEvent) abstractEvent; switch (ev.getAction()) { case UPDATE: if (ev.getSubType() == NeutronL3AdapterEvent.SubType.SUBTYPE_EXTERNAL_MAC_UPDATE) { updateExternalRouterMac( ev.getMacAddress().getValue() ); } else { LOG.warn("Received update for an unexpected event " + ev); } break; case ADD: // fall through... // break; case DELETE: // fall through... // break; default: LOG.warn("Unable to process event " + ev); break; } } // // Callbacks from GatewayMacResolverListener // @Override public void gatewayMacResolved(Long externalNetworkBridgeDpid, IpAddress gatewayIpAddress, MacAddress macAddress) { LOG.info("got gatewayMacResolved callback for ip {} on dpid {} to mac {}", gatewayIpAddress, externalNetworkBridgeDpid, macAddress); if (!this.enabled) { return; } if (macAddress == null || macAddress.getValue() == null) { // TODO: handle cases when mac is null return; } // // Enqueue event so update is handled by adapter's thread // enqueueEvent( new NeutronL3AdapterEvent(externalNetworkBridgeDpid, gatewayIpAddress, macAddress) ); } private void populateL3ForwardingCaches() { if (!this.enabled) { return; } if(this.isCachePopulationDone || this.neutronFloatingIpCache == null || this.neutronPortCache == null ||this.neutronNetworkCache == null) { return; } this.isCachePopulationDone = true; LOG.debug("Populating NetVirt L3 caches from data store configuration"); Routers routers = this.neutronModelsDataStoreHelper.readAllNeutronRouters(); Ports ports = this.neutronModelsDataStoreHelper.readAllNeutronPorts(); if(routers != null && routers.getRouter() != null && ports != null) { LOG.debug("L3 Cache Population : {} Neutron router present in data store",routers.getRouter().size()); for( Router router : routers.getRouter()) { LOG.debug("L3 Cache Population : Populate caches for router {}",router); if(!ports.getPort().isEmpty()) { for( Port port : ports.getPort()) { if (port.getDeviceId().equals(router.getUuid().getValue()) && port.getDeviceOwner().equals(OWNER_ROUTER_INTERFACE)) { LOG.debug("L3 Cache Population : Router interface {} found.",port); networkIdToRouterMacCache.put(port.getNetworkId().getValue() , port.getMacAddress()); networkIdToRouterIpListCache.put(port.getNetworkId().getValue(), NeutronIAwareUtil.convertMDSalIpToNeutronIp(port.getFixedIps())); subnetIdToRouterInterfaceCache.put(port.getFixedIps().get(0).getSubnetId().getValue(), NeutronIAwareUtil.convertMDSalInterfaceToNeutronRouterInterface(port)); } } }else { LOG.warn("L3 Cache Population :Did not find any port information " + "in config Data Store for router {}",router); } } } LOG.debug("NetVirt L3 caches population is done"); } private Pair<Long, Uuid> getDpIdOfNeutronPort(String neutronTenantPortUuid) { if(neutronPortToDpIdCache.get(neutronTenantPortUuid) == null) { List<Node> bridges = this.southbound.readOvsdbTopologyBridgeNodes(); LOG.debug("getDpIdOfNeutronPort : {} bridges present in ovsdb topology",bridges.size()); for(Node bridge : bridges) { List<OvsdbTerminationPointAugmentation> interfaces = southbound.extractTerminationPointAugmentations(bridge); if(interfaces != null && !interfaces.isEmpty()) { LOG.debug("getDpIdOfNeutronPort : {} termination point present on bridge {}", interfaces.size(), bridge.getNodeId()); for (OvsdbTerminationPointAugmentation intf : interfaces) { NeutronPort neutronPort = tenantNetworkManager.getTenantPort(intf); if(neutronPort != null && neutronPort.getID().equals(neutronTenantPortUuid)) { Long dpId = getDpidForIntegrationBridge(bridge); Uuid interfaceUuid = intf.getInterfaceUuid(); LOG.debug("getDpIdOfNeutronPort : Found bridge {} and interface {} for the tenant neutron" + " port {}",dpId,interfaceUuid,neutronTenantPortUuid); handleInterfaceEventAdd(neutronPort.getPortUUID(), dpId, interfaceUuid); break; } } } } } return neutronPortToDpIdCache.get(neutronTenantPortUuid); } private Collection<FloatIpData> getAllFloatingIPsWithMetadata() { LOG.debug("getAllFloatingIPsWithMetadata : Fechting all floating Ips and it's metadata"); List<NeutronFloatingIP> neutronFloatingIps = neutronFloatingIpCache.getAllFloatingIPs(); if(neutronFloatingIps != null && !neutronFloatingIps.isEmpty()) { for (NeutronFloatingIP neutronFloatingIP : neutronFloatingIps) { if(!floatIpDataMapCache.containsKey(neutronFloatingIP.getID())){ LOG.debug("Metadata for floating ip {} is not present in the cache. " + "Fetching from data store.",neutronFloatingIP.getID()); this.getFloatingIPWithMetadata(neutronFloatingIP.getID()); } } } LOG.debug("getAllFloatingIPsWithMetadata : {} floating points found in data store",floatIpDataMapCache.size()); return floatIpDataMapCache.values(); } private FloatIpData getFloatingIPWithMetadata(String neutronFloatingId) { LOG.debug("getFloatingIPWithMetadata : Get Floating ip and it's meta data for neutron " + "floating id {} ",neutronFloatingId); if(floatIpDataMapCache.get(neutronFloatingId) == null) { NeutronFloatingIP neutronFloatingIP = neutronFloatingIpCache.getFloatingIP(neutronFloatingId); if (neutronFloatingIP == null) { LOG.error("getFloatingIPWithMetadata : Floating ip {} is missing from data store, that should not happen",neutronFloatingId); return null; } List<NeutronPort> neutronPorts = neutronPortCache.getAllPorts(); NeutronPort neutronPortForFloatIp = null; for (NeutronPort neutronPort : neutronPorts) { if (neutronPort.getDeviceOwner().equals(OWNER_FLOATING_IP) && neutronPort.getDeviceID().equals(neutronFloatingIP.getID())) { neutronPortForFloatIp = neutronPort; break; } } String neutronTenantPortUuid = neutronFloatingIP.getPortUUID(); if(neutronTenantPortUuid == null) { return null; } Pair<Long, Uuid> nodeIfPair = this.getDpIdOfNeutronPort(neutronTenantPortUuid); String floatingIpMac = neutronPortForFloatIp == null ? null : neutronPortForFloatIp.getMacAddress(); String fixedIpAddress = neutronFloatingIP.getFixedIPAddress(); String floatingIpAddress = neutronFloatingIP.getFloatingIPAddress(); NeutronPort tenantNeutronPort = neutronPortCache.getPort(neutronTenantPortUuid); NeutronNetwork tenantNeutronNetwork = tenantNeutronPort != null ? neutronNetworkCache.getNetwork(tenantNeutronPort.getNetworkUUID()) : null; String providerSegmentationId = tenantNeutronNetwork != null ? tenantNeutronNetwork.getProviderSegmentationID() : null; String neutronRouterMac = tenantNeutronNetwork != null ? networkIdToRouterMacCache.get(tenantNeutronNetwork.getID()) : null; if (nodeIfPair == null || neutronTenantPortUuid == null || providerSegmentationId == null || providerSegmentationId.isEmpty() || floatingIpMac == null || floatingIpMac.isEmpty() || neutronRouterMac == null || neutronRouterMac.isEmpty()) { LOG.debug("getFloatingIPWithMetadata :Floating IP {}<->{}, incomplete floatPort {} tenantPortUuid {} " + "seg {} mac {} rtrMac {}", fixedIpAddress, floatingIpAddress, neutronPortForFloatIp, neutronTenantPortUuid, providerSegmentationId, floatingIpMac, neutronRouterMac); return null; } // get ofport for patch port in br-int final Long dpId = nodeIfPair.getLeft(); final Long ofPort = findOFPortForExtPatch(dpId); if (ofPort == null) { LOG.warn("getFloatingIPWithMetadata : Unable to locate OF port of patch port " + "to connect floating ip to external bridge. dpid {}", dpId); return null; } final FloatIpData floatIpData = new FloatIpData(dpId, ofPort, providerSegmentationId, floatingIpMac, floatingIpAddress, fixedIpAddress, neutronRouterMac); floatIpDataMapCache.put(neutronFloatingIP.getID(), floatIpData); } return floatIpDataMapCache.get(neutronFloatingId); } /** * Invoked to configure the mac address for the external gateway in br-ex. ovsdb netvirt needs help in getting * mac for given ip in br-ex (bug 3378). For example, since ovsdb has no real arp, it needs a service in can * subscribe so that the mac address associated to the gateway ip address is available. * * @param externalRouterMacUpdate The mac address to be associated to the gateway. */ public void updateExternalRouterMac(final String externalRouterMacUpdate) { Preconditions.checkNotNull(externalRouterMacUpdate); flushExistingIpRewrite(); this.externalRouterMac = externalRouterMacUpdate; rebuildExistingIpRewrite(); } /** * Process the event. * * @param action the {@link org.opendaylight.ovsdb.openstack.netvirt.api.Action} action to be handled. * @param subnet An instance of NeutronSubnet object. */ public void handleNeutronSubnetEvent(final NeutronSubnet subnet, Action action) { LOG.debug("Neutron subnet {} event : {}", action, subnet.toString()); if (action == Action.ADD) { this.storeNetworkInCleanupCache(neutronNetworkCache.getNetwork(subnet.getNetworkUUID())); } } /** * Process the port event as a router interface event. * For a not delete action, since a port is only create when the tennat uses the subnet, it is required to * verify if all routers across all nodes have the interface for the port's subnet(s) configured. * * @param action the {@link org.opendaylight.ovsdb.openstack.netvirt.api.Action} action to be handled. * @param neutronPort An instance of NeutronPort object. */ public void handleNeutronPortEvent(final NeutronPort neutronPort, Action action) { LOG.debug("Neutron port {} event : {}", action, neutronPort.toString()); if (action == Action.UPDATE) { // FIXME: Bug 4971 Move cleanup cache to SG Impl this.updatePortInCleanupCache(neutronPort, neutronPort.getOriginalPort()); this.processSecurityGroupUpdate(neutronPort); } if (!this.enabled) { return; } final boolean isDelete = action == Action.DELETE; if (action == Action.DELETE) { // Bug 5164: Cleanup Floating IP OpenFlow Rules when port is deleted. this.cleanupFloatingIPRules(neutronPort); } else if (action == Action.UPDATE){ // Bug 5353: VM restart cause floatingIp flows to be removed this.updateFloatingIPRules(neutronPort); } if (neutronPort.getDeviceOwner().equalsIgnoreCase(OWNER_ROUTER_GATEWAY)){ if (!isDelete) { LOG.info("Port {} is network router gateway interface, " + "triggering gateway resolution for the attached external network", neutronPort); this.triggerGatewayMacResolver(neutronPort); }else{ NeutronNetwork externalNetwork = neutronNetworkCache.getNetwork(neutronPort.getNetworkUUID()); if (null == externalNetwork) { externalNetwork = this.getNetworkFromCleanupCache(neutronPort.getNetworkUUID()); } if (externalNetwork != null && externalNetwork.isRouterExternal()) { final NeutronSubnet externalSubnet = getExternalNetworkSubnet(neutronPort); // TODO support IPv6 if (externalSubnet != null && externalSubnet.getIpVersion() == 4) { gatewayMacResolver.stopPeriodicRefresh(new Ipv4Address(externalSubnet.getGatewayIP())); } } } } // Treat the port event as a router interface event if the port belongs to router. This is a // helper for handling cases when handleNeutronRouterInterfaceEvent is not available // if (neutronPort.getDeviceOwner().equalsIgnoreCase(OWNER_ROUTER_INTERFACE) || neutronPort.getDeviceOwner().equalsIgnoreCase(OWNER_ROUTER_INTERFACE_DISTRIBUTED)) { if (neutronPort.getFixedIPs() != null) { for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) { NeutronRouter_Interface neutronRouterInterface = new NeutronRouter_Interface(neutronIP.getSubnetUUID(), neutronPort.getPortUUID()); // id of router interface to be same as subnet neutronRouterInterface.setID(neutronIP.getSubnetUUID()); neutronRouterInterface.setTenantID(neutronPort.getTenantID()); this.handleNeutronRouterInterfaceEvent(null /*neutronRouter*/, neutronRouterInterface, action); } } } else { // We made it here, port is not used as a router interface. If this is not a delete action, make sure that // all nodes that are supposed to have a router interface for the port's subnet(s), have it configured. We // need to do this check here because a router interface is not added to a node until tenant becomes needed // there. // if (!isDelete && neutronPort.getFixedIPs() != null) { for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) { NeutronRouter_Interface neutronRouterInterface = subnetIdToRouterInterfaceCache.get(neutronIP.getSubnetUUID()); if (neutronRouterInterface != null) { this.handleNeutronRouterInterfaceEvent(null /*neutronRouter*/, neutronRouterInterface, action); } } } this.updateL3ForNeutronPort(neutronPort, isDelete); } } /** * Process the event. * * @param action the {@link org.opendaylight.ovsdb.openstack.netvirt.api.Action} action to be handled. * @param neutronRouter An instance of NeutronRouter object. */ public void handleNeutronRouterEvent(final NeutronRouter neutronRouter, Action action) { LOG.debug("Neutron router {} event : {}", action, neutronRouter.toString()); } /** * Process the event enforcing actions and verifying dependencies between all router's interface. For example, * delete the ports on the same subnet. * * @param action the {@link org.opendaylight.ovsdb.openstack.netvirt.api.Action} action to be handled. * @param neutronRouter An instance of NeutronRouter object. * @param neutronRouterInterface An instance of NeutronRouter_Interface object. */ public void handleNeutronRouterInterfaceEvent(final NeutronRouter neutronRouter, final NeutronRouter_Interface neutronRouterInterface, Action action) { LOG.debug("Router interface {} got event {}. Subnet {}", neutronRouterInterface.getPortUUID(), action, neutronRouterInterface.getSubnetUUID()); if (!this.enabled) { return; } final boolean isDelete = action == Action.DELETE; this.programFlowsForNeutronRouterInterface(neutronRouterInterface, isDelete); // As neutron router interface is added/removed, we need to iterate through all the neutron ports and // see if they are affected by l3 // for (NeutronPort neutronPort : neutronPortCache.getAllPorts()) { boolean currPortShouldBeDeleted = false; // Note: delete in this case only applies to 1)router interface delete and 2)ports on the same subnet if (isDelete) { if (neutronPort.getFixedIPs() != null) { for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) { if (neutronRouterInterface.getSubnetUUID().equalsIgnoreCase(neutronIP.getSubnetUUID())) { currPortShouldBeDeleted = true; break; } } } } this.updateL3ForNeutronPort(neutronPort, currPortShouldBeDeleted); } } /** * Invoked when a neutron message regarding the floating ip association is sent to odl via ml2. If the action is * a creation, it will first add ARP rules for the given floating ip and then configure the DNAT (rewrite the * packets from the floating IP address to the internal fixed ip) rules on OpenFlow Table 30 and SNAT rules (other * way around) on OpenFlow Table 100. * * @param actionIn the {@link org.opendaylight.ovsdb.openstack.netvirt.api.Action} action to be handled. * @param neutronFloatingIP An {@link org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronFloatingIP} instance of NeutronFloatingIP object. */ public void handleNeutronFloatingIPEvent(final NeutronFloatingIP neutronFloatingIP, Action actionIn) { Preconditions.checkNotNull(neutronFloatingIP); LOG.debug(" Floating IP {} {}<->{}, network uuid {}", actionIn, neutronFloatingIP.getFixedIPAddress(), neutronFloatingIP.getFloatingIPAddress(), neutronFloatingIP.getFloatingNetworkUUID()); if (!this.enabled) { return; } Action action; // Consider action to be delete if getFixedIPAddress is null // if (neutronFloatingIP.getFixedIPAddress() == null) { action = Action.DELETE; } else { action = actionIn; } // this.programFlowsForFloatingIP(neutronFloatingIP, action == Action.DELETE); if (action != Action.DELETE) { // must be first, as it updates floatIpDataMapCache programFlowsForFloatingIPArpAdd(neutronFloatingIP); programFlowsForFloatingIPInbound(neutronFloatingIP, Action.ADD); programFlowsForFloatingIPOutbound(neutronFloatingIP, Action.ADD); } else { programFlowsForFloatingIPOutbound(neutronFloatingIP, Action.DELETE); programFlowsForFloatingIPInbound(neutronFloatingIP, Action.DELETE); // must be last, as it updates floatIpDataMapCache programFlowsForFloatingIPArpDelete(neutronFloatingIP.getID()); } } /** * This method performs creation or deletion of in-bound rules into Table 30 for a existing available floating * ip, otherwise for newer one. */ private void programFlowsForFloatingIPInbound(final NeutronFloatingIP neutronFloatingIP, final Action action) { Preconditions.checkNotNull(neutronFloatingIP); final FloatIpData fid = getFloatingIPWithMetadata(neutronFloatingIP.getID()); if (fid == null) { LOG.trace("programFlowsForFloatingIPInboundAdd {} for {} uuid {} not in local cache", action, neutronFloatingIP.getFloatingIPAddress(), neutronFloatingIP.getID()); return; } programInboundIpRewriteStage1(fid.dpid, fid.ofPort, fid.segId, fid.floatingIpAddress, fid.fixedIpAddress, action); } /** * This method performs creation or deletion of out-bound rules into Table 100 for a existing available floating * ip, otherwise for newer one. */ private void programFlowsForFloatingIPOutbound(final NeutronFloatingIP neutronFloatingIP, final Action action) { Preconditions.checkNotNull(neutronFloatingIP); final FloatIpData fid = getFloatingIPWithMetadata(neutronFloatingIP.getID()); if (fid == null) { LOG.trace("programFlowsForFloatingIPOutbound {} for {} uuid {} not in local cache", action, neutronFloatingIP.getFloatingIPAddress(), neutronFloatingIP.getID()); return; } programOutboundIpRewriteStage1(fid, action); } private void flushExistingIpRewrite() { for (FloatIpData fid : getAllFloatingIPsWithMetadata()) { programOutboundIpRewriteStage1(fid, Action.DELETE); } } private void rebuildExistingIpRewrite() { for (FloatIpData fid : getAllFloatingIPsWithMetadata()) { programOutboundIpRewriteStage1(fid, Action.ADD); } } /** * This method creates ARP response rules into OpenFlow Table 30 for a given floating ip. In order to connect * to br-ex from br-int, a patch-port is used. Thus, the patch-port will be responsible to respond the ARP * requests. */ private void programFlowsForFloatingIPArpAdd(final NeutronFloatingIP neutronFloatingIP) { Preconditions.checkNotNull(neutronFloatingIP); Preconditions.checkNotNull(neutronFloatingIP.getFixedIPAddress()); Preconditions.checkNotNull(neutronFloatingIP.getFloatingIPAddress()); // find bridge Node where floating ip is configured by looking up cache for its port final NeutronPort neutronPortForFloatIp = findNeutronPortForFloatingIp(neutronFloatingIP.getID()); final String neutronTenantPortUuid = neutronFloatingIP.getPortUUID(); final Pair<Long, Uuid> nodeIfPair = this.getDpIdOfNeutronPort(neutronTenantPortUuid); final String floatingIpMac = neutronPortForFloatIp == null ? null : neutronPortForFloatIp.getMacAddress(); final String fixedIpAddress = neutronFloatingIP.getFixedIPAddress(); final String floatingIpAddress = neutronFloatingIP.getFloatingIPAddress(); final NeutronPort tenantNeutronPort = neutronPortCache.getPort(neutronTenantPortUuid); final NeutronNetwork tenantNeutronNetwork = tenantNeutronPort != null ? neutronNetworkCache.getNetwork(tenantNeutronPort.getNetworkUUID()) : null; final String providerSegmentationId = tenantNeutronNetwork != null ? tenantNeutronNetwork.getProviderSegmentationID() : null; final String neutronRouterMac = tenantNeutronNetwork != null ? networkIdToRouterMacCache.get(tenantNeutronNetwork.getID()) : null; if (nodeIfPair == null || neutronTenantPortUuid == null || providerSegmentationId == null || providerSegmentationId.isEmpty() || floatingIpMac == null || floatingIpMac.isEmpty() || neutronRouterMac == null || neutronRouterMac.isEmpty()) { LOG.trace("Floating IP {}<->{}, incomplete floatPort {} tenantPortUuid {} seg {} mac {} rtrMac {}", fixedIpAddress, floatingIpAddress, neutronPortForFloatIp, neutronTenantPortUuid, providerSegmentationId, floatingIpMac, neutronRouterMac); return; } // get ofport for patch port in br-int final Long dpId = nodeIfPair.getLeft(); final Long ofPort = findOFPortForExtPatch(dpId); if (ofPort == null) { LOG.warn("Unable to locate OF port of patch port to connect floating ip to external bridge. dpid {}", dpId); return; } // Respond to ARPs for the floating ip address by default, via the patch port that connects br-int to br-ex // if (distributedArpService.programStaticRuleStage1(dpId, encodeExcplicitOFPort(ofPort), floatingIpMac, floatingIpAddress, Action.ADD)) { final FloatIpData floatIpData = new FloatIpData(dpId, ofPort, providerSegmentationId, floatingIpMac, floatingIpAddress, fixedIpAddress, neutronRouterMac); floatIpDataMapCache.put(neutronFloatingIP.getID(), floatIpData); LOG.info("Floating IP {}<->{} programmed ARP mac {} on OFport {} seg {} dpid {}", neutronFloatingIP.getFixedIPAddress(), neutronFloatingIP.getFloatingIPAddress(), floatingIpMac, ofPort, providerSegmentationId, dpId); } } private void programFlowsForFloatingIPArpDelete(final String neutronFloatingIPUuid) { final FloatIpData floatIpData = getFloatingIPWithMetadata(neutronFloatingIPUuid); if (floatIpData == null) { LOG.trace("programFlowsForFloatingIPArpDelete for uuid {} is not needed", neutronFloatingIPUuid); return; } if (distributedArpService.programStaticRuleStage1(floatIpData.dpid, encodeExcplicitOFPort(floatIpData.ofPort), floatIpData.macAddress, floatIpData.floatingIpAddress, Action.DELETE)) { floatIpDataMapCache.remove(neutronFloatingIPUuid); LOG.info("Floating IP {} un-programmed ARP mac {} on {} dpid {}", floatIpData.floatingIpAddress, floatIpData.macAddress, floatIpData.ofPort, floatIpData.dpid); } } private NeutronPort findNeutronPortForFloatingIp(final String floatingIpUuid) { for (NeutronPort neutronPort : neutronPortCache.getAllPorts()) { if (neutronPort.getDeviceOwner().equals(OWNER_FLOATING_IP) && neutronPort.getDeviceID().equals(floatingIpUuid)) { return neutronPort; } } return null; } private Long findOFPortForExtPatch(Long dpId) { final String brInt = configurationService.getIntegrationBridgeName(); final String brExt = configurationService.getExternalBridgeName(); final String portNameInt = configurationService.getPatchPortName(new ImmutablePair<>(brInt, brExt)); Preconditions.checkNotNull(dpId); Preconditions.checkNotNull(portNameInt); final long dpidPrimitive = dpId; for (Node node : nodeCacheManager.getBridgeNodes()) { if (dpidPrimitive == southbound.getDataPathId(node)) { final OvsdbTerminationPointAugmentation terminationPointOfBridge = southbound.getTerminationPointOfBridge(node, portNameInt); return terminationPointOfBridge == null ? null : terminationPointOfBridge.getOfport(); } } return null; } /** * Process the event. * * @param action the {@link org.opendaylight.ovsdb.openstack.netvirt.api.Action} action to be handled. * @param neutronNetwork An {@link org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronNetwork} instance of NeutronFloatingIP object. */ public void handleNeutronNetworkEvent(final NeutronNetwork neutronNetwork, Action action) { LOG.debug("neutronNetwork {}: network: {}", action, neutronNetwork); if (action == Action.UPDATE) { this.updateNetworkInCleanupCache(neutronNetwork); } } // // Callbacks from OVSDB's southbound handler // /** * Process the event. * * @param bridgeNode An instance of Node object. * @param intf An {@link org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105 * .OvsdbTerminationPointAugmentation} instance of OvsdbTerminationPointAugmentation object. * @param neutronNetwork An {@link org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronNetwork} instance of NeutronNetwork * object. * @param action the {@link org.opendaylight.ovsdb.openstack.netvirt.api.Action} action to be handled. */ public void handleInterfaceEvent(final Node bridgeNode, final OvsdbTerminationPointAugmentation intf, final NeutronNetwork neutronNetwork, Action action) { LOG.debug("southbound interface {} node:{} interface:{}, neutronNetwork:{}", action, bridgeNode.getNodeId().getValue(), intf.getName(), neutronNetwork); final NeutronPort neutronPort = tenantNetworkManager.getTenantPort(intf); if (action != Action.DELETE && neutronPort != null) { // FIXME: Bug 4971 Move cleanup cache to SG Impl storePortInCleanupCache(neutronPort); } if (!this.enabled) { return; } final Long dpId = getDpidForIntegrationBridge(bridgeNode); final Uuid interfaceUuid = intf.getInterfaceUuid(); LOG.trace("southbound interface {} node:{} interface:{}, neutronNetwork:{} port:{} dpid:{} intfUuid:{}", action, bridgeNode.getNodeId().getValue(), intf.getName(), neutronNetwork, neutronPort, dpId, interfaceUuid); if (neutronPort != null) { final String neutronPortUuid = neutronPort.getPortUUID(); if (action != Action.DELETE && dpId != null && interfaceUuid != null) { handleInterfaceEventAdd(neutronPortUuid, dpId, interfaceUuid); } handleNeutronPortEvent(neutronPort, action); } if (action == Action.DELETE && interfaceUuid != null) { handleInterfaceEventDelete(intf, dpId); } } private void handleInterfaceEventAdd(final String neutronPortUuid, Long dpId, final Uuid interfaceUuid) { neutronPortToDpIdCache.put(neutronPortUuid, new ImmutablePair<>(dpId, interfaceUuid)); LOG.debug("handleInterfaceEvent add cache entry NeutronPortUuid {} : dpid {}, ifUuid {}", neutronPortUuid, dpId, interfaceUuid.getValue()); } private void handleInterfaceEventDelete(final OvsdbTerminationPointAugmentation intf, final Long dpId) { // Remove entry from neutronPortToDpIdCache based on interface uuid for (Map.Entry<String, Pair<Long, Uuid>> entry : neutronPortToDpIdCache.entrySet()) { final String currPortUuid = entry.getKey(); if (intf.getInterfaceUuid().equals(entry.getValue().getRight())) { LOG.debug("handleInterfaceEventDelete remove cache entry NeutronPortUuid {} : dpid {}, ifUuid {}", currPortUuid, dpId, intf.getInterfaceUuid().getValue()); neutronPortToDpIdCache.remove(currPortUuid); break; } } } // // Internal helpers // private void updateL3ForNeutronPort(final NeutronPort neutronPort, final boolean isDelete) { final String networkUUID = neutronPort.getNetworkUUID(); final String routerMacAddress = networkIdToRouterMacCache.get(networkUUID); if(!isDelete) { // If there is no router interface handling the networkUUID, we are done if (routerMacAddress == null || routerMacAddress.isEmpty()) { return; } // If this is the neutron port for the router interface itself, ignore it as well. Ports that represent the // router interface are handled via handleNeutronRouterInterfaceEvent. if (routerMacAddress.equalsIgnoreCase(neutronPort.getMacAddress())) { return; } } final NeutronNetwork neutronNetwork = neutronNetworkCache.getNetwork(networkUUID); final String providerSegmentationId = neutronNetwork != null ? neutronNetwork.getProviderSegmentationID() : null; final String tenantMac = neutronPort.getMacAddress(); if (providerSegmentationId == null || providerSegmentationId.isEmpty() || tenantMac == null || tenantMac.isEmpty()) { // done: go no further w/out all the info needed... return; } final Action action = isDelete ? Action.DELETE : Action.ADD; List<Node> nodes = nodeCacheManager.getBridgeNodes(); if (nodes.isEmpty()) { LOG.trace("updateL3ForNeutronPort has no nodes to work with"); } for (Node node : nodes) { final Long dpid = getDpidForIntegrationBridge(node); if (dpid == null) { continue; } if (neutronPort.getFixedIPs() == null) { continue; } for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) { final String tenantIpStr = neutronIP.getIpAddress(); if (tenantIpStr.isEmpty()) { continue; } // Configure L3 fwd. We do that regardless of tenant network present, because these rules are // still needed when routing to subnets non-local to node (bug 2076). programL3ForwardingStage1(node, dpid, providerSegmentationId, tenantMac, tenantIpStr, action); } } } private void processSecurityGroupUpdate(NeutronPort neutronPort) { LOG.trace("processSecurityGroupUpdate:" + neutronPort); /** * Get updated data and original data for the the changed. Identify the security groups that got * added and removed and call the appropriate providers for updating the flows. */ try { NeutronPort originalPort = neutronPort.getOriginalPort(); List<NeutronSecurityGroup> addedGroup = getsecurityGroupChanged(neutronPort, neutronPort.getOriginalPort()); List<NeutronSecurityGroup> deletedGroup = getsecurityGroupChanged(neutronPort.getOriginalPort(), neutronPort); if (null != addedGroup && !addedGroup.isEmpty()) { securityServicesManager.syncSecurityGroup(neutronPort,addedGroup,true); } if (null != deletedGroup && !deletedGroup.isEmpty()) { securityServicesManager.syncSecurityGroup(neutronPort,deletedGroup,false); } } catch (Exception e) { LOG.error("Exception in processSecurityGroupUpdate", e); } } private List<NeutronSecurityGroup> getsecurityGroupChanged(NeutronPort port1, NeutronPort port2) { LOG.trace("getsecurityGroupChanged:" + "Port1:" + port1 + "Port2" + port2); if (port1 == null) { return null; } List<NeutronSecurityGroup> list1 = new ArrayList<>(port1.getSecurityGroups()); if (port2 == null) { return list1; } List<NeutronSecurityGroup> list2 = new ArrayList<>(port2.getSecurityGroups()); for (Iterator<NeutronSecurityGroup> iterator = list1.iterator(); iterator.hasNext();) { NeutronSecurityGroup securityGroup1 = iterator.next(); for (NeutronSecurityGroup securityGroup2 :list2) { if (securityGroup1.getID().equals(securityGroup2.getID())) { iterator.remove(); } } } return list1; } private void programL3ForwardingStage1(Node node, Long dpid, String providerSegmentationId, String macAddress, String ipStr, Action actionForNode) { if (actionForNode == Action.DELETE) { LOG.trace("Deleting Flow : programL3ForwardingStage1 for node {} providerId {} mac {} ip {} action {}", node.getNodeId().getValue(), providerSegmentationId, macAddress, ipStr, actionForNode); } if (actionForNode == Action.ADD) { LOG.trace("Adding Flow : programL3ForwardingStage1 for node {} providerId {} mac {} ip {} action {}", node.getNodeId().getValue(), providerSegmentationId, macAddress, ipStr, actionForNode); } this.programL3ForwardingStage2(node, dpid, providerSegmentationId, macAddress, ipStr, actionForNode); } private Status programL3ForwardingStage2(Node node, Long dpid, String providerSegmentationId, String macAddress, String address, Action actionForNode) { Status status; try { InetAddress inetAddress = InetAddress.getByName(address); status = l3ForwardingProvider == null ? new Status(StatusCode.SUCCESS) : l3ForwardingProvider.programForwardingTableEntry(dpid, providerSegmentationId, inetAddress, macAddress, actionForNode); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } if (status.isSuccess()) { LOG.debug("ProgramL3Forwarding {} for mac:{} addr:{} node:{} action:{}", l3ForwardingProvider == null ? "skipped" : "programmed", macAddress, address, node.getNodeId().getValue(), actionForNode); } else { LOG.error("ProgramL3Forwarding failed for mac:{} addr:{} node:{} action:{} status:{}", macAddress, address, node.getNodeId().getValue(), actionForNode, status); } return status; } // -- private void programFlowsForNeutronRouterInterface(final NeutronRouter_Interface destNeutronRouterInterface, Boolean isDelete) { Preconditions.checkNotNull(destNeutronRouterInterface); final NeutronPort neutronPort = neutronPortCache.getPort(destNeutronRouterInterface.getPortUUID()); String macAddress = neutronPort != null ? neutronPort.getMacAddress() : null; List<Neutron_IPs> ipList = neutronPort != null ? neutronPort.getFixedIPs() : null; final NeutronSubnet subnet = neutronSubnetCache.getSubnet(destNeutronRouterInterface.getSubnetUUID()); final NeutronNetwork neutronNetwork = subnet != null ? neutronNetworkCache.getNetwork(subnet.getNetworkUUID()) : null; final String destinationSegmentationId = neutronNetwork != null ? neutronNetwork.getProviderSegmentationID() : null; final Boolean isExternal = neutronNetwork != null ? neutronNetwork.getRouterExternal() : Boolean.TRUE; final String cidr = subnet != null ? subnet.getCidr() : null; final int mask = getMaskLenFromCidr(cidr); LOG.trace("programFlowsForNeutronRouterInterface called for interface {} isDelete {}", destNeutronRouterInterface, isDelete); // in delete path, mac address as well as ip address are not provided. Being so, let's find them from // the local cache if (neutronNetwork != null) { if (macAddress == null || macAddress.isEmpty()) { macAddress = networkIdToRouterMacCache.get(neutronNetwork.getNetworkUUID()); } if (ipList == null || ipList.isEmpty()) { ipList = networkIdToRouterIpListCache.get(neutronNetwork.getNetworkUUID()); } } if (destinationSegmentationId == null || destinationSegmentationId.isEmpty() || cidr == null || cidr.isEmpty() || macAddress == null || macAddress.isEmpty() || ipList == null || ipList.isEmpty()) { LOG.debug("programFlowsForNeutronRouterInterface is bailing seg:{} cidr:{} mac:{} ip:{}", destinationSegmentationId, cidr, macAddress, ipList); // done: go no further w/out all the info needed... return; } final Action actionForNode = isDelete ? Action.DELETE : Action.ADD; // Keep cache for finding router's mac from network uuid -- add // if (! isDelete) { networkIdToRouterMacCache.put(neutronNetwork.getNetworkUUID(), macAddress); networkIdToRouterIpListCache.put(neutronNetwork.getNetworkUUID(), new ArrayList<>(ipList)); subnetIdToRouterInterfaceCache.put(subnet.getSubnetUUID(), destNeutronRouterInterface); } List<Node> nodes = nodeCacheManager.getBridgeNodes(); if (nodes.isEmpty()) { LOG.trace("programFlowsForNeutronRouterInterface has no nodes to work with"); } for (Node node : nodes) { final Long dpid = getDpidForIntegrationBridge(node); if (dpid == null) { continue; } for (Neutron_IPs neutronIP : ipList) { final String ipStr = neutronIP.getIpAddress(); if (ipStr.isEmpty()) { LOG.debug("programFlowsForNeutronRouterInterface is skipping node {} ip {}", node.getNodeId().getValue(), ipStr); continue; } // Iterate through all other interfaces and add/remove reflexive flows to this interface // for (NeutronRouter_Interface srcNeutronRouterInterface : subnetIdToRouterInterfaceCache.values()) { programFlowsForNeutronRouterInterfacePair(node, dpid, srcNeutronRouterInterface, destNeutronRouterInterface, neutronNetwork, destinationSegmentationId, macAddress, ipStr, mask, actionForNode, true /*isReflexsive*/); } if (! isExternal) { programFlowForNetworkFromExternal(node, dpid, destinationSegmentationId, macAddress, ipStr, mask, actionForNode); } // Enable ARP responder by default, because router interface needs to be responded always. distributedArpService.programStaticRuleStage1(dpid, destinationSegmentationId, macAddress, ipStr, actionForNode); programIcmpEcho(dpid, destinationSegmentationId, macAddress, ipStr, actionForNode); } // Compute action to be programmed. In the case of rewrite exclusions, we must never program rules // for the external neutron networks. // { final Action actionForRewriteExclusion = isExternal ? Action.DELETE : actionForNode; programIpRewriteExclusionStage1(node, dpid, destinationSegmentationId, cidr, actionForRewriteExclusion); } } if (isDelete) { networkIdToRouterMacCache.remove(neutronNetwork.getNetworkUUID()); networkIdToRouterIpListCache.remove(neutronNetwork.getNetworkUUID()); subnetIdToRouterInterfaceCache.remove(subnet.getSubnetUUID()); } } private void programFlowForNetworkFromExternal(final Node node, final Long dpid, final String destinationSegmentationId, final String dstMacAddress, final String destIpStr, final int destMask, final Action actionForNode) { programRouterInterfaceStage1(node, dpid, Constants.EXTERNAL_NETWORK, destinationSegmentationId, dstMacAddress, destIpStr, destMask, actionForNode); } private void programFlowsForNeutronRouterInterfacePair(final Node node, final Long dpid, final NeutronRouter_Interface srcNeutronRouterInterface, final NeutronRouter_Interface dstNeutronRouterInterface, final NeutronNetwork dstNeutronNetwork, final String destinationSegmentationId, final String dstMacAddress, final String destIpStr, final int destMask, final Action actionForNode, Boolean isReflexsive) { Preconditions.checkNotNull(srcNeutronRouterInterface); Preconditions.checkNotNull(dstNeutronRouterInterface); final String sourceSubnetId = srcNeutronRouterInterface.getSubnetUUID(); if (sourceSubnetId == null) { LOG.error("Could not get provider Subnet ID from router interface {}", srcNeutronRouterInterface.getID()); return; } final NeutronSubnet sourceSubnet = neutronSubnetCache.getSubnet(sourceSubnetId); final String sourceNetworkId = sourceSubnet == null ? null : sourceSubnet.getNetworkUUID(); if (sourceNetworkId == null) { LOG.error("Could not get provider Network ID from subnet {}", sourceSubnetId); return; } final NeutronNetwork sourceNetwork = neutronNetworkCache.getNetwork(sourceNetworkId); if (sourceNetwork == null) { LOG.error("Could not get provider Network for Network ID {}", sourceNetworkId); return; } if (! sourceNetwork.getTenantID().equals(dstNeutronNetwork.getTenantID())) { // Isolate subnets from different tenants within the same router return; } final String sourceSegmentationId = sourceNetwork.getProviderSegmentationID(); if (sourceSegmentationId == null) { LOG.error("Could not get provider Segmentation ID for Subnet {}", sourceSubnetId); return; } if (sourceSegmentationId.equals(destinationSegmentationId)) { // Skip 'self' return; } programRouterInterfaceStage1(node, dpid, sourceSegmentationId, destinationSegmentationId, dstMacAddress, destIpStr, destMask, actionForNode); // Flip roles src->dst; dst->src if (isReflexsive) { final NeutronPort sourceNeutronPort = neutronPortCache.getPort(srcNeutronRouterInterface.getPortUUID()); final String macAddress2 = sourceNeutronPort != null ? sourceNeutronPort.getMacAddress() : null; final List<Neutron_IPs> ipList2 = sourceNeutronPort != null ? sourceNeutronPort.getFixedIPs() : null; final String cidr2 = sourceSubnet.getCidr(); final int mask2 = getMaskLenFromCidr(cidr2); if (cidr2 == null || cidr2.isEmpty() || macAddress2 == null || macAddress2.isEmpty() || ipList2 == null || ipList2.isEmpty()) { LOG.trace("programFlowsForNeutronRouterInterfacePair reflexive is bailing seg:{} cidr:{} mac:{} ip:{}", sourceSegmentationId, cidr2, macAddress2, ipList2); // done: go no further w/out all the info needed... return; } for (Neutron_IPs neutronIP2 : ipList2) { final String ipStr2 = neutronIP2.getIpAddress(); if (ipStr2.isEmpty()) { continue; } programFlowsForNeutronRouterInterfacePair(node, dpid, dstNeutronRouterInterface, srcNeutronRouterInterface, sourceNetwork, sourceSegmentationId, macAddress2, ipStr2, mask2, actionForNode, false /*isReflexsive*/); } } } private void programRouterInterfaceStage1(Node node, Long dpid, String sourceSegmentationId, String destinationSegmentationId, String macAddress, String ipStr, int mask, Action actionForNode) { if (actionForNode == Action.DELETE) { LOG.trace("Deleting Flow : programRouterInterfaceStage1 for node {} sourceSegId {} destSegId {} mac {} ip {} mask {}" + " action {}", node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId, macAddress, ipStr, mask, actionForNode); } if (actionForNode == Action.ADD) { LOG.trace("Adding Flow : programRouterInterfaceStage1 for node {} sourceSegId {} destSegId {} mac {} ip {} mask {}" + " action {}", node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId, macAddress, ipStr, mask, actionForNode); } this.programRouterInterfaceStage2(node, dpid, sourceSegmentationId, destinationSegmentationId, macAddress, ipStr, mask, actionForNode); } private Status programRouterInterfaceStage2(Node node, Long dpid, String sourceSegmentationId, String destinationSegmentationId, String macAddress, String address, int mask, Action actionForNode) { Status status; try { InetAddress inetAddress = InetAddress.getByName(address); status = routingProvider == null ? new Status(StatusCode.SUCCESS) : routingProvider.programRouterInterface(dpid, sourceSegmentationId, destinationSegmentationId, macAddress, inetAddress, mask, actionForNode); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } if (status.isSuccess()) { LOG.debug("programRouterInterfaceStage2 {} for mac:{} addr:{}/{} node:{} srcTunId:{} destTunId:{} action:{}", routingProvider == null ? "skipped" : "programmed", macAddress, address, mask, node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId, actionForNode); } else { LOG.error("programRouterInterfaceStage2 failed for mac:{} addr:{}/{} node:{} srcTunId:{} destTunId:{} action:{} status:{}", macAddress, address, mask, node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId, actionForNode, status); } return status; } private boolean programIcmpEcho(Long dpid, String segOrOfPort, String macAddress, String ipStr, Action action) { if (action == Action.DELETE ) { LOG.trace("Deleting Flow : programIcmpEcho dpid {} segOrOfPort {} mac {} ip {} action {}", dpid, segOrOfPort, macAddress, ipStr, action); } if (action == Action.ADD) { LOG.trace("Adding Flow : programIcmpEcho dpid {} segOrOfPort {} mac {} ip {} action {}", dpid, segOrOfPort, macAddress, ipStr, action); } Status status = new Status(StatusCode.UNSUPPORTED); if (icmpEchoProvider != null){ try { InetAddress inetAddress = InetAddress.getByName(ipStr); status = icmpEchoProvider.programIcmpEchoEntry(dpid, segOrOfPort, macAddress, inetAddress, action); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } } if (status.isSuccess()) { LOG.debug("programIcmpEcho {} for mac:{} addr:{} dpid:{} segOrOfPort:{} action:{}", icmpEchoProvider == null ? "skipped" : "programmed", macAddress, ipStr, dpid, segOrOfPort, action); } else { LOG.error("programIcmpEcho failed for mac:{} addr:{} dpid:{} segOrOfPort:{} action:{} status:{}", macAddress, ipStr, dpid, segOrOfPort, action, status); } return status.isSuccess(); } private boolean programInboundIpRewriteStage1(Long dpid, Long inboundOFPort, String providerSegmentationId, String matchAddress, String rewriteAddress, Action action) { if (action == Action.DELETE ) { LOG.trace("Deleting Flow : programInboundIpRewriteStage1 dpid {} OFPort {} seg {} matchAddress {} rewriteAddress {}" + " action {}", dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action); } if (action == Action.ADD ) { LOG.trace("Adding Flow : programInboundIpRewriteStage1 dpid {} OFPort {} seg {} matchAddress {} rewriteAddress {}" + " action {}", dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action); } Status status = programInboundIpRewriteStage2(dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action); return status.isSuccess(); } private Status programInboundIpRewriteStage2(Long dpid, Long inboundOFPort, String providerSegmentationId, String matchAddress, String rewriteAddress, Action action) { Status status; try { InetAddress inetMatchAddress = InetAddress.getByName(matchAddress); InetAddress inetRewriteAddress = InetAddress.getByName(rewriteAddress); status = inboundNatProvider == null ? new Status(StatusCode.SUCCESS) : inboundNatProvider.programIpRewriteRule(dpid, inboundOFPort, providerSegmentationId, inetMatchAddress, inetRewriteAddress, action); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } if (status.isSuccess()) { final boolean isSkipped = inboundNatProvider == null; LOG.debug("programInboundIpRewriteStage2 {} for dpid:{} ofPort:{} seg:{} match:{} rewrite:{} action:{}", isSkipped ? "skipped" : "programmed", dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action); } else { LOG.error("programInboundIpRewriteStage2 failed for dpid:{} ofPort:{} seg:{} match:{} rewrite:{} action:{}" + " status:{}", dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action, status); } return status; } private void programIpRewriteExclusionStage1(Node node, Long dpid, String providerSegmentationId, String cidr, Action actionForRewriteExclusion) { if (actionForRewriteExclusion == Action.DELETE ) { LOG.trace("Deleting Flow : programIpRewriteExclusionStage1 node {} providerId {} cidr {} action {}", node.getNodeId().getValue(), providerSegmentationId, cidr, actionForRewriteExclusion); } if (actionForRewriteExclusion == Action.ADD) { LOG.trace("Adding Flow : programIpRewriteExclusionStage1 node {} providerId {} cidr {} action {}", node.getNodeId().getValue(), providerSegmentationId, cidr, actionForRewriteExclusion); } this.programIpRewriteExclusionStage2(node, dpid, providerSegmentationId, cidr,actionForRewriteExclusion); } private Status programIpRewriteExclusionStage2(Node node, Long dpid, String providerSegmentationId, String cidr, Action actionForNode) { final Status status = outboundNatProvider == null ? new Status(StatusCode.SUCCESS) : outboundNatProvider.programIpRewriteExclusion(dpid, providerSegmentationId, cidr, actionForNode); if (status.isSuccess()) { final boolean isSkipped = outboundNatProvider == null; LOG.debug("IpRewriteExclusion {} for cidr:{} node:{} action:{}", isSkipped ? "skipped" : "programmed", cidr, node.getNodeId().getValue(), actionForNode); } else { LOG.error("IpRewriteExclusion failed for cidr:{} node:{} action:{} status:{}", cidr, node.getNodeId().getValue(), actionForNode, status); } return status; } private void programOutboundIpRewriteStage1(FloatIpData fid, Action action) { if (action == Action.DELETE) { LOG.trace("Deleting Flow : programOutboundIpRewriteStage1 dpid {} seg {} fixedIpAddress {} floatIp {} action {} ", fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action); } if (action == Action.ADD) { LOG.trace("Adding Flow : programOutboundIpRewriteStage1 dpid {} seg {} fixedIpAddress {} floatIp {} action {} " , fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action); } this.programOutboundIpRewriteStage2(fid, action); } private Status programOutboundIpRewriteStage2(FloatIpData fid, Action action) { Status status; try { InetAddress matchSrcAddress = InetAddress.getByName(fid.fixedIpAddress); InetAddress rewriteSrcAddress = InetAddress.getByName(fid.floatingIpAddress); status = outboundNatProvider == null ? new Status(StatusCode.SUCCESS) : outboundNatProvider.programIpRewriteRule( fid.dpid, fid.segId, fid.neutronRouterMac, matchSrcAddress, fid.macAddress, this.externalRouterMac, rewriteSrcAddress, fid.ofPort, action); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } if (status.isSuccess()) { final boolean isSkipped = outboundNatProvider == null; LOG.debug("programOutboundIpRewriteStage2 {} for dpid {} seg {} fixedIpAddress {} floatIp {}" + " action {}", isSkipped ? "skipped" : "programmed", fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action); } else { LOG.error("programOutboundIpRewriteStage2 failed for dpid {} seg {} fixedIpAddress {} floatIp {}" + " action {} status:{}", fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action, status); } return status; } private int getMaskLenFromCidr(String cidr) { if (cidr == null) { return 0; } String[] splits = cidr.split("/"); if (splits.length != 2) { return 0; } int result; try { result = Integer.parseInt(splits[1].trim()); } catch (NumberFormatException nfe) { result = 0; } return result; } private Long getDpidForIntegrationBridge(Node node) { // Check if node is integration bridge; and only then return its dpid if (southbound.getBridge(node, configurationService.getIntegrationBridgeName()) != null) { return southbound.getDataPathId(node); } return null; } private Long getDpidForExternalBridge(Node node) { // Check if node is external bridge; and only then return its dpid if (southbound.getBridge(node, configurationService.getExternalBridgeName()) != null) { return southbound.getDataPathId(node); } return null; } private Node getExternalBridgeNode(){ //Pickup the first node that has external bridge (br-ex). //NOTE: We are assuming that all the br-ex are serving one external network and gateway ip of //the external network is reachable from every br-ex // TODO: Consider other deployment scenario, and thing of better solution. List<Node> allBridges = nodeCacheManager.getBridgeNodes(); for(Node node : allBridges){ if (southbound.getBridge(node, configurationService.getExternalBridgeName()) != null) { return node; } } return null; } private NeutronSubnet getExternalNetworkSubnet(NeutronPort gatewayPort){ if (gatewayPort.getFixedIPs() == null) { return null; } for (Neutron_IPs neutronIPs : gatewayPort.getFixedIPs()) { String subnetUUID = neutronIPs.getSubnetUUID(); NeutronSubnet extSubnet = neutronSubnetCache.getSubnet(subnetUUID); if (extSubnet != null && extSubnet.getGatewayIP() != null) { return extSubnet; } if (extSubnet == null) { // TODO: when subnet is created, try again. LOG.debug("subnet {} in not found", subnetUUID); } } return null; } private void cleanupFloatingIPRules(final NeutronPort neutronPort) { List<NeutronFloatingIP> neutronFloatingIps = neutronFloatingIpCache.getAllFloatingIPs(); if (neutronFloatingIps != null && !neutronFloatingIps.isEmpty()) { for (NeutronFloatingIP neutronFloatingIP : neutronFloatingIps) { if (neutronFloatingIP.getPortUUID().equals(neutronPort.getPortUUID())) { handleNeutronFloatingIPEvent(neutronFloatingIP, Action.DELETE); } } } } private void updateFloatingIPRules(final NeutronPort neutronPort) { List<NeutronFloatingIP> neutronFloatingIps = neutronFloatingIpCache.getAllFloatingIPs(); if (neutronFloatingIps != null) { for (NeutronFloatingIP neutronFloatingIP : neutronFloatingIps) { if (neutronFloatingIP.getPortUUID().equals(neutronPort.getPortUUID())) { handleNeutronFloatingIPEvent(neutronFloatingIP, Action.UPDATE); } } } } private void triggerGatewayMacResolver(final NeutronPort gatewayPort){ Preconditions.checkNotNull(gatewayPort); NeutronNetwork externalNetwork = neutronNetworkCache.getNetwork(gatewayPort.getNetworkUUID()); if(externalNetwork != null){ if(externalNetwork.isRouterExternal()){ final NeutronSubnet externalSubnet = getExternalNetworkSubnet(gatewayPort); // TODO: address IPv6 case. if (externalSubnet != null && externalSubnet.getIpVersion() == 4 && gatewayPort.getFixedIPs() != null) { LOG.info("Trigger MAC resolution for gateway ip {}", externalSubnet.getGatewayIP()); Neutron_IPs neutronIP = null; for (Neutron_IPs nIP : gatewayPort.getFixedIPs()) { InetAddress ipAddress; try { ipAddress = InetAddress.getByAddress(nIP.getIpAddress().getBytes()); } catch (UnknownHostException e) { LOG.warn("unknown host exception {}", e); continue; } if (ipAddress instanceof Inet4Address) { neutronIP = nIP; break; } } if (neutronIP == null) { // TODO IPv6 neighbor discovery LOG.debug("Ignoring gateway ports with IPv6 only fixed ip {}", gatewayPort.getFixedIPs()); } else { gatewayMacResolver.resolveMacAddress( this, /* gatewayMacResolverListener */ null, /* externalNetworkBridgeDpid */ true, /* refreshExternalNetworkBridgeDpidIfNeeded */ new Ipv4Address(externalSubnet.getGatewayIP()), new Ipv4Address(neutronIP.getIpAddress()), new MacAddress(gatewayPort.getMacAddress()), true /* periodicRefresh */); } } else { LOG.warn("No gateway IP address found for external network {}", externalNetwork); } } }else{ LOG.warn("Neutron network not found for router interface {}", gatewayPort); } } private void storePortInCleanupCache(NeutronPort port) { this.portCleanupCache.put(port.getPortUUID(),port); } private void updatePortInCleanupCache(NeutronPort updatedPort,NeutronPort originalPort) { removePortFromCleanupCache(originalPort); storePortInCleanupCache(updatedPort); } public void removePortFromCleanupCache(NeutronPort port) { if(port != null) { this.portCleanupCache.remove(port.getPortUUID()); } } public Map<String, NeutronPort> getPortCleanupCache() { return this.portCleanupCache; } public NeutronPort getPortFromCleanupCache(String portid) { for (String neutronPortUuid : this.portCleanupCache.keySet()) { if (neutronPortUuid.equals(portid)) { LOG.info("getPortFromCleanupCache: Matching NeutronPort found {}", portid); return this.portCleanupCache.get(neutronPortUuid); } } return null; } private void storeNetworkInCleanupCache(NeutronNetwork network) { this.networkCleanupCache.put(network.getNetworkUUID(), network); } private void updateNetworkInCleanupCache(NeutronNetwork network) { for (String neutronNetworkUuid:this.networkCleanupCache.keySet()) { if (neutronNetworkUuid.equals(network.getNetworkUUID())) { this.networkCleanupCache.remove(neutronNetworkUuid); } } this.networkCleanupCache.put(network.getNetworkUUID(), network); } public void removeNetworkFromCleanupCache(String networkid) { NeutronNetwork network = null; for (String neutronNetworkUuid:this.networkCleanupCache.keySet()) { if (neutronNetworkUuid.equals(networkid)) { network = networkCleanupCache.get(neutronNetworkUuid); break; } } if (network != null) { for (String neutronPortUuid:this.portCleanupCache.keySet()) { if (this.portCleanupCache.get(neutronPortUuid).getNetworkUUID().equals(network.getNetworkUUID())) { LOG.info("This network is used by another port", network); return; } } this.networkCleanupCache.remove(network.getNetworkUUID()); } } public Map<String, NeutronNetwork> getNetworkCleanupCache() { return this.networkCleanupCache; } public NeutronNetwork getNetworkFromCleanupCache(String networkid) { for (String neutronNetworkUuid:this.networkCleanupCache.keySet()) { if (neutronNetworkUuid.equals(networkid)) { LOG.info("getPortFromCleanupCache: Matching NeutronPort found {}", networkid); return networkCleanupCache.get(neutronNetworkUuid); } } return null; } /** * Return String that represents OF port with marker explicitly provided (reverse of MatchUtils:parseExplicitOFPort) * * @param ofPort the OF port number * @return the string with encoded OF port (example format "OFPort|999") */ public static String encodeExcplicitOFPort(Long ofPort) { return "OFPort|" + ofPort.toString(); } private void initNetworkCleanUpCache() { if (this.neutronNetworkCache != null) { for (NeutronNetwork neutronNetwork : neutronNetworkCache.getAllNetworks()) { networkCleanupCache.put(neutronNetwork.getNetworkUUID(), neutronNetwork); } } } private void initPortCleanUpCache() { if (this.neutronPortCache != null) { for (NeutronPort neutronPort : neutronPortCache.getAllPorts()) { portCleanupCache.put(neutronPort.getPortUUID(), neutronPort); } } } @Override public void setDependencies(ServiceReference serviceReference) { eventDispatcher = (EventDispatcher) ServiceHelper.getGlobalInstance(EventDispatcher.class, this); eventDispatcher.eventHandlerAdded(serviceReference, this); tenantNetworkManager = (TenantNetworkManager) ServiceHelper.getGlobalInstance(TenantNetworkManager.class, this); configurationService = (ConfigurationService) ServiceHelper.getGlobalInstance(ConfigurationService.class, this); arpProvider = (ArpProvider) ServiceHelper.getGlobalInstance(ArpProvider.class, this); inboundNatProvider = (InboundNatProvider) ServiceHelper.getGlobalInstance(InboundNatProvider.class, this); outboundNatProvider = (OutboundNatProvider) ServiceHelper.getGlobalInstance(OutboundNatProvider.class, this); routingProvider = (RoutingProvider) ServiceHelper.getGlobalInstance(RoutingProvider.class, this); l3ForwardingProvider = (L3ForwardingProvider) ServiceHelper.getGlobalInstance(L3ForwardingProvider.class, this); distributedArpService = (DistributedArpService) ServiceHelper.getGlobalInstance(DistributedArpService.class, this); nodeCacheManager = (NodeCacheManager) ServiceHelper.getGlobalInstance(NodeCacheManager.class, this); southbound = (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this); gatewayMacResolver = (GatewayMacResolver) ServiceHelper.getGlobalInstance(GatewayMacResolver.class, this); securityServicesManager = (SecurityServicesManager) ServiceHelper.getGlobalInstance(SecurityServicesManager.class, this); initL3AdapterMembers(); } @Override public void setDependencies(Object impl) { if (impl instanceof INeutronNetworkCRUD) { neutronNetworkCache = (INeutronNetworkCRUD)impl; initNetworkCleanUpCache(); } else if (impl instanceof INeutronPortCRUD) { neutronPortCache = (INeutronPortCRUD)impl; initPortCleanUpCache(); } else if (impl instanceof INeutronSubnetCRUD) { neutronSubnetCache = (INeutronSubnetCRUD)impl; } else if (impl instanceof INeutronFloatingIPCRUD) { neutronFloatingIpCache = (INeutronFloatingIPCRUD)impl; } else if (impl instanceof ArpProvider) { arpProvider = (ArpProvider)impl; } else if (impl instanceof InboundNatProvider) { inboundNatProvider = (InboundNatProvider)impl; } else if (impl instanceof OutboundNatProvider) { outboundNatProvider = (OutboundNatProvider)impl; } else if (impl instanceof RoutingProvider) { routingProvider = (RoutingProvider)impl; } else if (impl instanceof L3ForwardingProvider) { l3ForwardingProvider = (L3ForwardingProvider)impl; }else if (impl instanceof GatewayMacResolver) { gatewayMacResolver = (GatewayMacResolver)impl; }else if (impl instanceof IcmpEchoProvider) { icmpEchoProvider = (IcmpEchoProvider)impl; } populateL3ForwardingCaches(); } }
Bug 5466 - GatewayMacResolver Broken "nIP.getIpAddress().getBytes()" returns a byte representation of the IP address string (including periods). What we really want is a byte representation of the IP address represented by the string. The solution is to use the InetAddress.getByName method that takes an IP address string directly. Change-Id: I39dcc1b8e97ab175e23d5aa2c9310581b87214ee Signed-off-by: Andre Fredette <[email protected]>
openstack/net-virt/src/main/java/org/opendaylight/ovsdb/openstack/netvirt/impl/NeutronL3Adapter.java
Bug 5466 - GatewayMacResolver Broken
<ide><path>penstack/net-virt/src/main/java/org/opendaylight/ovsdb/openstack/netvirt/impl/NeutronL3Adapter.java <ide> for (Neutron_IPs nIP : gatewayPort.getFixedIPs()) { <ide> InetAddress ipAddress; <ide> try { <del> ipAddress = InetAddress.getByAddress(nIP.getIpAddress().getBytes()); <add> ipAddress = InetAddress.getByName(nIP.getIpAddress()); <ide> } catch (UnknownHostException e) { <ide> LOG.warn("unknown host exception {}", e); <ide> continue;
Java
apache-2.0
fbcb442a65e68a8eb38691230c5a4e2f2aba77ab
0
tarasane/h2o-3,bikash/h2o-dev,pchmieli/h2o-3,spennihana/h2o-3,PawarPawan/h2o-v3,h2oai/h2o-dev,weaver-viii/h2o-3,weaver-viii/h2o-3,mathemage/h2o-3,michalkurka/h2o-3,PawarPawan/h2o-v3,h2oai/h2o-3,kyoren/https-github.com-h2oai-h2o-3,mathemage/h2o-3,junwucs/h2o-3,YzPaul3/h2o-3,tarasane/h2o-3,bospetersen/h2o-3,spennihana/h2o-3,PawarPawan/h2o-v3,nilbody/h2o-3,junwucs/h2o-3,pchmieli/h2o-3,brightchen/h2o-3,mathemage/h2o-3,brightchen/h2o-3,h2oai/h2o-dev,brightchen/h2o-3,madmax983/h2o-3,mrgloom/h2o-3,mrgloom/h2o-3,nilbody/h2o-3,ChristosChristofidis/h2o-3,michalkurka/h2o-3,pchmieli/h2o-3,kyoren/https-github.com-h2oai-h2o-3,junwucs/h2o-3,pchmieli/h2o-3,h2oai/h2o-3,kyoren/https-github.com-h2oai-h2o-3,h2oai/h2o-3,bospetersen/h2o-3,YzPaul3/h2o-3,nilbody/h2o-3,datachand/h2o-3,tarasane/h2o-3,mrgloom/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,spennihana/h2o-3,datachand/h2o-3,printedheart/h2o-3,printedheart/h2o-3,spennihana/h2o-3,pchmieli/h2o-3,mrgloom/h2o-3,datachand/h2o-3,spennihana/h2o-3,h2oai/h2o-dev,YzPaul3/h2o-3,bospetersen/h2o-3,weaver-viii/h2o-3,ChristosChristofidis/h2o-3,tarasane/h2o-3,madmax983/h2o-3,YzPaul3/h2o-3,brightchen/h2o-3,mrgloom/h2o-3,ChristosChristofidis/h2o-3,bikash/h2o-dev,tarasane/h2o-3,datachand/h2o-3,michalkurka/h2o-3,PawarPawan/h2o-v3,mathemage/h2o-3,bospetersen/h2o-3,printedheart/h2o-3,datachand/h2o-3,YzPaul3/h2o-3,weaver-viii/h2o-3,bospetersen/h2o-3,michalkurka/h2o-3,madmax983/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,jangorecki/h2o-3,h2oai/h2o-dev,jangorecki/h2o-3,h2oai/h2o-3,bikash/h2o-dev,printedheart/h2o-3,ChristosChristofidis/h2o-3,kyoren/https-github.com-h2oai-h2o-3,tarasane/h2o-3,nilbody/h2o-3,ChristosChristofidis/h2o-3,PawarPawan/h2o-v3,printedheart/h2o-3,datachand/h2o-3,weaver-viii/h2o-3,mathemage/h2o-3,weaver-viii/h2o-3,YzPaul3/h2o-3,mrgloom/h2o-3,madmax983/h2o-3,h2oai/h2o-3,h2oai/h2o-3,printedheart/h2o-3,bikash/h2o-dev,brightchen/h2o-3,bikash/h2o-dev,kyoren/https-github.com-h2oai-h2o-3,michalkurka/h2o-3,spennihana/h2o-3,jangorecki/h2o-3,jangorecki/h2o-3,datachand/h2o-3,michalkurka/h2o-3,nilbody/h2o-3,junwucs/h2o-3,printedheart/h2o-3,brightchen/h2o-3,PawarPawan/h2o-v3,bospetersen/h2o-3,bospetersen/h2o-3,jangorecki/h2o-3,kyoren/https-github.com-h2oai-h2o-3,YzPaul3/h2o-3,pchmieli/h2o-3,weaver-viii/h2o-3,nilbody/h2o-3,spennihana/h2o-3,michalkurka/h2o-3,ChristosChristofidis/h2o-3,kyoren/https-github.com-h2oai-h2o-3,madmax983/h2o-3,jangorecki/h2o-3,h2oai/h2o-dev,PawarPawan/h2o-v3,mathemage/h2o-3,jangorecki/h2o-3,junwucs/h2o-3,brightchen/h2o-3,ChristosChristofidis/h2o-3,madmax983/h2o-3,mrgloom/h2o-3,pchmieli/h2o-3,nilbody/h2o-3,junwucs/h2o-3,madmax983/h2o-3,bikash/h2o-dev,mathemage/h2o-3,junwucs/h2o-3,tarasane/h2o-3
package water.fvec; import water.AutoBuffer; import water.H2O; import water.util.UnsafeUtils; import java.util.Iterator; // Sparse chunk. public class CXIChunk extends Chunk { private transient int _valsz; // byte size of stored value protected final int valsz() { return _valsz; } private transient int _valsz_log; // private transient int _ridsz; // byte size of stored (chunk-relative) row nums protected final int ridsz() { return _ridsz; } private transient int _sparse_len; protected static final int _OFF = 6; private transient int _lastOff = _OFF; private static final long [] NAS = {C1Chunk._NA,C2Chunk._NA,C4Chunk._NA,C8Chunk._NA}; protected CXIChunk(int len, int nzs, int valsz, byte [] buf){ assert (valsz == 0 || valsz == 1 || valsz == 2 || valsz == 4 || valsz == 8); set_len(len); int log = 0; while((1 << log) < valsz)++log; assert valsz == 0 || (1 << log) == valsz; _valsz = valsz; _valsz_log = log; _ridsz = (len >= 65535)?4:2; UnsafeUtils.set4(buf, 0, len); byte b = (byte) _ridsz; buf[4] = b; buf[5] = (byte) _valsz; _mem = buf; _sparse_len = (_mem.length - _OFF) / (_valsz+_ridsz); assert (_mem.length - _OFF) % (_valsz+_ridsz) == 0:"unexpected mem buffer length: mem.length = " + _mem.length + ", off = " + _OFF + ", valSz = " + _valsz + "ridsz = " + _ridsz; } @Override public final boolean isSparse() {return true;} @Override public final int sparseLen(){ return _sparse_len; } /** Fills in a provided (recycled/reused) temp array of the NZ indices, and * returns the count of them. Array must be large enough. */ @Override public final int nonzeros(int [] arr){ int len = sparseLen(); int off = _OFF; final int inc = _valsz + 2; for(int i = 0; i < len; ++i, off += inc) arr[i] = UnsafeUtils.get2(_mem, off)&0xFFFF; return len; } @Override boolean set_impl(int idx, long l) { return false; } @Override boolean set_impl(int idx, double d) { return false; } @Override boolean set_impl(int idx, float f ) { return false; } @Override boolean setNA_impl(int idx) { return false; } @Override protected long at8_impl(int idx) { int off = findOffset(idx); if(getId(off) != idx)return 0; long v = getIValue(off); if( v== NAS[_valsz_log]) throw new IllegalArgumentException("at8_abs but value is missing"); return v; } @Override protected double atd_impl(int idx) { int off = findOffset(idx); if(getId(off) != idx)return 0; long v = getIValue(off); return (v == NAS[_valsz_log])?Double.NaN:v; } @Override protected boolean isNA_impl( int i ) { int off = findOffset(i); if(getId(off) != i)return false; return getIValue(off) == NAS[_valsz_log]; } @Override public NewChunk inflate_impl(NewChunk nc) { final int slen = sparseLen(); nc.set_len(_len); nc.set_sparseLen(slen); nc.alloc_mantissa(slen); nc.alloc_exponent(slen); nc.alloc_indices(slen); int off = _OFF; for( int i = 0; i < slen; ++i, off += _ridsz + _valsz) { nc.indices()[i] = getId(off); long v = getIValue(off); if(v == NAS[_valsz_log]) nc.setNA_impl2(i); else nc.mantissa()[i] = v; } return nc; } // get id of nth (chunk-relative) stored element protected final int getId(int off){ return _ridsz == 2 ?UnsafeUtils.get2(_mem,off)&0xFFFF :UnsafeUtils.get4(_mem,off); } // get offset of nth (chunk-relative) stored element private int getOff(int n){return _OFF + (_ridsz + _valsz)*n;} // extract integer value from an (byte)offset protected final long getIValue(int off){ switch(_valsz){ case 1: return _mem[off+ _ridsz]&0xFF; case 2: return UnsafeUtils.get2(_mem, off + _ridsz); case 4: return UnsafeUtils.get4(_mem, off + _ridsz); case 8: return UnsafeUtils.get8(_mem, off + _ridsz); default: throw H2O.unimpl(); } } // find offset of the chunk-relative row id, or -1 if not stored (i.e. sparse zero) // find offset of the chunk-relative row id, or -1 if not stored (i.e. sparse zero) protected final int findOffset(int idx) { if(idx >= _len)throw new IndexOutOfBoundsException(); int sparseLen = sparseLen(); if(sparseLen == 0)return 0; final byte [] mem = _mem; if(idx <= getId(_OFF)) // easy cut off accessing the zeros prior first nz return _OFF; int last = mem.length - _ridsz - _valsz; if(idx >= getId(last)) // easy cut off accessing of the tail zeros return last; final int off = _lastOff; int lastIdx = getId(off); // check the last accessed elem + one after if( idx == lastIdx ) return off; if(idx > lastIdx){ // check the next one (no need to check bounds, already checked at the beginning) final int nextOff = off + _ridsz + _valsz; int nextId = getId(nextOff); if(idx < nextId) return off; if(idx == nextId){ _lastOff = nextOff; return nextOff; } } // binary search int lo=0, hi = sparseLen; while( lo+1 != hi ) { int mid = (hi+lo)>>>1; if( idx < getId(getOff(mid))) hi = mid; else lo = mid; } int y = getOff(lo); _lastOff = y; return y; } @Override public final int nextNZ(int rid){ final int off = rid == -1?_OFF:findOffset(rid); int x = getId(off); if(x > rid)return x; if(off < _mem.length - _ridsz - _valsz) return getId(off + _ridsz + _valsz); return _len; } @Override public AutoBuffer write_impl(AutoBuffer bb) { return bb.putA1(_mem, _mem.length); } @Override public CXIChunk read_impl(AutoBuffer bb) { _mem = bb.bufClose(); _start = -1; set_len(UnsafeUtils.get4(_mem,0)); _ridsz = _mem[4]; _valsz = _mem[5]; int x = _valsz; int log = 0; while(x > 1){ x = x >>> 1; ++log; } _valsz_log = log; _sparse_len = (_mem.length - _OFF) / (_valsz+_ridsz); assert (_mem.length - _OFF) % (_valsz+_ridsz) == 0:"unexpected mem buffer length: meme.length = " + _mem.length + ", off = " + _OFF + ", valSz = " + _valsz + "ridsz = " + _ridsz; return this; } public abstract class Value { protected int _off = 0; public int rowInChunk(){return getId(_off);} public abstract long asLong(); public abstract double asDouble(); public abstract boolean isNA(); } public final class SparseIterator implements Iterator<Value> { final Value _val; public SparseIterator(Value v){_val = v;} @Override public final boolean hasNext(){return _val._off < _mem.length - (_ridsz + _valsz);} @Override public final Value next(){ if(_val._off == 0)_val._off = _OFF; else _val._off += (_ridsz + _valsz); return _val; } @Override public final void remove(){throw new UnsupportedOperationException();} } public Iterator<Value> values(){ return new SparseIterator(new Value(){ @Override public final long asLong(){ long v = getIValue(_off); if(v == NAS[(_valsz >>> 1) - 1]) throw new IllegalArgumentException("at8_abs but value is missing"); return v; } @Override public final double asDouble() { long v = getIValue(_off); return (v == NAS[_valsz_log -1])?Double.NaN:v; } @Override public final boolean isNA(){ long v = getIValue(_off); return (v == NAS[_valsz_log]); } }); } @Override public boolean hasFloat() {return false;} }
h2o-core/src/main/java/water/fvec/CXIChunk.java
package water.fvec; import water.AutoBuffer; import water.H2O; import water.util.UnsafeUtils; import java.util.Iterator; // Sparse chunk. public class CXIChunk extends Chunk { private transient int _valsz; // byte size of stored value protected final int valsz() { return _valsz; } private transient int _valsz_log; // private transient int _ridsz; // byte size of stored (chunk-relative) row nums protected final int ridsz() { return _ridsz; } private transient int _sparse_len; protected static final int _OFF = 6; private transient int _lastOff = _OFF; private static final long [] NAS = {C1Chunk._NA,C2Chunk._NA,C4Chunk._NA,C8Chunk._NA}; protected CXIChunk(int len, int nzs, int valsz, byte [] buf){ assert (valsz == 0 || valsz == 1 || valsz == 2 || valsz == 4 || valsz == 8); set_len(len); int log = 0; while((1 << log) < valsz)++log; assert valsz == 0 || (1 << log) == valsz; _valsz = valsz; _valsz_log = log; _ridsz = (len >= 65535)?4:2; UnsafeUtils.set4(buf, 0, len); byte b = (byte) _ridsz; buf[4] = b; buf[5] = (byte) _valsz; _mem = buf; _sparse_len = (_mem.length - _OFF) / (_valsz+_ridsz); assert (_mem.length - _OFF) % (_valsz+_ridsz) == 0:"unexpected mem buffer length: mem.length = " + _mem.length + ", off = " + _OFF + ", valSz = " + _valsz + "ridsz = " + _ridsz; } @Override public final boolean isSparse() {return true;} @Override public final int sparseLen(){ return _sparse_len; } @Override public final int nonzeros(int [] arr){ int len = sparseLen(); int off = _OFF; final int inc = _valsz + 2; for(int i = 0; i < len; ++i, off += inc) arr[i] = UnsafeUtils.get2(_mem, off)&0xFFFF; return len; } @Override boolean set_impl(int idx, long l) { return false; } @Override boolean set_impl(int idx, double d) { return false; } @Override boolean set_impl(int idx, float f ) { return false; } @Override boolean setNA_impl(int idx) { return false; } @Override protected long at8_impl(int idx) { int off = findOffset(idx); if(getId(off) != idx)return 0; long v = getIValue(off); if( v== NAS[_valsz_log]) throw new IllegalArgumentException("at8_abs but value is missing"); return v; } @Override protected double atd_impl(int idx) { int off = findOffset(idx); if(getId(off) != idx)return 0; long v = getIValue(off); return (v == NAS[_valsz_log])?Double.NaN:v; } @Override protected boolean isNA_impl( int i ) { int off = findOffset(i); if(getId(off) != i)return false; return getIValue(off) == NAS[_valsz_log]; } @Override public NewChunk inflate_impl(NewChunk nc) { final int slen = sparseLen(); nc.set_len(_len); nc.set_sparseLen(slen); nc.alloc_mantissa(slen); nc.alloc_exponent(slen); nc.alloc_indices(slen); int off = _OFF; for( int i = 0; i < slen; ++i, off += _ridsz + _valsz) { nc.indices()[i] = getId(off); long v = getIValue(off); if(v == NAS[_valsz_log]) nc.setNA_impl2(i); else nc.mantissa()[i] = v; } return nc; } // get id of nth (chunk-relative) stored element protected final int getId(int off){ return _ridsz == 2 ?UnsafeUtils.get2(_mem,off)&0xFFFF :UnsafeUtils.get4(_mem,off); } // get offset of nth (chunk-relative) stored element private int getOff(int n){return _OFF + (_ridsz + _valsz)*n;} // extract integer value from an (byte)offset protected final long getIValue(int off){ switch(_valsz){ case 1: return _mem[off+ _ridsz]&0xFF; case 2: return UnsafeUtils.get2(_mem, off + _ridsz); case 4: return UnsafeUtils.get4(_mem, off + _ridsz); case 8: return UnsafeUtils.get8(_mem, off + _ridsz); default: throw H2O.unimpl(); } } // find offset of the chunk-relative row id, or -1 if not stored (i.e. sparse zero) // find offset of the chunk-relative row id, or -1 if not stored (i.e. sparse zero) protected final int findOffset(int idx) { if(idx >= _len)throw new IndexOutOfBoundsException(); int sparseLen = sparseLen(); if(sparseLen == 0)return 0; final byte [] mem = _mem; if(idx <= getId(_OFF)) // easy cut off accessing the zeros prior first nz return _OFF; int last = mem.length - _ridsz - _valsz; if(idx >= getId(last)) // easy cut off accessing of the tail zeros return last; final int off = _lastOff; int lastIdx = getId(off); // check the last accessed elem + one after if( idx == lastIdx ) return off; if(idx > lastIdx){ // check the next one (no need to check bounds, already checked at the beginning) final int nextOff = off + _ridsz + _valsz; int nextId = getId(nextOff); if(idx < nextId) return off; if(idx == nextId){ _lastOff = nextOff; return nextOff; } } // binary search int lo=0, hi = sparseLen; while( lo+1 != hi ) { int mid = (hi+lo)>>>1; if( idx < getId(getOff(mid))) hi = mid; else lo = mid; } int y = getOff(lo); _lastOff = y; return y; } @Override public final int nextNZ(int rid){ final int off = rid == -1?_OFF:findOffset(rid); int x = getId(off); if(x > rid)return x; if(off < _mem.length - _ridsz - _valsz) return getId(off + _ridsz + _valsz); return _len; } @Override public AutoBuffer write_impl(AutoBuffer bb) { return bb.putA1(_mem, _mem.length); } @Override public CXIChunk read_impl(AutoBuffer bb) { _mem = bb.bufClose(); _start = -1; set_len(UnsafeUtils.get4(_mem,0)); _ridsz = _mem[4]; _valsz = _mem[5]; int x = _valsz; int log = 0; while(x > 1){ x = x >>> 1; ++log; } _valsz_log = log; _sparse_len = (_mem.length - _OFF) / (_valsz+_ridsz); assert (_mem.length - _OFF) % (_valsz+_ridsz) == 0:"unexpected mem buffer length: meme.length = " + _mem.length + ", off = " + _OFF + ", valSz = " + _valsz + "ridsz = " + _ridsz; return this; } public abstract class Value { protected int _off = 0; public int rowInChunk(){return getId(_off);} public abstract long asLong(); public abstract double asDouble(); public abstract boolean isNA(); } public final class SparseIterator implements Iterator<Value> { final Value _val; public SparseIterator(Value v){_val = v;} @Override public final boolean hasNext(){return _val._off < _mem.length - (_ridsz + _valsz);} @Override public final Value next(){ if(_val._off == 0)_val._off = _OFF; else _val._off += (_ridsz + _valsz); return _val; } @Override public final void remove(){throw new UnsupportedOperationException();} } public Iterator<Value> values(){ return new SparseIterator(new Value(){ @Override public final long asLong(){ long v = getIValue(_off); if(v == NAS[(_valsz >>> 1) - 1]) throw new IllegalArgumentException("at8_abs but value is missing"); return v; } @Override public final double asDouble() { long v = getIValue(_off); return (v == NAS[_valsz_log -1])?Double.NaN:v; } @Override public final boolean isNA(){ long v = getIValue(_off); return (v == NAS[_valsz_log]); } }); } @Override public boolean hasFloat() {return false;} }
add a comment
h2o-core/src/main/java/water/fvec/CXIChunk.java
add a comment
<ide><path>2o-core/src/main/java/water/fvec/CXIChunk.java <ide> <ide> @Override public final boolean isSparse() {return true;} <ide> @Override public final int sparseLen(){ return _sparse_len; } <add> /** Fills in a provided (recycled/reused) temp array of the NZ indices, and <add> * returns the count of them. Array must be large enough. */ <ide> @Override public final int nonzeros(int [] arr){ <ide> int len = sparseLen(); <ide> int off = _OFF;
Java
apache-2.0
2746034cfb540dbd8cfd1f7cfd3613c480c84355
0
MC-U-Team/U-Team-Core,MC-U-Team/U-Team-Core
package info.u_team.u_team_core.util; /** * Basic rgba representation of a color with some conversion methods * * @author HyCraftHD */ public class RGBA { public static final RGBA BLACK = new RGBA(0x000000FF); public static final RGBA WHITE = new RGBA(0xFFFFFFFF); private final int red, green, blue, alpha; private final int colorRGBA; private final int colorARGB; /** * Creates a new RGBA object from a color integer * * @param color hex code of color e.g. 0xFFFFFFFF for white */ public RGBA(int color) { red = (color >> 24 & 255); green = (color >> 16 & 255); blue = (color >> 8 & 255); alpha = (color & 255); colorRGBA = color; colorARGB = ((alpha & 0x0ff) << 24) | ((red & 0x0ff) << 16) | ((green & 0x0ff) << 8) | (blue & 0x0ff); } /** * Creates a new RGBA object from the color components in range from 0 to 255 integers. * * @param red Red component * @param green Green component * @param blue Blue component * @param alpha Alpha component */ public RGBA(int red, int green, int blue, int alpha) { this.red = red; this.green = green; this.blue = blue; this.alpha = alpha; colorRGBA = ((this.red & 0x0ff) << 24) | ((this.green & 0x0ff) << 16) | ((this.blue & 0x0ff) << 8) | (this.alpha & 0x0ff); colorARGB = ((this.alpha & 0x0ff) << 24) | ((this.red & 0x0ff) << 16) | ((this.green & 0x0ff) << 8) | (this.blue & 0x0ff); } /** * Creates a new RGBA object from the color components in range from 0 to 1 floats. * * @param red Red component * @param green Green component * @param blue Blue component * @param alpha Alpha component */ public RGBA(float red, float green, float blue, float alpha) { this.red = (int) (red * 255); this.green = (int) (green * 255); this.blue = (int) (blue * 255); this.alpha = (int) (alpha * 255); colorRGBA = ((this.red & 0x0ff) << 24) | ((this.green & 0x0ff) << 16) | ((this.blue & 0x0ff) << 8) | (this.alpha & 0x0ff); colorARGB = ((this.alpha & 0x0ff) << 24) | ((this.red & 0x0ff) << 16) | ((this.green & 0x0ff) << 8) | (this.blue & 0x0ff); } /** * Get red component in range from 0 to 255 * * @return Red component */ public int getRed() { return red; } /** * Get green component in range from 0 to 255 * * @return Green component */ public int getGreen() { return green; } /** * Get blue component in range from 0 to 255 * * @return Blue component */ public int getBlue() { return blue; } /** * Get alpha component in range from 0 to 255 * * @return Alpha component */ public int getAlpha() { return alpha; } /** * Get red component in range from 0 to 1 * * @return Red component */ public float getRedComponent() { return red / 255F; } /** * Get green component in range from 0 to 1 * * @return Green component */ public float getGreenComponent() { return green / 255F; } /** * Get blue component in range from 0 to 1 * * @return Blue component */ public float getBlueComponent() { return blue / 255F; } /** * Get alpha component in range from 0 to 1 * * @return Alpha component */ public float getAlphaComponent() { return alpha / 255F; } /** * Get the integer (hex) representation of this color in rgba format * * @return Color as an integer */ public int getColor() { return colorRGBA; } /** * Get the integer (hex) representation of this color in argb format * * @return Color as an integer */ public int getColorARGB() { return colorARGB; } /** * Set the red component in range from 0 to 255 * * @param red Red component * @return A new RGBA instance with the red value set */ public RGBA setRed(int red) { return new RGBA(red, getGreen(), getBlue(), getAlpha()); } /** * Set the green component in range from 0 to 255 * * @param green Green component * @return A new RGBA instance with the green value set */ public RGBA setGreen(int green) { return new RGBA(getRed(), green, getBlue(), getAlpha()); } /** * Set the blue component in range from 0 to 255 * * @param blue Blue component * @return A new RGBA instance with the blue value set */ public RGBA setBlue(int blue) { return new RGBA(getRed(), getGreen(), blue, getAlpha()); } /** * Set the alpha component in range from 0 to 255 * * @param alpha Alpha component * @return A new RGBA instance with the alpha value set */ public RGBA setAlpha(int alpha) { return new RGBA(getRed(), getGreen(), getBlue(), alpha); } /** * Set the red component in range from 0 to 1 * * @param red Red component * @return A new RGBA instance with the red value set */ public RGBA setRedComponent(float red) { return new RGBA((int) (red * 255), getGreen(), getBlue(), getAlpha()); } /** * Set the green component in range from 0 to 1 * * @param green Green component * @return A new RGBA instance with the green value set */ public RGBA setGreenComponent(float green) { return new RGBA(getRed(), (int) (green * 255), getBlue(), getAlpha()); } /** * Set the blue component in range from 0 to 1 * * @param blue Blue component * @return A new RGBA instance with the blue value set */ public RGBA setBlueComponent(float blue) { return new RGBA(getRed(), getGreen(), (int) (blue * 255), getAlpha()); } /** * Set the alpha component in range from 0 to 1 * * @param alpha Alpha component * @return A new RGBA instance with the alpha value set */ public RGBA setAlphaComponent(float alpha) { return new RGBA(getRed(), getGreen(), getBlue(), (int) (alpha * 255)); } @Override public String toString() { return "RGBA [red=" + red + ", green=" + green + ", blue=" + blue + ", alpha=" + alpha + "]"; } /** * Returns an {@link RGBA} object from an argb integer. This encoding is used in many minecraft stuff * * @param color ARBA color * @return RGBA object */ public static RGBA fromARGB(int color) { final var red = (color >> 16 & 255); final var green = (color >> 8 & 255); final var blue = (color & 255); final var alpha = (color >> 24 & 255); return new RGBA(red, green, blue, alpha); } }
src/main/java/info/u_team/u_team_core/util/RGBA.java
package info.u_team.u_team_core.util; import org.lwjgl.opengl.GL11; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; /** * Basic rgba representation of a color with some conversion methods * * @author HyCraftHD */ public class RGBA { public static final RGBA BLACK = new RGBA(0x000000FF); public static final RGBA WHITE = new RGBA(0xFFFFFFFF); private final int red, green, blue, alpha; private final int colorRGBA; private final int colorARGB; /** * Creates a new RGBA object from a color integer * * @param color hex code of color e.g. 0xFFFFFFFF for white */ public RGBA(int color) { red = (color >> 24 & 255); green = (color >> 16 & 255); blue = (color >> 8 & 255); alpha = (color & 255); colorRGBA = color; colorARGB = ((alpha & 0x0ff) << 24) | ((red & 0x0ff) << 16) | ((green & 0x0ff) << 8) | (blue & 0x0ff); } /** * Creates a new RGBA object from the color components in range from 0 to 255 integers. * * @param red Red component * @param green Green component * @param blue Blue component * @param alpha Alpha component */ public RGBA(int red, int green, int blue, int alpha) { this.red = red; this.green = green; this.blue = blue; this.alpha = alpha; colorRGBA = ((this.red & 0x0ff) << 24) | ((this.green & 0x0ff) << 16) | ((this.blue & 0x0ff) << 8) | (this.alpha & 0x0ff); colorARGB = ((this.alpha & 0x0ff) << 24) | ((this.red & 0x0ff) << 16) | ((this.green & 0x0ff) << 8) | (this.blue & 0x0ff); } /** * Creates a new RGBA object from the color components in range from 0 to 1 floats. * * @param red Red component * @param green Green component * @param blue Blue component * @param alpha Alpha component */ public RGBA(float red, float green, float blue, float alpha) { this.red = (int) (red * 255); this.green = (int) (green * 255); this.blue = (int) (blue * 255); this.alpha = (int) (alpha * 255); colorRGBA = ((this.red & 0x0ff) << 24) | ((this.green & 0x0ff) << 16) | ((this.blue & 0x0ff) << 8) | (this.alpha & 0x0ff); colorARGB = ((this.alpha & 0x0ff) << 24) | ((this.red & 0x0ff) << 16) | ((this.green & 0x0ff) << 8) | (this.blue & 0x0ff); } /** * Get red component in range from 0 to 255 * * @return Red component */ public int getRed() { return red; } /** * Get green component in range from 0 to 255 * * @return Green component */ public int getGreen() { return green; } /** * Get blue component in range from 0 to 255 * * @return Blue component */ public int getBlue() { return blue; } /** * Get alpha component in range from 0 to 255 * * @return Alpha component */ public int getAlpha() { return alpha; } /** * Get red component in range from 0 to 1 * * @return Red component */ public float getRedComponent() { return red / 255F; } /** * Get green component in range from 0 to 1 * * @return Green component */ public float getGreenComponent() { return green / 255F; } /** * Get blue component in range from 0 to 1 * * @return Blue component */ public float getBlueComponent() { return blue / 255F; } /** * Get alpha component in range from 0 to 1 * * @return Alpha component */ public float getAlphaComponent() { return alpha / 255F; } /** * Get the integer (hex) representation of this color in rgba format * * @return Color as an integer */ public int getColor() { return colorRGBA; } /** * Get the integer (hex) representation of this color in argb format * * @return Color as an integer */ public int getColorARGB() { return colorARGB; } /** * Set the red component in range from 0 to 255 * * @param red Red component * @return A new RGBA instance with the red value set */ public RGBA setRed(int red) { return new RGBA(red, getGreen(), getBlue(), getAlpha()); } /** * Set the green component in range from 0 to 255 * * @param green Green component * @return A new RGBA instance with the green value set */ public RGBA setGreen(int green) { return new RGBA(getRed(), green, getBlue(), getAlpha()); } /** * Set the blue component in range from 0 to 255 * * @param blue Blue component * @return A new RGBA instance with the blue value set */ public RGBA setBlue(int blue) { return new RGBA(getRed(), getGreen(), blue, getAlpha()); } /** * Set the alpha component in range from 0 to 255 * * @param alpha Alpha component * @return A new RGBA instance with the alpha value set */ public RGBA setAlpha(int alpha) { return new RGBA(getRed(), getGreen(), getBlue(), alpha); } /** * Set the red component in range from 0 to 1 * * @param red Red component * @return A new RGBA instance with the red value set */ public RGBA setRedComponent(float red) { return new RGBA((int) (red * 255), getGreen(), getBlue(), getAlpha()); } /** * Set the green component in range from 0 to 1 * * @param green Green component * @return A new RGBA instance with the green value set */ public RGBA setGreenComponent(float green) { return new RGBA(getRed(), (int) (green * 255), getBlue(), getAlpha()); } /** * Set the blue component in range from 0 to 1 * * @param blue Blue component * @return A new RGBA instance with the blue value set */ public RGBA setBlueComponent(float blue) { return new RGBA(getRed(), getGreen(), (int) (blue * 255), getAlpha()); } /** * Set the alpha component in range from 0 to 1 * * @param alpha Alpha component * @return A new RGBA instance with the alpha value set */ public RGBA setAlphaComponent(float alpha) { return new RGBA(getRed(), getGreen(), getBlue(), (int) (alpha * 255)); } /** * Calls {@link GL11#glColor4f(float, float, float, float)} to color something with gl */ @OnlyIn(Dist.CLIENT) @Deprecated public void glColor() { GL11.glColor4f(getRedComponent(), getGreenComponent(), getBlueComponent(), getAlphaComponent()); } @Override public String toString() { return "RGBA [red=" + red + ", green=" + green + ", blue=" + blue + ", alpha=" + alpha + "]"; } /** * Returns an {@link RGBA} object from an argb integer. This encoding is used in many minecraft stuff * * @param color ARBA color * @return RGBA object */ public static RGBA fromARGB(int color) { final var red = (color >> 16 & 255); final var green = (color >> 8 & 255); final var blue = (color & 255); final var alpha = (color >> 24 & 255); return new RGBA(red, green, blue, alpha); } }
Remove deprecated method
src/main/java/info/u_team/u_team_core/util/RGBA.java
Remove deprecated method
<ide><path>rc/main/java/info/u_team/u_team_core/util/RGBA.java <ide> package info.u_team.u_team_core.util; <del> <del>import org.lwjgl.opengl.GL11; <del> <del>import net.minecraftforge.api.distmarker.Dist; <del>import net.minecraftforge.api.distmarker.OnlyIn; <ide> <ide> /** <ide> * Basic rgba representation of a color with some conversion methods <ide> return new RGBA(getRed(), getGreen(), getBlue(), (int) (alpha * 255)); <ide> } <ide> <del> /** <del> * Calls {@link GL11#glColor4f(float, float, float, float)} to color something with gl <del> */ <del> @OnlyIn(Dist.CLIENT) <del> @Deprecated <del> public void glColor() { <del> GL11.glColor4f(getRedComponent(), getGreenComponent(), getBlueComponent(), getAlphaComponent()); <del> } <del> <ide> @Override <ide> public String toString() { <ide> return "RGBA [red=" + red + ", green=" + green + ", blue=" + blue + ", alpha=" + alpha + "]";
Java
apache-2.0
64617a846c9fa06215031b2ad34a30d58003a732
0
GerritCodeReview/plugins_replication,qtproject/qtqa-gerrit-plugin-replication
// Copyright (C) 2009 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication; import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isGerrit; import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isSSH; import com.google.common.base.Objects; import com.google.common.base.Strings; import com.google.common.collect.Queues; import com.google.gerrit.common.Nullable; import com.google.gerrit.extensions.events.GitReferenceUpdatedListener; import com.google.gerrit.extensions.events.HeadUpdatedListener; import com.google.gerrit.extensions.events.LifecycleListener; import com.google.gerrit.extensions.events.ProjectDeletedListener; import com.google.gerrit.extensions.registration.DynamicItem; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.server.UsedAt; import com.google.gerrit.server.events.EventDispatcher; import com.google.gerrit.server.git.WorkQueue; import com.google.inject.Inject; import com.googlesource.gerrit.plugins.replication.PushResultProcessing.GitUpdateProcessing; import com.googlesource.gerrit.plugins.replication.ReplicationConfig.FilterType; import com.googlesource.gerrit.plugins.replication.ReplicationTasksStorage.ReplicateRefUpdate; import java.net.URISyntaxException; import java.util.Collections; import java.util.HashSet; import java.util.Optional; import java.util.Queue; import java.util.Set; import org.eclipse.jgit.transport.URIish; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** Manages automatic replication to remote repositories. */ public class ReplicationQueue implements LifecycleListener, GitReferenceUpdatedListener, ProjectDeletedListener, HeadUpdatedListener { static final String REPLICATION_LOG_NAME = "replication_log"; static final Logger repLog = LoggerFactory.getLogger(REPLICATION_LOG_NAME); private final ReplicationStateListener stateLog; static String replaceName(String in, String name, boolean keyIsOptional) { String key = "${name}"; int n = in.indexOf(key); if (0 <= n) { return in.substring(0, n) + name + in.substring(n + key.length()); } if (keyIsOptional) { return in; } return null; } private final WorkQueue workQueue; private final DynamicItem<EventDispatcher> dispatcher; private final ReplicationConfig config; private final DynamicItem<AdminApiFactory> adminApiFactory; private final ReplicationTasksStorage replicationTasksStorage; private volatile boolean running; private volatile boolean replaying; private final Queue<ReferenceUpdatedEvent> beforeStartupEventsQueue; @Inject ReplicationQueue( WorkQueue wq, DynamicItem<AdminApiFactory> aaf, ReplicationConfig rc, DynamicItem<EventDispatcher> dis, ReplicationStateListeners sl, ReplicationTasksStorage rts) { workQueue = wq; dispatcher = dis; config = rc; stateLog = sl; adminApiFactory = aaf; replicationTasksStorage = rts; beforeStartupEventsQueue = Queues.newConcurrentLinkedQueue(); } @Override public void start() { if (!running) { config.startup(workQueue); running = true; Thread t = new Thread(this::firePendingEvents, "firePendingEvents"); t.setDaemon(true); t.start(); fireBeforeStartupEvents(); } } @Override public void stop() { running = false; int discarded = config.shutdown(); if (discarded > 0) { repLog.warn("Canceled {} replication events during shutdown", discarded); } } public boolean isRunning() { return running; } public boolean isReplaying() { return replaying; } public void scheduleFullSync( Project.NameKey project, String urlMatch, ReplicationState state, boolean now) { if (!running) { stateLog.warn("Replication plugin did not finish startup before event", state); return; } for (Destination cfg : config.getDestinations(FilterType.ALL)) { if (cfg.wouldPushProject(project)) { for (URIish uri : cfg.getURIs(project, urlMatch)) { cfg.schedule(project, PushOne.ALL_REFS, uri, state, now); replicationTasksStorage.persist( new ReplicateRefUpdate( project.get(), PushOne.ALL_REFS, uri, cfg.getRemoteConfigName())); } } } } @Override public void onGitReferenceUpdated(GitReferenceUpdatedListener.Event event) { onGitReferenceUpdated(event.getProjectName(), event.getRefName()); } private void onGitReferenceUpdated(String projectName, String refName) { ReplicationState state = new ReplicationState(new GitUpdateProcessing(dispatcher.get())); if (!running) { stateLog.warn( "Replication plugin did not finish startup before event, event replication is postponed", state); beforeStartupEventsQueue.add(new ReferenceUpdatedEvent(projectName, refName)); return; } Project.NameKey project = new Project.NameKey(projectName); for (Destination cfg : config.getDestinations(FilterType.ALL)) { pushReference(cfg, project, refName, state); } state.markAllPushTasksScheduled(); } private void fire(URIish uri, Project.NameKey project, String refName) { ReplicationState state = new ReplicationState(new GitUpdateProcessing(dispatcher.get())); for (Destination dest : config.getDestinations(uri, project, refName)) { dest.schedule(project, refName, uri, state); } state.markAllPushTasksScheduled(); } @UsedAt(UsedAt.Project.COLLABNET) public void pushReference(Destination cfg, Project.NameKey project, String refName) { pushReference(cfg, project, refName, null); } private void pushReference( Destination cfg, Project.NameKey project, String refName, ReplicationState state) { boolean withoutState = state == null; if (withoutState) { state = new ReplicationState(new GitUpdateProcessing(dispatcher.get())); } if (cfg.wouldPushProject(project) && cfg.wouldPushRef(refName)) { for (URIish uri : cfg.getURIs(project, null)) { replicationTasksStorage.persist( new ReplicateRefUpdate(project.get(), refName, uri, cfg.getRemoteConfigName())); cfg.schedule(project, refName, uri, state); } } else { repLog.debug("Skipping ref {} on project {}", refName, project.get()); } if (withoutState) { state.markAllPushTasksScheduled(); } } private void firePendingEvents() { try { replaying = true; for (ReplicationTasksStorage.ReplicateRefUpdate t : replicationTasksStorage.list()) { if (t == null) { repLog.warn("Encountered null replication event in ReplicationTasksStorage"); continue; } try { fire(new URIish(t.uri), new Project.NameKey(t.project), t.ref); } catch (URISyntaxException e) { repLog.error("Encountered malformed URI for persisted event %s", t); } } } catch (Throwable e) { repLog.error("Unexpected error while firing pending events", e); } finally { replaying = false; } } @Override public void onProjectDeleted(ProjectDeletedListener.Event event) { Project.NameKey projectName = new Project.NameKey(event.getProjectName()); for (URIish uri : getURIs(null, projectName, FilterType.PROJECT_DELETION)) { deleteProject(uri, projectName); } } @Override public void onHeadUpdated(HeadUpdatedListener.Event event) { Project.NameKey project = new Project.NameKey(event.getProjectName()); for (URIish uri : getURIs(null, project, FilterType.ALL)) { updateHead(uri, project, event.getNewHeadName()); } } private void fireBeforeStartupEvents() { Set<String> eventsReplayed = new HashSet<>(); for (ReferenceUpdatedEvent event : beforeStartupEventsQueue) { String eventKey = String.format("%s:%s", event.getProjectName(), event.getRefName()); if (!eventsReplayed.contains(eventKey)) { repLog.info("Firing pending task {}", event); onGitReferenceUpdated(event.getProjectName(), event.getRefName()); eventsReplayed.add(eventKey); } } } private Set<URIish> getURIs( @Nullable String remoteName, Project.NameKey projectName, FilterType filterType) { if (config.getDestinations(filterType).isEmpty()) { return Collections.emptySet(); } if (!running) { repLog.error("Replication plugin did not finish startup before event"); return Collections.emptySet(); } Set<URIish> uris = new HashSet<>(); for (Destination config : this.config.getDestinations(filterType)) { if (filterType != FilterType.PROJECT_DELETION && !config.wouldPushProject(projectName)) { continue; } if (remoteName != null && !config.getRemoteConfigName().equals(remoteName)) { continue; } boolean adminURLUsed = false; for (String url : config.getAdminUrls()) { if (Strings.isNullOrEmpty(url)) { continue; } URIish uri; try { uri = new URIish(url); } catch (URISyntaxException e) { repLog.warn("adminURL '{}' is invalid: {}", url, e.getMessage()); continue; } if (!isGerrit(uri)) { String path = replaceName(uri.getPath(), projectName.get(), config.isSingleProjectMatch()); if (path == null) { repLog.warn("adminURL {} does not contain ${name}", uri); continue; } uri = uri.setPath(path); if (!isSSH(uri)) { repLog.warn("adminURL '{}' is invalid: only SSH is supported", uri); continue; } } uris.add(uri); adminURLUsed = true; } if (!adminURLUsed) { for (URIish uri : config.getURIs(projectName, "*")) { uris.add(uri); } } } return uris; } public boolean createProject(String remoteName, Project.NameKey project, String head) { boolean success = true; for (URIish uri : getURIs(remoteName, project, FilterType.PROJECT_CREATION)) { success &= createProject(uri, project, head); } return success; } private boolean createProject(URIish replicateURI, Project.NameKey projectName, String head) { Optional<AdminApi> adminApi = adminApiFactory.get().create(replicateURI); if (adminApi.isPresent() && adminApi.get().createProject(projectName, head)) { return true; } warnCannotPerform("create new project", replicateURI); return false; } private void deleteProject(URIish replicateURI, Project.NameKey projectName) { Optional<AdminApi> adminApi = adminApiFactory.get().create(replicateURI); if (adminApi.isPresent()) { adminApi.get().deleteProject(projectName); return; } warnCannotPerform("delete project", replicateURI); } private void updateHead(URIish replicateURI, Project.NameKey projectName, String newHead) { Optional<AdminApi> adminApi = adminApiFactory.get().create(replicateURI); if (adminApi.isPresent()) { adminApi.get().updateHead(projectName, newHead); return; } warnCannotPerform("update HEAD of project", replicateURI); } private void warnCannotPerform(String op, URIish uri) { repLog.warn("Cannot {} on remote site {}.", op, uri); } private static class ReferenceUpdatedEvent { private String projectName; private String refName; public ReferenceUpdatedEvent(String projectName, String refName) { this.projectName = projectName; this.refName = refName; } public String getProjectName() { return projectName; } public String getRefName() { return refName; } @Override public int hashCode() { return Objects.hashCode(projectName, refName); } @Override public boolean equals(Object obj) { return (obj instanceof ReferenceUpdatedEvent) && Objects.equal(projectName, ((ReferenceUpdatedEvent) obj).projectName) && Objects.equal(refName, ((ReferenceUpdatedEvent) obj).refName); } } }
src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java
// Copyright (C) 2009 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication; import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isGerrit; import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isSSH; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import com.google.common.base.Strings; import com.google.common.collect.Queues; import com.google.gerrit.common.Nullable; import com.google.gerrit.extensions.events.GitReferenceUpdatedListener; import com.google.gerrit.extensions.events.HeadUpdatedListener; import com.google.gerrit.extensions.events.LifecycleListener; import com.google.gerrit.extensions.events.ProjectDeletedListener; import com.google.gerrit.extensions.registration.DynamicItem; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.server.UsedAt; import com.google.gerrit.server.events.EventDispatcher; import com.google.gerrit.server.git.WorkQueue; import com.google.inject.Inject; import com.googlesource.gerrit.plugins.replication.PushResultProcessing.GitUpdateProcessing; import com.googlesource.gerrit.plugins.replication.ReplicationConfig.FilterType; import com.googlesource.gerrit.plugins.replication.ReplicationTasksStorage.ReplicateRefUpdate; import java.net.URISyntaxException; import java.util.Collections; import java.util.HashSet; import java.util.Optional; import java.util.Queue; import java.util.Set; import org.eclipse.jgit.transport.URIish; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** Manages automatic replication to remote repositories. */ public class ReplicationQueue implements LifecycleListener, GitReferenceUpdatedListener, ProjectDeletedListener, HeadUpdatedListener { static final String REPLICATION_LOG_NAME = "replication_log"; static final Logger repLog = LoggerFactory.getLogger(REPLICATION_LOG_NAME); private final ReplicationStateListener stateLog; static String replaceName(String in, String name, boolean keyIsOptional) { String key = "${name}"; int n = in.indexOf(key); if (0 <= n) { return in.substring(0, n) + name + in.substring(n + key.length()); } if (keyIsOptional) { return in; } return null; } private final WorkQueue workQueue; private final DynamicItem<EventDispatcher> dispatcher; private final ReplicationConfig config; private final DynamicItem<AdminApiFactory> adminApiFactory; private final ReplicationTasksStorage replicationTasksStorage; private volatile boolean running; private volatile boolean replaying; private final Queue<ReferenceUpdatedEvent> beforeStartupEventsQueue; @Inject ReplicationQueue( WorkQueue wq, DynamicItem<AdminApiFactory> aaf, ReplicationConfig rc, DynamicItem<EventDispatcher> dis, ReplicationStateListeners sl, ReplicationTasksStorage rts) { workQueue = wq; dispatcher = dis; config = rc; stateLog = sl; adminApiFactory = aaf; replicationTasksStorage = rts; beforeStartupEventsQueue = Queues.newConcurrentLinkedQueue(); } @Override public void start() { if (!running) { config.startup(workQueue); running = true; Thread t = new Thread(this::firePendingEvents, "firePendingEvents"); t.setDaemon(true); t.start(); fireBeforeStartupEvents(); } } @Override public void stop() { running = false; int discarded = config.shutdown(); if (discarded > 0) { repLog.warn("Canceled {} replication events during shutdown", discarded); } } public boolean isRunning() { return running; } public boolean isReplaying() { return replaying; } void scheduleFullSync(Project.NameKey project, String urlMatch, ReplicationState state) { scheduleFullSync(project, urlMatch, state, false); } @VisibleForTesting public void scheduleFullSync( Project.NameKey project, String urlMatch, ReplicationState state, boolean now) { if (!running) { stateLog.warn("Replication plugin did not finish startup before event", state); return; } for (Destination cfg : config.getDestinations(FilterType.ALL)) { if (cfg.wouldPushProject(project)) { for (URIish uri : cfg.getURIs(project, urlMatch)) { cfg.schedule(project, PushOne.ALL_REFS, uri, state, now); replicationTasksStorage.persist( new ReplicateRefUpdate( project.get(), PushOne.ALL_REFS, uri, cfg.getRemoteConfigName())); } } } } @Override public void onGitReferenceUpdated(GitReferenceUpdatedListener.Event event) { onGitReferenceUpdated(event.getProjectName(), event.getRefName()); } private void onGitReferenceUpdated(String projectName, String refName) { ReplicationState state = new ReplicationState(new GitUpdateProcessing(dispatcher.get())); if (!running) { stateLog.warn( "Replication plugin did not finish startup before event, event replication is postponed", state); beforeStartupEventsQueue.add(new ReferenceUpdatedEvent(projectName, refName)); return; } Project.NameKey project = new Project.NameKey(projectName); for (Destination cfg : config.getDestinations(FilterType.ALL)) { pushReference(cfg, project, refName, state); } state.markAllPushTasksScheduled(); } private void fire(URIish uri, Project.NameKey project, String refName) { ReplicationState state = new ReplicationState(new GitUpdateProcessing(dispatcher.get())); for (Destination dest : config.getDestinations(uri, project, refName)) { dest.schedule(project, refName, uri, state); } state.markAllPushTasksScheduled(); } @UsedAt(UsedAt.Project.COLLABNET) public void pushReference(Destination cfg, Project.NameKey project, String refName) { pushReference(cfg, project, refName, null); } private void pushReference( Destination cfg, Project.NameKey project, String refName, ReplicationState state) { boolean withoutState = state == null; if (withoutState) { state = new ReplicationState(new GitUpdateProcessing(dispatcher.get())); } if (cfg.wouldPushProject(project) && cfg.wouldPushRef(refName)) { for (URIish uri : cfg.getURIs(project, null)) { replicationTasksStorage.persist( new ReplicateRefUpdate(project.get(), refName, uri, cfg.getRemoteConfigName())); cfg.schedule(project, refName, uri, state); } } else { repLog.debug("Skipping ref {} on project {}", refName, project.get()); } if (withoutState) { state.markAllPushTasksScheduled(); } } private void firePendingEvents() { try { replaying = true; for (ReplicationTasksStorage.ReplicateRefUpdate t : replicationTasksStorage.list()) { if (t == null) { repLog.warn("Encountered null replication event in ReplicationTasksStorage"); continue; } try { fire(new URIish(t.uri), new Project.NameKey(t.project), t.ref); } catch (URISyntaxException e) { repLog.error("Encountered malformed URI for persisted event %s", t); } } } catch (Throwable e) { repLog.error("Unexpected error while firing pending events", e); } finally { replaying = false; } } @Override public void onProjectDeleted(ProjectDeletedListener.Event event) { Project.NameKey projectName = new Project.NameKey(event.getProjectName()); for (URIish uri : getURIs(null, projectName, FilterType.PROJECT_DELETION)) { deleteProject(uri, projectName); } } @Override public void onHeadUpdated(HeadUpdatedListener.Event event) { Project.NameKey project = new Project.NameKey(event.getProjectName()); for (URIish uri : getURIs(null, project, FilterType.ALL)) { updateHead(uri, project, event.getNewHeadName()); } } private void fireBeforeStartupEvents() { Set<String> eventsReplayed = new HashSet<>(); for (ReferenceUpdatedEvent event : beforeStartupEventsQueue) { String eventKey = String.format("%s:%s", event.getProjectName(), event.getRefName()); if (!eventsReplayed.contains(eventKey)) { repLog.info("Firing pending task {}", event); onGitReferenceUpdated(event.getProjectName(), event.getRefName()); eventsReplayed.add(eventKey); } } } private Set<URIish> getURIs( @Nullable String remoteName, Project.NameKey projectName, FilterType filterType) { if (config.getDestinations(filterType).isEmpty()) { return Collections.emptySet(); } if (!running) { repLog.error("Replication plugin did not finish startup before event"); return Collections.emptySet(); } Set<URIish> uris = new HashSet<>(); for (Destination config : this.config.getDestinations(filterType)) { if (filterType != FilterType.PROJECT_DELETION && !config.wouldPushProject(projectName)) { continue; } if (remoteName != null && !config.getRemoteConfigName().equals(remoteName)) { continue; } boolean adminURLUsed = false; for (String url : config.getAdminUrls()) { if (Strings.isNullOrEmpty(url)) { continue; } URIish uri; try { uri = new URIish(url); } catch (URISyntaxException e) { repLog.warn("adminURL '{}' is invalid: {}", url, e.getMessage()); continue; } if (!isGerrit(uri)) { String path = replaceName(uri.getPath(), projectName.get(), config.isSingleProjectMatch()); if (path == null) { repLog.warn("adminURL {} does not contain ${name}", uri); continue; } uri = uri.setPath(path); if (!isSSH(uri)) { repLog.warn("adminURL '{}' is invalid: only SSH is supported", uri); continue; } } uris.add(uri); adminURLUsed = true; } if (!adminURLUsed) { for (URIish uri : config.getURIs(projectName, "*")) { uris.add(uri); } } } return uris; } public boolean createProject(String remoteName, Project.NameKey project, String head) { boolean success = true; for (URIish uri : getURIs(remoteName, project, FilterType.PROJECT_CREATION)) { success &= createProject(uri, project, head); } return success; } private boolean createProject(URIish replicateURI, Project.NameKey projectName, String head) { Optional<AdminApi> adminApi = adminApiFactory.get().create(replicateURI); if (adminApi.isPresent() && adminApi.get().createProject(projectName, head)) { return true; } warnCannotPerform("create new project", replicateURI); return false; } private void deleteProject(URIish replicateURI, Project.NameKey projectName) { Optional<AdminApi> adminApi = adminApiFactory.get().create(replicateURI); if (adminApi.isPresent()) { adminApi.get().deleteProject(projectName); return; } warnCannotPerform("delete project", replicateURI); } private void updateHead(URIish replicateURI, Project.NameKey projectName, String newHead) { Optional<AdminApi> adminApi = adminApiFactory.get().create(replicateURI); if (adminApi.isPresent()) { adminApi.get().updateHead(projectName, newHead); return; } warnCannotPerform("update HEAD of project", replicateURI); } private void warnCannotPerform(String op, URIish uri) { repLog.warn("Cannot {} on remote site {}.", op, uri); } private static class ReferenceUpdatedEvent { private String projectName; private String refName; public ReferenceUpdatedEvent(String projectName, String refName) { this.projectName = projectName; this.refName = refName; } public String getProjectName() { return projectName; } public String getRefName() { return refName; } @Override public int hashCode() { return Objects.hashCode(projectName, refName); } @Override public boolean equals(Object obj) { return (obj instanceof ReferenceUpdatedEvent) && Objects.equal(projectName, ((ReferenceUpdatedEvent) obj).projectName) && Objects.equal(refName, ((ReferenceUpdatedEvent) obj).refName); } } }
ReplicationQueue: Remove unused method And drop the misleading @VisibleForTesting annotation from the method the removed method was wrapping. scheduleFullSync() is public so that PushAll can call it. Change-Id: I0139e653654fcaf20de68dddfb5ea85560a323d0
src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java
ReplicationQueue: Remove unused method
<ide><path>rc/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java <ide> import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isGerrit; <ide> import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isSSH; <ide> <del>import com.google.common.annotations.VisibleForTesting; <ide> import com.google.common.base.Objects; <ide> import com.google.common.base.Strings; <ide> import com.google.common.collect.Queues; <ide> return replaying; <ide> } <ide> <del> void scheduleFullSync(Project.NameKey project, String urlMatch, ReplicationState state) { <del> scheduleFullSync(project, urlMatch, state, false); <del> } <del> <del> @VisibleForTesting <ide> public void scheduleFullSync( <ide> Project.NameKey project, String urlMatch, ReplicationState state, boolean now) { <ide> if (!running) {
Java
agpl-3.0
cf04ac3b6324c15566b888311e08e5639c0cf9b6
0
AlienQueen/alienlabs-skeleton-for-wicket-spring-hibernate,AlienQueen/alienlabs-skeleton-for-wicket-spring-hibernate,AlienQueen/alienlabs-skeleton-for-wicket-spring-hibernate,AlienQueen/alienlabs-skeleton-for-wicket-spring-hibernate,AlienQueen/alienlabs-skeleton-for-wicket-spring-hibernate
package org.alienlabs.amazon; import java.io.UnsupportedEncodingException; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormSubmitBehavior; import org.apache.wicket.extensions.ajax.markup.html.IndicatingAjaxButton; import org.apache.wicket.injection.Injector; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Button; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.markup.html.form.upload.FileUpload; import org.apache.wicket.markup.html.form.upload.FileUploadField; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.Model; import org.apache.wicket.spring.injection.annot.SpringBean; import org.apache.wicket.util.lang.Bytes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Required; import com.xuggle.mediatool.IMediaReader; import com.xuggle.mediatool.IMediaWriter; import com.xuggle.mediatool.MediaToolAdapter; import com.xuggle.mediatool.MediaListenerAdapter; import com.xuggle.mediatool.ToolFactory; import com.xuggle.mediatool.event.IAudioSamplesEvent; import com.xuggle.mediatool.event.ICloseEvent; import com.xuggle.mediatool.event.IOpenCoderEvent; import com.xuggle.mediatool.event.IAddStreamEvent; import com.xuggle.xuggler.IContainer; import com.xuggle.xuggler.IStreamCoder; @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = { "SE_INNER_CLASS", "SIC_INNER_SHOULD_BE_STATIC_ANON" }, justification = "In Wicket, serializable inner classes are common. And as the parent Page is serialized as well, this is no concern. This is no bad practice in Wicket") public class ImportDeckDialog extends Panel { private static final Logger LOGGER = LoggerFactory.getLogger(ImportDeckDialog.class); private static final long serialVersionUID = 1L; final FileUploadField file; public ImportDeckDialog(final String id) { super(id); Injector.get().inject(this); final Form<Void> form = new Form<>("form"); this.file = new FileUploadField("deckFile"); form.setMarkupId("inputForm").setOutputMarkupId(true); form.setMaxSize(Bytes.kilobytes(5)); form.setMultiPart(true); form.add(this.file); this.add(form); final Button upload = new Button("upload") { @Override public void onSubmit() { ImportDeckDialog.LOGGER.info("trying to upload something"); //final FileUpload fupload = ImportDeckDialog.this.file.getFileUpload(); //if (fupload == null) //{ // No file was provided // ImportDeckDialog.LOGGER.info("Please provide a valid file"); // return; //} //else if (fupload.getSize() == 0) //{ // ImportDeckDialog.LOGGER.info("Please provide a non-empty file"); // return; //} //else if ((fupload.getClientFileName() == null) // || ("".equals(fupload.getClientFileName().trim())) // || (fupload.getClientFileName().endsWith(".txt"))) //{ // ImportDeckDialog.LOGGER.info("Please provide a valid file"); // return; //} //ImportDeckDialog.LOGGER.info("uploading file: " // + ImportDeckDialog.this.file.getFileUpload().getClientFileName()); //try //{ // new String(fupload.getBytes(), "UTF-8"); ImportDeckDialog.convert("/home/nostromo/test.avi", "/home/nostromo/test.wav"); //} //catch (final UnsupportedEncodingException e) //{ // ImportDeckDialog.LOGGER.info("Please provide a file encoded with UTF-8 charset"); // return; //} //ImportDeckDialog.LOGGER.info("successfully added deck: " // + fupload.getClientFileName()); ImportDeckDialog.LOGGER.info("Your file has been successfully uploaded"); } }; form.add(upload); } public static void convert(String from, final String to) { IMediaReader mediaReader = ToolFactory.makeReader(from); final int mySampleRate = 44100; final int myChannels = 1; mediaReader.addListener(new MediaToolAdapter() { private IContainer container; private IMediaWriter mediaWriter; @Override public void onOpenCoder(IOpenCoderEvent event) { container = event.getSource().getContainer(); mediaWriter = null; } @Override public void onAudioSamples(IAudioSamplesEvent event) { if (container != null) { if (mediaWriter == null) { mediaWriter = ToolFactory.makeWriter(to); mediaWriter.addListener(new MediaListenerAdapter() { @Override public void onAddStream(IAddStreamEvent event) { IStreamCoder streamCoder = event.getSource().getContainer().getStream(event.getStreamIndex()).getStreamCoder(); streamCoder.setFlag(IStreamCoder.Flags.FLAG_QSCALE, false); streamCoder.setBitRate(128); streamCoder.setChannels(myChannels); streamCoder.setSampleRate(mySampleRate); streamCoder.setBitRateTolerance(0); } }); mediaWriter.addAudioStream(0, 0, myChannels, mySampleRate); } mediaWriter.encodeAudio(0, event.getAudioSamples()); //System.out.println(event.getTimeStamp() / 1000); } } @Override public void onClose(ICloseEvent event) { if (mediaWriter != null) { mediaWriter.close(); } } }); while (mediaReader.readPacket() == null) { } } }
src/main/java/org/alienlabs/amazon/ImportDeckDialog.java
package org.alienlabs.amazon; import java.io.UnsupportedEncodingException; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormSubmitBehavior; import org.apache.wicket.extensions.ajax.markup.html.IndicatingAjaxButton; import org.apache.wicket.injection.Injector; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Button; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.markup.html.form.upload.FileUpload; import org.apache.wicket.markup.html.form.upload.FileUploadField; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.Model; import org.apache.wicket.spring.injection.annot.SpringBean; import org.apache.wicket.util.lang.Bytes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Required; import com.xuggle.mediatool.IMediaReader; import com.xuggle.mediatool.IMediaWriter; import com.xuggle.mediatool.MediaToolAdapter; import com.xuggle.mediatool.MediaListenerAdapter; import com.xuggle.mediatool.ToolFactory; import com.xuggle.mediatool.event.IAudioSamplesEvent; import com.xuggle.mediatool.event.ICloseEvent; import com.xuggle.mediatool.event.IOpenCoderEvent; import com.xuggle.mediatool.event.IAddStreamEvent; import com.xuggle.xuggler.IContainer; import com.xuggle.xuggler.IStreamCoder; @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = { "SE_INNER_CLASS", "SIC_INNER_SHOULD_BE_STATIC_ANON" }, justification = "In Wicket, serializable inner classes are common. And as the parent Page is serialized as well, this is no concern. This is no bad practice in Wicket") public class ImportDeckDialog extends Panel { private static final Logger LOGGER = LoggerFactory.getLogger(ImportDeckDialog.class); private static final long serialVersionUID = 1L; final FileUploadField file; public ImportDeckDialog(final String id) { super(id); Injector.get().inject(this); final Form<Void> form = new Form<>("form"); this.file = new FileUploadField("deckFile"); form.setMarkupId("inputForm").setOutputMarkupId(true); form.setMaxSize(Bytes.kilobytes(5)); form.setMultiPart(true); form.add(this.file); this.add(form); final Button upload = new Button("upload") { @Override public void onSubmit() { ImportDeckDialog.LOGGER.info("trying to upload something"); //final FileUpload fupload = ImportDeckDialog.this.file.getFileUpload(); //if (fupload == null) //{ // No file was provided // ImportDeckDialog.LOGGER.info("Please provide a valid file"); // return; //} //else if (fupload.getSize() == 0) //{ // ImportDeckDialog.LOGGER.info("Please provide a non-empty file"); // return; //} //else if ((fupload.getClientFileName() == null) // || ("".equals(fupload.getClientFileName().trim())) // || (fupload.getClientFileName().endsWith(".txt"))) //{ // ImportDeckDialog.LOGGER.info("Please provide a valid file"); // return; //} //ImportDeckDialog.LOGGER.info("uploading file: " // + ImportDeckDialog.this.file.getFileUpload().getClientFileName()); try { // new String(fupload.getBytes(), "UTF-8"); ImportDeckDialog.convert("/home/nostromo/test.avi", "/home/nostromo/test.wav"); } catch (final UnsupportedEncodingException e) { ImportDeckDialog.LOGGER.info("Please provide a file encoded with UTF-8 charset"); return; } //ImportDeckDialog.LOGGER.info("successfully added deck: " // + fupload.getClientFileName()); ImportDeckDialog.LOGGER.info("Your file has been successfully uploaded"); } }; form.add(upload); } public static void convert(String from, final String to) { IMediaReader mediaReader = ToolFactory.makeReader(from); final int mySampleRate = 44100; final int myChannels = 1; mediaReader.addListener(new MediaToolAdapter() { private IContainer container; private IMediaWriter mediaWriter; @Override public void onOpenCoder(IOpenCoderEvent event) { container = event.getSource().getContainer(); mediaWriter = null; } @Override public void onAudioSamples(IAudioSamplesEvent event) { if (container != null) { if (mediaWriter == null) { mediaWriter = ToolFactory.makeWriter(to); mediaWriter.addListener(new MediaListenerAdapter() { @Override public void onAddStream(IAddStreamEvent event) { IStreamCoder streamCoder = event.getSource().getContainer().getStream(event.getStreamIndex()).getStreamCoder(); streamCoder.setFlag(IStreamCoder.Flags.FLAG_QSCALE, false); streamCoder.setBitRate(128); streamCoder.setChannels(myChannels); streamCoder.setSampleRate(mySampleRate); streamCoder.setBitRateTolerance(0); } }); mediaWriter.addAudioStream(0, 0, myChannels, mySampleRate); } mediaWriter.encodeAudio(0, event.getAudioSamples()); //System.out.println(event.getTimeStamp() / 1000); } } @Override public void onClose(ICloseEvent event) { if (mediaWriter != null) { mediaWriter.close(); } } }); while (mediaReader.readPacket() == null) { } } }
commented out exception handling, for POC
src/main/java/org/alienlabs/amazon/ImportDeckDialog.java
commented out exception handling, for POC
<ide><path>rc/main/java/org/alienlabs/amazon/ImportDeckDialog.java <ide> //ImportDeckDialog.LOGGER.info("uploading file: " <ide> // + ImportDeckDialog.this.file.getFileUpload().getClientFileName()); <ide> <del> try <del> { <add> //try <add> //{ <ide> // new String(fupload.getBytes(), "UTF-8"); <ide> ImportDeckDialog.convert("/home/nostromo/test.avi", "/home/nostromo/test.wav"); <del> } <del> catch (final UnsupportedEncodingException e) <del> { <del> ImportDeckDialog.LOGGER.info("Please provide a file encoded with UTF-8 charset"); <del> return; <del> } <add> //} <add> //catch (final UnsupportedEncodingException e) <add> //{ <add> // ImportDeckDialog.LOGGER.info("Please provide a file encoded with UTF-8 charset"); <add> // return; <add> //} <ide> <ide> //ImportDeckDialog.LOGGER.info("successfully added deck: " <ide> // + fupload.getClientFileName());
Java
mit
64aa6afbe025d44c6a40f1cdc2c43d87df033a04
0
hudson/hudson-2.x,hudson/hudson-2.x,hudson/hudson-2.x,hudson/hudson-2.x,hudson/hudson-2.x,hudson/hudson-2.x
package org.jvnet.hudson.maven.plugins.hpi; /* * Copyright 2001-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import com.thoughtworks.qdox.JavaDocBuilder; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaSource; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter; import org.apache.maven.model.Resource; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.archiver.UnArchiver; import org.codehaus.plexus.archiver.jar.Manifest.Attribute; import org.codehaus.plexus.archiver.jar.Manifest.Section; import org.codehaus.plexus.archiver.jar.ManifestException; import org.codehaus.plexus.archiver.manager.ArchiverManager; import org.codehaus.plexus.archiver.manager.NoSuchArchiverException; import org.codehaus.plexus.util.DirectoryScanner; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.InterpolationFilterReader; import org.codehaus.plexus.util.StringUtils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.Set; public abstract class AbstractHpiMojo extends AbstractMojo { /** * The directory for the generated WAR. * * @parameter expression="${project.build.directory}" * @required */ protected String outputDirectory; /** * The maven project. * * @parameter expression="${project}" * @required * @readonly */ protected MavenProject project; /** * The directory containing generated classes. * * @parameter expression="${project.build.outputDirectory}" * @required * @readonly */ private File classesDirectory; /** * Name of the plugin that Hudson uses for display purpose. * It should be one line text. * * @parameter expression="${project.name}" * @required * @readonly */ protected String pluginName; /** * The directory where the webapp is built. * * @parameter expression="${project.build.directory}/${project.build.finalName}" * @required */ private File webappDirectory; /** * Single directory for extra files to include in the WAR. * * @parameter expression="${basedir}/src/main/webapp" * @required */ protected File warSourceDirectory; /** * The list of webResources we want to transfer. * * @parameter */ private Resource[] webResources; /** * @parameter expression="${project.build.filters}" */ private List<String> filters; /** * The path to the context.xml file to use. * * @parameter expression="${maven.war.containerConfigXML}" */ private File containerConfigXML; /** * Directory to unpack dependent WARs into if needed * * @parameter expression="${project.build.directory}/war/work" * @required */ private File workDirectory; /** * To look up Archiver/UnArchiver implementations * * @parameter expression="${component.org.codehaus.plexus.archiver.manager.ArchiverManager}" * @required */ protected ArchiverManager archiverManager; private static final String WEB_INF = "WEB-INF"; private static final String META_INF = "META-INF"; private static final String[] DEFAULT_INCLUDES = {"**/**"}; /** * The comma separated list of tokens to include in the WAR. * Default is '**'. * * @parameter alias="includes" */ private String warSourceIncludes = "**"; /** * The comma separated list of tokens to exclude from the WAR. * * @parameter alias="excludes" */ private String warSourceExcludes; /** * The comma separated list of tokens to include when doing * a war overlay. * Default is '**' * * @parameter */ private String dependentWarIncludes = "**"; /** * The comma separated list of tokens to exclude when doing * a way overlay. * * @parameter */ private String dependentWarExcludes; private static final String[] EMPTY_STRING_ARRAY = {}; public File getClassesDirectory() { return classesDirectory; } public void setClassesDirectory(File classesDirectory) { this.classesDirectory = classesDirectory; } public File getWebappDirectory() { return webappDirectory; } public void setWebappDirectory(File webappDirectory) { this.webappDirectory = webappDirectory; } public void setWarSourceDirectory(File warSourceDirectory) { this.warSourceDirectory = warSourceDirectory; } public File getContainerConfigXML() { return containerConfigXML; } public void setContainerConfigXML(File containerConfigXML) { this.containerConfigXML = containerConfigXML; } /** * Returns a string array of the excludes to be used * when assembling/copying the war. * * @return an array of tokens to exclude */ protected String[] getExcludes() { List<String> excludeList = new ArrayList<String>(); if (StringUtils.isNotEmpty(warSourceExcludes)) { excludeList.addAll(Arrays.asList(StringUtils.split(warSourceExcludes, ","))); } // if contextXML is specified, omit the one in the source directory if (containerConfigXML != null && StringUtils.isNotEmpty(containerConfigXML.getName())) { excludeList.add("**/" + META_INF + "/" + containerConfigXML.getName()); } return excludeList.toArray(EMPTY_STRING_ARRAY); } /** * Returns a string array of the includes to be used * when assembling/copying the war. * * @return an array of tokens to include */ protected String[] getIncludes() { return StringUtils.split(StringUtils.defaultString(warSourceIncludes), ","); } /** * Returns a string array of the excludes to be used * when adding dependent wars as an overlay onto this war. * * @return an array of tokens to exclude */ protected String[] getDependentWarExcludes() { String[] excludes; if (StringUtils.isNotEmpty(dependentWarExcludes)) { excludes = StringUtils.split(dependentWarExcludes, ","); } else { excludes = EMPTY_STRING_ARRAY; } return excludes; } /** * Returns a string array of the includes to be used * when adding dependent wars as an overlay onto this war. * * @return an array of tokens to include */ protected String[] getDependentWarIncludes() { return StringUtils.split(StringUtils.defaultString(dependentWarIncludes), ","); } public void buildExplodedWebapp(File webappDirectory) throws MojoExecutionException { getLog().info("Exploding webapp..."); webappDirectory.mkdirs(); File webinfDir = new File(webappDirectory, WEB_INF); webinfDir.mkdirs(); File metainfDir = new File(webappDirectory, META_INF); metainfDir.mkdirs(); try { List<Resource> webResources = this.webResources != null ? Arrays.asList(this.webResources) : null; if (webResources != null && webResources.size() > 0) { Properties filterProperties = getBuildFilterProperties(); for (Resource resource : webResources) { copyResources(resource, webappDirectory, filterProperties); } } copyResources(warSourceDirectory, webappDirectory); if (containerConfigXML != null && StringUtils.isNotEmpty(containerConfigXML.getName())) { metainfDir = new File(webappDirectory, META_INF); String xmlFileName = containerConfigXML.getName(); copyFileIfModified(containerConfigXML, new File(metainfDir, xmlFileName)); } buildWebapp(project, webappDirectory); } catch (IOException e) { throw new MojoExecutionException("Could not explode webapp...", e); } } private Properties getBuildFilterProperties() throws MojoExecutionException { // System properties Properties filterProperties = new Properties(System.getProperties()); // Project properties filterProperties.putAll(project.getProperties()); for (String filter : filters) { try { Properties properties = PropertyUtils.loadPropertyFile(new File(filter), true, true); filterProperties.putAll(properties); } catch (IOException e) { throw new MojoExecutionException("Error loading property file '" + filter + "'", e); } } return filterProperties; } /** * Copies webapp webResources from the specified directory. * <p/> * Note that the <tt>webXml</tt> parameter could be null and may * specify a file which is not named <tt>web.xml<tt>. If the file * exists, it will be copied to the <tt>META-INF</tt> directory and * renamed accordingly. * * @param resource the resource to copy * @param webappDirectory the target directory * @param filterProperties * @throws java.io.IOException if an error occurred while copying webResources */ public void copyResources(Resource resource, File webappDirectory, Properties filterProperties) throws IOException { if (!resource.getDirectory().equals(webappDirectory.getPath())) { getLog().info("Copy webapp webResources to " + webappDirectory.getAbsolutePath()); if (webappDirectory.exists()) { String[] fileNames = getWarFiles(resource); for (String fileName : fileNames) { if (resource.isFiltering()) { copyFilteredFile(new File(resource.getDirectory(), fileName), new File(webappDirectory, fileName), null, getFilterWrappers(), filterProperties); } else { copyFileIfModified(new File(resource.getDirectory(), fileName), new File(webappDirectory, fileName)); } } } } } /** * Copies webapp webResources from the specified directory. * <p/> * Note that the <tt>webXml</tt> parameter could be null and may * specify a file which is not named <tt>web.xml<tt>. If the file * exists, it will be copied to the <tt>META-INF</tt> directory and * renamed accordingly. * * @param sourceDirectory the source directory * @param webappDirectory the target directory * @throws java.io.IOException if an error occurred while copying webResources */ public void copyResources(File sourceDirectory, File webappDirectory) throws IOException { if (!sourceDirectory.equals(webappDirectory)) { getLog().info("Copy webapp webResources to " + webappDirectory.getAbsolutePath()); if (warSourceDirectory.exists()) { String[] fileNames = getWarFiles(sourceDirectory); for (String fileName : fileNames) { copyFileIfModified(new File(sourceDirectory, fileName), new File(webappDirectory, fileName)); } } } } /** * Builds the webapp for the specified project. * <p/> * Classes, libraries and tld files are copied to * the <tt>webappDirectory</tt> during this phase. * * @param project the maven project * @param webappDirectory * @throws java.io.IOException if an error occurred while building the webapp */ public void buildWebapp(MavenProject project, File webappDirectory) throws MojoExecutionException, IOException { getLog().info("Assembling webapp " + project.getArtifactId() + " in " + webappDirectory); File libDirectory = new File(webappDirectory, WEB_INF + "/lib"); File tldDirectory = new File(webappDirectory, WEB_INF + "/tld"); File webappClassesDirectory = new File(webappDirectory, WEB_INF + "/classes"); if (classesDirectory.exists() && !classesDirectory.equals(webappClassesDirectory)) { copyDirectoryStructureIfModified(classesDirectory, webappClassesDirectory); } Set<Artifact> artifacts = project.getArtifacts(); List duplicates = findDuplicates(artifacts); List<File> dependentWarDirectories = new ArrayList<File>(); for (Artifact artifact : artifacts) { String targetFileName = getDefaultFinalName(artifact); getLog().debug("Processing: " + targetFileName); if (duplicates.contains(targetFileName)) { getLog().debug("Duplicate found: " + targetFileName); targetFileName = artifact.getGroupId() + "-" + targetFileName; getLog().debug("Renamed to: " + targetFileName); } // TODO: utilise appropriate methods from project builder ScopeArtifactFilter filter = new ScopeArtifactFilter(Artifact.SCOPE_RUNTIME); if (!artifact.isOptional() && filter.include(artifact)) { String type = artifact.getType(); if ("tld".equals(type)) { copyFileIfModified(artifact.getFile(), new File(tldDirectory, targetFileName)); } else { if ("jar".equals(type) || "ejb".equals(type) || "ejb-client".equals(type)) { copyFileIfModified(artifact.getFile(), new File(libDirectory, targetFileName)); } else { if ("par".equals(type)) { targetFileName = targetFileName.substring(0, targetFileName.lastIndexOf('.')) + ".jar"; getLog().debug( "Copying " + artifact.getFile() + " to " + new File(libDirectory, targetFileName)); copyFileIfModified(artifact.getFile(), new File(libDirectory, targetFileName)); } else { if ("war".equals(type)) { dependentWarDirectories.add(unpackWarToTempDirectory(artifact)); } else { getLog().debug("Skipping artifact of type " + type + " for WEB-INF/lib"); } } } } } } if (dependentWarDirectories.size() > 0) { getLog().info("Overlaying " + dependentWarDirectories.size() + " war(s)."); // overlay dependent wars for (Iterator iter = dependentWarDirectories.iterator(); iter.hasNext();) { copyDependentWarContents((File) iter.next(), webappDirectory); } } } /** * Searches a set of artifacts for duplicate filenames and returns a list of duplicates. * * @param artifacts set of artifacts * @return List of duplicated artifacts */ private List<String> findDuplicates(Set<Artifact> artifacts) { List<String> duplicates = new ArrayList<String>(); List<String> identifiers = new ArrayList<String>(); for (Artifact artifact : artifacts) { String candidate = getDefaultFinalName(artifact); if (identifiers.contains(candidate)) { duplicates.add(candidate); } else { identifiers.add(candidate); } } return duplicates; } /** * Unpacks war artifacts into a temporary directory inside <tt>workDirectory</tt> * named with the name of the war. * * @param artifact War artifact to unpack. * @return Directory containing the unpacked war. * @throws MojoExecutionException */ private File unpackWarToTempDirectory(Artifact artifact) throws MojoExecutionException { String name = artifact.getFile().getName(); File tempLocation = new File(workDirectory, name.substring(0, name.length() - 4)); boolean process = false; if (!tempLocation.exists()) { tempLocation.mkdirs(); process = true; } else if (artifact.getFile().lastModified() > tempLocation.lastModified()) { process = true; } if (process) { File file = artifact.getFile(); try { unpack(file, tempLocation); } catch (NoSuchArchiverException e) { this.getLog().info("Skip unpacking dependency file with unknown extension: " + file.getPath()); } } return tempLocation; } /** * Unpacks the archive file. * * @param file File to be unpacked. * @param location Location where to put the unpacked files. */ private void unpack(File file, File location) throws MojoExecutionException, NoSuchArchiverException { String archiveExt = FileUtils.getExtension(file.getAbsolutePath()).toLowerCase(); try { UnArchiver unArchiver = archiverManager.getUnArchiver(archiveExt); unArchiver.setSourceFile(file); unArchiver.setDestDirectory(location); unArchiver.extract(); } catch (IOException e) { throw new MojoExecutionException("Error unpacking file: " + file + "to: " + location, e); } catch (ArchiverException e) { throw new MojoExecutionException("Error unpacking file: " + file + "to: " + location, e); } } /** * Recursively copies contents of <tt>srcDir</tt> into <tt>targetDir</tt>. * This will not overwrite any existing files. * * @param srcDir Directory containing unpacked dependent war contents * @param targetDir Directory to overlay srcDir into */ private void copyDependentWarContents(File srcDir, File targetDir) throws MojoExecutionException { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(srcDir); scanner.setExcludes(getDependentWarExcludes()); scanner.addDefaultExcludes(); scanner.setIncludes(getDependentWarIncludes()); scanner.scan(); for (String dir : scanner.getIncludedDirectories()) { new File(targetDir, dir).mkdirs(); } for (String file : scanner.getIncludedFiles()) { File targetFile = new File(targetDir, file); // Do not overwrite existing files. if (!targetFile.exists()) { try { targetFile.getParentFile().mkdirs(); copyFileIfModified(new File(srcDir, file), targetFile); } catch (IOException e) { throw new MojoExecutionException("Error copying file '" + file + "' to '" + targetFile + "'", e); } } } } /** * Returns a list of filenames that should be copied * over to the destination directory. * * @param sourceDir the directory to be scanned * @return the array of filenames, relative to the sourceDir */ private String[] getWarFiles(File sourceDir) { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(sourceDir); scanner.setExcludes(getExcludes()); scanner.addDefaultExcludes(); scanner.setIncludes(getIncludes()); scanner.scan(); return scanner.getIncludedFiles(); } /** * Returns a list of filenames that should be copied * over to the destination directory. * * @param resource the resource to be scanned * @return the array of filenames, relative to the sourceDir */ private String[] getWarFiles(Resource resource) { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(resource.getDirectory()); if (resource.getIncludes() != null && !resource.getIncludes().isEmpty()) { scanner.setIncludes((String[]) resource.getIncludes().toArray(EMPTY_STRING_ARRAY)); } else { scanner.setIncludes(DEFAULT_INCLUDES); } if (resource.getExcludes() != null && !resource.getExcludes().isEmpty()) { scanner.setExcludes((String[]) resource.getExcludes().toArray(EMPTY_STRING_ARRAY)); } scanner.addDefaultExcludes(); scanner.scan(); return scanner.getIncludedFiles(); } /** * Copy file from source to destination only if source is newer than the target file. * If <code>destinationDirectory</code> does not exist, it * (and any parent directories) will be created. If a file <code>source</code> in * <code>destinationDirectory</code> exists, it will be overwritten. * * @param source An existing <code>File</code> to copy. * @param destinationDirectory A directory to copy <code>source</code> into. * @throws java.io.FileNotFoundException if <code>source</code> isn't a normal file. * @throws IllegalArgumentException if <code>destinationDirectory</code> isn't a directory. * @throws java.io.IOException if <code>source</code> does not exist, the file in * <code>destinationDirectory</code> cannot be written to, or an IO error occurs during copying. * <p/> * TO DO: Remove this method when Maven moves to plexus-utils version 1.4 */ private static void copyFileToDirectoryIfModified(File source, File destinationDirectory) throws IOException { // TO DO: Remove this method and use the method in WarFileUtils when Maven 2 changes // to plexus-utils 1.2. if (destinationDirectory.exists() && !destinationDirectory.isDirectory()) { throw new IllegalArgumentException("Destination is not a directory"); } copyFileIfModified(source, new File(destinationDirectory, source.getName())); } private FilterWrapper[] getFilterWrappers() { return new FilterWrapper[]{ // support ${token} new FilterWrapper() { public Reader getReader(Reader fileReader, Properties filterProperties) { return new InterpolationFilterReader(fileReader, filterProperties, "${", "}"); } }, // support @token@ new FilterWrapper() { public Reader getReader(Reader fileReader, Properties filterProperties) { return new InterpolationFilterReader(fileReader, filterProperties, "@", "@"); } }}; } /** * @param from * @param to * @param encoding * @param wrappers * @param filterProperties * @throws IOException TO DO: Remove this method when Maven moves to plexus-utils version 1.4 */ private static void copyFilteredFile(File from, File to, String encoding, FilterWrapper[] wrappers, Properties filterProperties) throws IOException { // buffer so it isn't reading a byte at a time! Reader fileReader = null; Writer fileWriter = null; try { // fix for MWAR-36, ensures that the parent dir are created first to.getParentFile().mkdirs(); if (encoding == null || encoding.length() < 1) { fileReader = new BufferedReader(new FileReader(from)); fileWriter = new FileWriter(to); } else { FileInputStream instream = new FileInputStream(from); FileOutputStream outstream = new FileOutputStream(to); fileReader = new BufferedReader(new InputStreamReader(instream, encoding)); fileWriter = new OutputStreamWriter(outstream, encoding); } Reader reader = fileReader; for (FilterWrapper wrapper : wrappers) { reader = wrapper.getReader(reader, filterProperties); } IOUtil.copy(reader, fileWriter); } finally { IOUtil.close(fileReader); IOUtil.close(fileWriter); } } /** * Copy file from source to destination only if source timestamp is later than the destination timestamp. * The directories up to <code>destination</code> will be created if they don't already exist. * <code>destination</code> will be overwritten if it already exists. * * @param source An existing non-directory <code>File</code> to copy bytes from. * @param destination A non-directory <code>File</code> to write bytes to (possibly * overwriting). * @throws IOException if <code>source</code> does not exist, <code>destination</code> cannot be * written to, or an IO error occurs during copying. * @throws java.io.FileNotFoundException if <code>destination</code> is a directory * <p/> * TO DO: Remove this method when Maven moves to plexus-utils version 1.4 */ private static void copyFileIfModified(File source, File destination) throws IOException { // TO DO: Remove this method and use the method in WarFileUtils when Maven 2 changes // to plexus-utils 1.2. if (destination.lastModified() < source.lastModified()) { FileUtils.copyFile(source, destination); } } /** * Copies a entire directory structure but only source files with timestamp later than the destinations'. * <p/> * Note: * <ul> * <li>It will include empty directories. * <li>The <code>sourceDirectory</code> must exists. * </ul> * * @param sourceDirectory * @param destinationDirectory * @throws IOException TO DO: Remove this method when Maven moves to plexus-utils version 1.4 */ private static void copyDirectoryStructureIfModified(File sourceDirectory, File destinationDirectory) throws IOException { if (!sourceDirectory.exists()) { throw new IOException("Source directory doesn't exists (" + sourceDirectory.getAbsolutePath() + ")."); } String sourcePath = sourceDirectory.getAbsolutePath(); for (File file : sourceDirectory.listFiles()) { String dest = file.getAbsolutePath(); dest = dest.substring(sourcePath.length() + 1); File destination = new File(destinationDirectory, dest); if (file.isFile()) { destination = destination.getParentFile(); copyFileToDirectoryIfModified(file, destination); } else if (file.isDirectory()) { if (!destination.exists() && !destination.mkdirs()) { throw new IOException( "Could not create destination directory '" + destination.getAbsolutePath() + "'."); } copyDirectoryStructureIfModified(file, destination); } else { throw new IOException("Unknown file type: " + file.getAbsolutePath()); } } } /** * TO DO: Remove this interface when Maven moves to plexus-utils version 1.4 */ private interface FilterWrapper { Reader getReader(Reader fileReader, Properties filterProperties); } /** * Converts the filename of an artifact to artifactId-version.type format. * * @param artifact * @return converted filename of the artifact */ private String getDefaultFinalName(Artifact artifact) { return artifact.getArtifactId() + "-" + artifact.getVersion() + "." + artifact.getArtifactHandler().getExtension(); } protected void setAttributes(Section mainSection) throws MojoExecutionException, ManifestException { JavaClass javaClass = findPluginClass(); if(javaClass==null) throw new MojoExecutionException("Unable to find a plugin class. Did you put @plugin in javadoc?"); mainSection.addAttributeAndCheck(new Attribute("Plugin-Class", javaClass.getPackage()+"."+javaClass.getName())); mainSection.addAttributeAndCheck(new Attribute("Long-Name",pluginName)); String v = project.getVersion(); if(v.endsWith("-SNAPSHOT")) { String dt = new SimpleDateFormat("MM/dd/yyyy hh:mm").format(new Date()); v += " (private-"+dt+"-"+System.getProperty("user.name")+")"; } mainSection.addAttributeAndCheck(new Attribute("Plugin-Version",v)); String dep = findDependencyProjects(); if(dep.length()>0) mainSection.addAttributeAndCheck(new Attribute("Plugin-Dependencies",dep)); } /** * Find a class that has "@plugin" marker. */ private JavaClass findPluginClass() { JavaDocBuilder builder = new JavaDocBuilder(); for (Object o : project.getCompileSourceRoots()) builder.addSourceTree(new File((String) o)); // look for a class that extends Plugin for( JavaSource js : builder.getSources() ) { JavaClass jc = js.getClasses()[0]; if(jc.getTagByName("plugin")!=null) return jc; } return null; } /** * Finds and lists dependency plugins. */ private String findDependencyProjects() { StringBuilder buf = new StringBuilder(); for(Object o : project.getArtifacts()) { Artifact a = (Artifact)o; if(a.getType().equals("hpi")) { if(buf.length()>0) buf.append(' '); buf.append(a.getArtifactId()); buf.append(':'); buf.append(a.getVersion()); } } return buf.toString(); } }
src/main/java/org/jvnet/hudson/maven/plugins/hpi/AbstractHpiMojo.java
package org.jvnet.hudson.maven.plugins.hpi; /* * Copyright 2001-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DependencyResolutionRequiredException; import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter; import org.apache.maven.model.Resource; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; import org.apache.maven.archiver.MavenArchiver; import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.archiver.UnArchiver; import org.codehaus.plexus.archiver.jar.Manifest; import org.codehaus.plexus.archiver.jar.ManifestException; import org.codehaus.plexus.archiver.jar.Manifest.Section; import org.codehaus.plexus.archiver.jar.Manifest.Attribute; import org.codehaus.plexus.archiver.manager.ArchiverManager; import org.codehaus.plexus.archiver.manager.NoSuchArchiverException; import org.codehaus.plexus.util.DirectoryScanner; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.InterpolationFilterReader; import org.codehaus.plexus.util.StringUtils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.Date; import java.text.SimpleDateFormat; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaSource; import com.thoughtworks.qdox.JavaDocBuilder; public abstract class AbstractHpiMojo extends AbstractMojo { /** * The directory for the generated WAR. * * @parameter expression="${project.build.directory}" * @required */ protected String outputDirectory; /** * The maven project. * * @parameter expression="${project}" * @required * @readonly */ protected MavenProject project; /** * The directory containing generated classes. * * @parameter expression="${project.build.outputDirectory}" * @required * @readonly */ private File classesDirectory; /** * Name of the plugin that Hudson uses for display purpose. * It should be one line text. * * @parameter expression="${project.name}" * @required * @readonly */ protected String pluginName; /** * The directory where the webapp is built. * * @parameter expression="${project.build.directory}/${project.build.finalName}" * @required */ private File webappDirectory; /** * Single directory for extra files to include in the WAR. * * @parameter expression="${basedir}/src/main/webapp" * @required */ protected File warSourceDirectory; /** * The list of webResources we want to transfer. * * @parameter */ private Resource[] webResources; /** * @parameter expression="${project.build.filters}" */ private List<String> filters; /** * The path to the context.xml file to use. * * @parameter expression="${maven.war.containerConfigXML}" */ private File containerConfigXML; /** * Directory to unpack dependent WARs into if needed * * @parameter expression="${project.build.directory}/war/work" * @required */ private File workDirectory; /** * To look up Archiver/UnArchiver implementations * * @parameter expression="${component.org.codehaus.plexus.archiver.manager.ArchiverManager}" * @required */ protected ArchiverManager archiverManager; private static final String WEB_INF = "WEB-INF"; private static final String META_INF = "META-INF"; private static final String[] DEFAULT_INCLUDES = {"**/**"}; /** * The comma separated list of tokens to include in the WAR. * Default is '**'. * * @parameter alias="includes" */ private String warSourceIncludes = "**"; /** * The comma separated list of tokens to exclude from the WAR. * * @parameter alias="excludes" */ private String warSourceExcludes; /** * The comma separated list of tokens to include when doing * a war overlay. * Default is '**' * * @parameter */ private String dependentWarIncludes = "**"; /** * The comma separated list of tokens to exclude when doing * a way overlay. * * @parameter */ private String dependentWarExcludes; private static final String[] EMPTY_STRING_ARRAY = {}; public File getClassesDirectory() { return classesDirectory; } public void setClassesDirectory(File classesDirectory) { this.classesDirectory = classesDirectory; } public File getWebappDirectory() { return webappDirectory; } public void setWebappDirectory(File webappDirectory) { this.webappDirectory = webappDirectory; } public void setWarSourceDirectory(File warSourceDirectory) { this.warSourceDirectory = warSourceDirectory; } public File getContainerConfigXML() { return containerConfigXML; } public void setContainerConfigXML(File containerConfigXML) { this.containerConfigXML = containerConfigXML; } /** * Returns a string array of the excludes to be used * when assembling/copying the war. * * @return an array of tokens to exclude */ protected String[] getExcludes() { List<String> excludeList = new ArrayList<String>(); if (StringUtils.isNotEmpty(warSourceExcludes)) { excludeList.addAll(Arrays.asList(StringUtils.split(warSourceExcludes, ","))); } // if contextXML is specified, omit the one in the source directory if (containerConfigXML != null && StringUtils.isNotEmpty(containerConfigXML.getName())) { excludeList.add("**/" + META_INF + "/" + containerConfigXML.getName()); } return excludeList.toArray(EMPTY_STRING_ARRAY); } /** * Returns a string array of the includes to be used * when assembling/copying the war. * * @return an array of tokens to include */ protected String[] getIncludes() { return StringUtils.split(StringUtils.defaultString(warSourceIncludes), ","); } /** * Returns a string array of the excludes to be used * when adding dependent wars as an overlay onto this war. * * @return an array of tokens to exclude */ protected String[] getDependentWarExcludes() { String[] excludes; if (StringUtils.isNotEmpty(dependentWarExcludes)) { excludes = StringUtils.split(dependentWarExcludes, ","); } else { excludes = EMPTY_STRING_ARRAY; } return excludes; } /** * Returns a string array of the includes to be used * when adding dependent wars as an overlay onto this war. * * @return an array of tokens to include */ protected String[] getDependentWarIncludes() { return StringUtils.split(StringUtils.defaultString(dependentWarIncludes), ","); } public void buildExplodedWebapp(File webappDirectory) throws MojoExecutionException { getLog().info("Exploding webapp..."); webappDirectory.mkdirs(); File webinfDir = new File(webappDirectory, WEB_INF); webinfDir.mkdirs(); File metainfDir = new File(webappDirectory, META_INF); metainfDir.mkdirs(); try { List<Resource> webResources = this.webResources != null ? Arrays.asList(this.webResources) : null; if (webResources != null && webResources.size() > 0) { Properties filterProperties = getBuildFilterProperties(); for (Resource resource : webResources) { copyResources(resource, webappDirectory, filterProperties); } } copyResources(warSourceDirectory, webappDirectory); if (containerConfigXML != null && StringUtils.isNotEmpty(containerConfigXML.getName())) { metainfDir = new File(webappDirectory, META_INF); String xmlFileName = containerConfigXML.getName(); copyFileIfModified(containerConfigXML, new File(metainfDir, xmlFileName)); } buildWebapp(project, webappDirectory); } catch (IOException e) { throw new MojoExecutionException("Could not explode webapp...", e); } } private Properties getBuildFilterProperties() throws MojoExecutionException { // System properties Properties filterProperties = new Properties(System.getProperties()); // Project properties filterProperties.putAll(project.getProperties()); for (String filter : filters) { try { Properties properties = PropertyUtils.loadPropertyFile(new File(filter), true, true); filterProperties.putAll(properties); } catch (IOException e) { throw new MojoExecutionException("Error loading property file '" + filter + "'", e); } } return filterProperties; } /** * Copies webapp webResources from the specified directory. * <p/> * Note that the <tt>webXml</tt> parameter could be null and may * specify a file which is not named <tt>web.xml<tt>. If the file * exists, it will be copied to the <tt>META-INF</tt> directory and * renamed accordingly. * * @param resource the resource to copy * @param webappDirectory the target directory * @param filterProperties * @throws java.io.IOException if an error occurred while copying webResources */ public void copyResources(Resource resource, File webappDirectory, Properties filterProperties) throws IOException { if (!resource.getDirectory().equals(webappDirectory.getPath())) { getLog().info("Copy webapp webResources to " + webappDirectory.getAbsolutePath()); if (webappDirectory.exists()) { String[] fileNames = getWarFiles(resource); for (String fileName : fileNames) { if (resource.isFiltering()) { copyFilteredFile(new File(resource.getDirectory(), fileName), new File(webappDirectory, fileName), null, getFilterWrappers(), filterProperties); } else { copyFileIfModified(new File(resource.getDirectory(), fileName), new File(webappDirectory, fileName)); } } } } } /** * Copies webapp webResources from the specified directory. * <p/> * Note that the <tt>webXml</tt> parameter could be null and may * specify a file which is not named <tt>web.xml<tt>. If the file * exists, it will be copied to the <tt>META-INF</tt> directory and * renamed accordingly. * * @param sourceDirectory the source directory * @param webappDirectory the target directory * @throws java.io.IOException if an error occurred while copying webResources */ public void copyResources(File sourceDirectory, File webappDirectory) throws IOException { if (!sourceDirectory.equals(webappDirectory)) { getLog().info("Copy webapp webResources to " + webappDirectory.getAbsolutePath()); if (warSourceDirectory.exists()) { String[] fileNames = getWarFiles(sourceDirectory); for (String fileName : fileNames) { copyFileIfModified(new File(sourceDirectory, fileName), new File(webappDirectory, fileName)); } } } } /** * Builds the webapp for the specified project. * <p/> * Classes, libraries and tld files are copied to * the <tt>webappDirectory</tt> during this phase. * * @param project the maven project * @param webappDirectory * @throws java.io.IOException if an error occurred while building the webapp */ public void buildWebapp(MavenProject project, File webappDirectory) throws MojoExecutionException, IOException { getLog().info("Assembling webapp " + project.getArtifactId() + " in " + webappDirectory); File libDirectory = new File(webappDirectory, WEB_INF + "/lib"); File tldDirectory = new File(webappDirectory, WEB_INF + "/tld"); File webappClassesDirectory = new File(webappDirectory, WEB_INF + "/classes"); if (classesDirectory.exists() && !classesDirectory.equals(webappClassesDirectory)) { copyDirectoryStructureIfModified(classesDirectory, webappClassesDirectory); } Set<Artifact> artifacts = project.getArtifacts(); List duplicates = findDuplicates(artifacts); List<File> dependentWarDirectories = new ArrayList<File>(); for (Artifact artifact : artifacts) { String targetFileName = getDefaultFinalName(artifact); getLog().debug("Processing: " + targetFileName); if (duplicates.contains(targetFileName)) { getLog().debug("Duplicate found: " + targetFileName); targetFileName = artifact.getGroupId() + "-" + targetFileName; getLog().debug("Renamed to: " + targetFileName); } // TODO: utilise appropriate methods from project builder ScopeArtifactFilter filter = new ScopeArtifactFilter(Artifact.SCOPE_RUNTIME); if (!artifact.isOptional() && filter.include(artifact)) { String type = artifact.getType(); if ("tld".equals(type)) { copyFileIfModified(artifact.getFile(), new File(tldDirectory, targetFileName)); } else { if ("jar".equals(type) || "ejb".equals(type) || "ejb-client".equals(type)) { copyFileIfModified(artifact.getFile(), new File(libDirectory, targetFileName)); } else { if ("par".equals(type)) { targetFileName = targetFileName.substring(0, targetFileName.lastIndexOf('.')) + ".jar"; getLog().debug( "Copying " + artifact.getFile() + " to " + new File(libDirectory, targetFileName)); copyFileIfModified(artifact.getFile(), new File(libDirectory, targetFileName)); } else { if ("war".equals(type)) { dependentWarDirectories.add(unpackWarToTempDirectory(artifact)); } else { getLog().debug("Skipping artifact of type " + type + " for WEB-INF/lib"); } } } } } } if (dependentWarDirectories.size() > 0) { getLog().info("Overlaying " + dependentWarDirectories.size() + " war(s)."); // overlay dependent wars for (Iterator iter = dependentWarDirectories.iterator(); iter.hasNext();) { copyDependentWarContents((File) iter.next(), webappDirectory); } } } /** * Searches a set of artifacts for duplicate filenames and returns a list of duplicates. * * @param artifacts set of artifacts * @return List of duplicated artifacts */ private List<String> findDuplicates(Set<Artifact> artifacts) { List<String> duplicates = new ArrayList<String>(); List<String> identifiers = new ArrayList<String>(); for (Artifact artifact : artifacts) { String candidate = getDefaultFinalName(artifact); if (identifiers.contains(candidate)) { duplicates.add(candidate); } else { identifiers.add(candidate); } } return duplicates; } /** * Unpacks war artifacts into a temporary directory inside <tt>workDirectory</tt> * named with the name of the war. * * @param artifact War artifact to unpack. * @return Directory containing the unpacked war. * @throws MojoExecutionException */ private File unpackWarToTempDirectory(Artifact artifact) throws MojoExecutionException { String name = artifact.getFile().getName(); File tempLocation = new File(workDirectory, name.substring(0, name.length() - 4)); boolean process = false; if (!tempLocation.exists()) { tempLocation.mkdirs(); process = true; } else if (artifact.getFile().lastModified() > tempLocation.lastModified()) { process = true; } if (process) { File file = artifact.getFile(); try { unpack(file, tempLocation); } catch (NoSuchArchiverException e) { this.getLog().info("Skip unpacking dependency file with unknown extension: " + file.getPath()); } } return tempLocation; } /** * Unpacks the archive file. * * @param file File to be unpacked. * @param location Location where to put the unpacked files. */ private void unpack(File file, File location) throws MojoExecutionException, NoSuchArchiverException { String archiveExt = FileUtils.getExtension(file.getAbsolutePath()).toLowerCase(); try { UnArchiver unArchiver = archiverManager.getUnArchiver(archiveExt); unArchiver.setSourceFile(file); unArchiver.setDestDirectory(location); unArchiver.extract(); } catch (IOException e) { throw new MojoExecutionException("Error unpacking file: " + file + "to: " + location, e); } catch (ArchiverException e) { throw new MojoExecutionException("Error unpacking file: " + file + "to: " + location, e); } } /** * Recursively copies contents of <tt>srcDir</tt> into <tt>targetDir</tt>. * This will not overwrite any existing files. * * @param srcDir Directory containing unpacked dependent war contents * @param targetDir Directory to overlay srcDir into */ private void copyDependentWarContents(File srcDir, File targetDir) throws MojoExecutionException { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(srcDir); scanner.setExcludes(getDependentWarExcludes()); scanner.addDefaultExcludes(); scanner.setIncludes(getDependentWarIncludes()); scanner.scan(); for (String dir : scanner.getIncludedDirectories()) { new File(targetDir, dir).mkdirs(); } for (String file : scanner.getIncludedFiles()) { File targetFile = new File(targetDir, file); // Do not overwrite existing files. if (!targetFile.exists()) { try { targetFile.getParentFile().mkdirs(); copyFileIfModified(new File(srcDir, file), targetFile); } catch (IOException e) { throw new MojoExecutionException("Error copying file '" + file + "' to '" + targetFile + "'", e); } } } } /** * Returns a list of filenames that should be copied * over to the destination directory. * * @param sourceDir the directory to be scanned * @return the array of filenames, relative to the sourceDir */ private String[] getWarFiles(File sourceDir) { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(sourceDir); scanner.setExcludes(getExcludes()); scanner.addDefaultExcludes(); scanner.setIncludes(getIncludes()); scanner.scan(); return scanner.getIncludedFiles(); } /** * Returns a list of filenames that should be copied * over to the destination directory. * * @param resource the resource to be scanned * @return the array of filenames, relative to the sourceDir */ private String[] getWarFiles(Resource resource) { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(resource.getDirectory()); if (resource.getIncludes() != null && !resource.getIncludes().isEmpty()) { scanner.setIncludes((String[]) resource.getIncludes().toArray(EMPTY_STRING_ARRAY)); } else { scanner.setIncludes(DEFAULT_INCLUDES); } if (resource.getExcludes() != null && !resource.getExcludes().isEmpty()) { scanner.setExcludes((String[]) resource.getExcludes().toArray(EMPTY_STRING_ARRAY)); } scanner.addDefaultExcludes(); scanner.scan(); return scanner.getIncludedFiles(); } /** * Copy file from source to destination only if source is newer than the target file. * If <code>destinationDirectory</code> does not exist, it * (and any parent directories) will be created. If a file <code>source</code> in * <code>destinationDirectory</code> exists, it will be overwritten. * * @param source An existing <code>File</code> to copy. * @param destinationDirectory A directory to copy <code>source</code> into. * @throws java.io.FileNotFoundException if <code>source</code> isn't a normal file. * @throws IllegalArgumentException if <code>destinationDirectory</code> isn't a directory. * @throws java.io.IOException if <code>source</code> does not exist, the file in * <code>destinationDirectory</code> cannot be written to, or an IO error occurs during copying. * <p/> * TO DO: Remove this method when Maven moves to plexus-utils version 1.4 */ private static void copyFileToDirectoryIfModified(File source, File destinationDirectory) throws IOException { // TO DO: Remove this method and use the method in WarFileUtils when Maven 2 changes // to plexus-utils 1.2. if (destinationDirectory.exists() && !destinationDirectory.isDirectory()) { throw new IllegalArgumentException("Destination is not a directory"); } copyFileIfModified(source, new File(destinationDirectory, source.getName())); } private FilterWrapper[] getFilterWrappers() { return new FilterWrapper[]{ // support ${token} new FilterWrapper() { public Reader getReader(Reader fileReader, Properties filterProperties) { return new InterpolationFilterReader(fileReader, filterProperties, "${", "}"); } }, // support @token@ new FilterWrapper() { public Reader getReader(Reader fileReader, Properties filterProperties) { return new InterpolationFilterReader(fileReader, filterProperties, "@", "@"); } }}; } /** * @param from * @param to * @param encoding * @param wrappers * @param filterProperties * @throws IOException TO DO: Remove this method when Maven moves to plexus-utils version 1.4 */ private static void copyFilteredFile(File from, File to, String encoding, FilterWrapper[] wrappers, Properties filterProperties) throws IOException { // buffer so it isn't reading a byte at a time! Reader fileReader = null; Writer fileWriter = null; try { // fix for MWAR-36, ensures that the parent dir are created first to.getParentFile().mkdirs(); if (encoding == null || encoding.length() < 1) { fileReader = new BufferedReader(new FileReader(from)); fileWriter = new FileWriter(to); } else { FileInputStream instream = new FileInputStream(from); FileOutputStream outstream = new FileOutputStream(to); fileReader = new BufferedReader(new InputStreamReader(instream, encoding)); fileWriter = new OutputStreamWriter(outstream, encoding); } Reader reader = fileReader; for (FilterWrapper wrapper : wrappers) { reader = wrapper.getReader(reader, filterProperties); } IOUtil.copy(reader, fileWriter); } finally { IOUtil.close(fileReader); IOUtil.close(fileWriter); } } /** * Copy file from source to destination only if source timestamp is later than the destination timestamp. * The directories up to <code>destination</code> will be created if they don't already exist. * <code>destination</code> will be overwritten if it already exists. * * @param source An existing non-directory <code>File</code> to copy bytes from. * @param destination A non-directory <code>File</code> to write bytes to (possibly * overwriting). * @throws IOException if <code>source</code> does not exist, <code>destination</code> cannot be * written to, or an IO error occurs during copying. * @throws java.io.FileNotFoundException if <code>destination</code> is a directory * <p/> * TO DO: Remove this method when Maven moves to plexus-utils version 1.4 */ private static void copyFileIfModified(File source, File destination) throws IOException { // TO DO: Remove this method and use the method in WarFileUtils when Maven 2 changes // to plexus-utils 1.2. if (destination.lastModified() < source.lastModified()) { FileUtils.copyFile(source, destination); } } /** * Copies a entire directory structure but only source files with timestamp later than the destinations'. * <p/> * Note: * <ul> * <li>It will include empty directories. * <li>The <code>sourceDirectory</code> must exists. * </ul> * * @param sourceDirectory * @param destinationDirectory * @throws IOException TO DO: Remove this method when Maven moves to plexus-utils version 1.4 */ private static void copyDirectoryStructureIfModified(File sourceDirectory, File destinationDirectory) throws IOException { if (!sourceDirectory.exists()) { throw new IOException("Source directory doesn't exists (" + sourceDirectory.getAbsolutePath() + ")."); } String sourcePath = sourceDirectory.getAbsolutePath(); for (File file : sourceDirectory.listFiles()) { String dest = file.getAbsolutePath(); dest = dest.substring(sourcePath.length() + 1); File destination = new File(destinationDirectory, dest); if (file.isFile()) { destination = destination.getParentFile(); copyFileToDirectoryIfModified(file, destination); } else if (file.isDirectory()) { if (!destination.exists() && !destination.mkdirs()) { throw new IOException( "Could not create destination directory '" + destination.getAbsolutePath() + "'."); } copyDirectoryStructureIfModified(file, destination); } else { throw new IOException("Unknown file type: " + file.getAbsolutePath()); } } } /** * TO DO: Remove this interface when Maven moves to plexus-utils version 1.4 */ private interface FilterWrapper { Reader getReader(Reader fileReader, Properties filterProperties); } /** * Converts the filename of an artifact to artifactId-version.type format. * * @param artifact * @return converted filename of the artifact */ private String getDefaultFinalName(Artifact artifact) { return artifact.getArtifactId() + "-" + artifact.getVersion() + "." + artifact.getArtifactHandler().getExtension(); } protected void setAttributes(Section mainSection) throws MojoExecutionException, ManifestException { JavaClass javaClass = findPluginClass(); if(javaClass==null) throw new MojoExecutionException("Unable to find a plugin class. Did you put @plugin in javadoc?"); mainSection.addAttributeAndCheck(new Attribute("Plugin-Class", javaClass.getPackage()+"."+javaClass.getName())); mainSection.addAttributeAndCheck(new Attribute("Long-Name",pluginName)); String v = project.getVersion(); if(v.endsWith("-SNAPSHOT")) { String dt = new SimpleDateFormat("MM/dd/yyyy hh:mm").format(new Date()); v += " (private-"+dt+"-"+System.getProperty("user.name")+")"; } mainSection.addAttributeAndCheck(new Attribute("Plugin-Version",v)); } /** * Find a class that has "@plugin" marker. */ private JavaClass findPluginClass() { JavaDocBuilder builder = new JavaDocBuilder(); for (Object o : project.getCompileSourceRoots()) builder.addSourceTree(new File((String) o)); // look for a class that extends Plugin for( JavaSource js : builder.getSources() ) { JavaClass jc = js.getClasses()[0]; if(jc.getTagByName("plugin")!=null) return jc; } return null; } }
added "Plugin-Dependencies" entry
src/main/java/org/jvnet/hudson/maven/plugins/hpi/AbstractHpiMojo.java
added "Plugin-Dependencies" entry
<ide><path>rc/main/java/org/jvnet/hudson/maven/plugins/hpi/AbstractHpiMojo.java <ide> * limitations under the License. <ide> */ <ide> <add>import com.thoughtworks.qdox.JavaDocBuilder; <add>import com.thoughtworks.qdox.model.JavaClass; <add>import com.thoughtworks.qdox.model.JavaSource; <ide> import org.apache.maven.artifact.Artifact; <del>import org.apache.maven.artifact.DependencyResolutionRequiredException; <ide> import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter; <ide> import org.apache.maven.model.Resource; <ide> import org.apache.maven.plugin.AbstractMojo; <ide> import org.apache.maven.plugin.MojoExecutionException; <ide> import org.apache.maven.project.MavenProject; <del>import org.apache.maven.archiver.MavenArchiver; <ide> import org.codehaus.plexus.archiver.ArchiverException; <ide> import org.codehaus.plexus.archiver.UnArchiver; <del>import org.codehaus.plexus.archiver.jar.Manifest; <add>import org.codehaus.plexus.archiver.jar.Manifest.Attribute; <add>import org.codehaus.plexus.archiver.jar.Manifest.Section; <ide> import org.codehaus.plexus.archiver.jar.ManifestException; <del>import org.codehaus.plexus.archiver.jar.Manifest.Section; <del>import org.codehaus.plexus.archiver.jar.Manifest.Attribute; <ide> import org.codehaus.plexus.archiver.manager.ArchiverManager; <ide> import org.codehaus.plexus.archiver.manager.NoSuchArchiverException; <ide> import org.codehaus.plexus.util.DirectoryScanner; <ide> import java.io.OutputStreamWriter; <ide> import java.io.Reader; <ide> import java.io.Writer; <del>import java.io.PrintWriter; <add>import java.text.SimpleDateFormat; <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <add>import java.util.Date; <ide> import java.util.Iterator; <ide> import java.util.List; <ide> import java.util.Properties; <ide> import java.util.Set; <del>import java.util.Date; <del>import java.text.SimpleDateFormat; <del> <del>import com.thoughtworks.qdox.model.JavaClass; <del>import com.thoughtworks.qdox.model.JavaSource; <del>import com.thoughtworks.qdox.JavaDocBuilder; <ide> <ide> public abstract class AbstractHpiMojo extends AbstractMojo { <ide> /** <ide> String dt = new SimpleDateFormat("MM/dd/yyyy hh:mm").format(new Date()); <ide> v += " (private-"+dt+"-"+System.getProperty("user.name")+")"; <ide> } <del> <ide> mainSection.addAttributeAndCheck(new Attribute("Plugin-Version",v)); <ide> <add> String dep = findDependencyProjects(); <add> if(dep.length()>0) <add> mainSection.addAttributeAndCheck(new Attribute("Plugin-Dependencies",dep)); <ide> } <ide> <ide> /** <ide> } <ide> return null; <ide> } <add> <add> /** <add> * Finds and lists dependency plugins. <add> */ <add> private String findDependencyProjects() { <add> StringBuilder buf = new StringBuilder(); <add> for(Object o : project.getArtifacts()) { <add> Artifact a = (Artifact)o; <add> if(a.getType().equals("hpi")) { <add> if(buf.length()>0) <add> buf.append(' '); <add> buf.append(a.getArtifactId()); <add> buf.append(':'); <add> buf.append(a.getVersion()); <add> } <add> } <add> return buf.toString(); <add> } <ide> }